| Safe Haskell | None |
|---|---|
| Language | GHC2021 |
LibP2P
Description
hs-libp2p: Haskell implementation of the libp2p networking stack.
This is the public API facade for the library. Import this module for the common types and functions needed to build a libp2p node:
import LibP2P main :: IO () main = do (pid, kp) <- generateAndPeerId sw <- newSwitch pid kp tcp <- newTCPTransport addTransport sw tcp registerIdentifyHandlers sw registerPingHandler sw (_relayState, _circuitState, _natServices) <- registerNATHandlers sw defaultNATConfig addrs <- switchListen sw defaultConnectionGater [fromText "ip4127.0.0.1tcp0"] print addrs -- ... dial other peers, etc. switchClose sw
Synopsis
- data PeerId
- data KeyPair
- generateKeyPair :: IO (Either String KeyPair)
- fromPublicKey :: PublicKey -> PeerId
- peerIdBytes :: PeerId -> ByteString
- toBase58 :: PeerId -> Text
- parsePeerId :: Text -> Either String PeerId
- toCIDv1 :: PeerId -> Text
- newtype Multiaddr = Multiaddr [Protocol]
- data Protocol
- = IP4 !Word32
- | IP6 !ByteString
- | TCP !Word16
- | UDP !Word16
- | P2P !ByteString
- | Certhash !ByteString
- | QuicV1
- | WS
- | WSS
- | DNS !Text
- | DNS4 !Text
- | DNS6 !Text
- | DNSAddr !Text
- | P2PCircuit
- | WebRTCDirect
- | WebRTC
- | WebTransport
- | NoiseProto
- splitP2P :: Multiaddr -> Maybe (Multiaddr, PeerId)
- toText :: Multiaddr -> Text
- fromText :: Text -> Either String Multiaddr
- data Switch
- data Direction
- newSwitch :: PeerId -> KeyPair -> IO Switch
- newSwitchWithConfig :: SwitchConfig -> PeerId -> KeyPair -> IO Switch
- data SwitchConfig = SwitchConfig {}
- defaultSwitchConfig :: SwitchConfig
- data YamuxConfig = YamuxConfig {
- ycKeepAlive :: !(Maybe Micros)
- ycPingTimeout :: !Micros
- defaultYamuxConfig :: YamuxConfig
- data Micros
- mkMicros :: Int -> Maybe Micros
- microsToInt :: Micros -> Int
- subscribeSwitchEvents :: Switch -> IO (TChan SwitchEvent)
- data SwitchEvent
- addTransport :: Switch -> Transport -> IO ()
- switchListen :: Switch -> ConnectionGater -> [Multiaddr] -> IO [Multiaddr]
- switchListenAddrs :: Switch -> IO [Multiaddr]
- switchClose :: Switch -> IO ()
- dial :: Switch -> PeerId -> [Multiaddr] -> IO (Either DialError Connection)
- closeConnection :: Switch -> Connection -> IO ()
- newStream :: Switch -> Connection -> IO (Either StreamOpenError StreamIO)
- newStreamAllowingLimited :: Switch -> Connection -> IO (Either StreamOpenError StreamIO)
- data StreamOpenError
- data RelayCircuitLimit = RelayCircuitLimit {
- rclDurationSeconds :: !(Maybe Word32)
- rclDataBytes :: !(Maybe Word64)
- data RelayCircuitExhausted
- data DialError
- data ResourceError
- setStreamHandler :: Switch -> ProtocolId -> StreamHandler -> IO ()
- removeStreamHandler :: Switch -> ProtocolId -> IO ()
- data StreamIO = StreamIO {
- streamWrite :: ByteString -> IO ()
- streamReadByte :: IO Word8
- streamReadChunk :: Int -> IO ByteString
- streamClose :: IO ()
- type StreamHandler = Connection -> StreamIO -> IO ()
- type ProtocolId = Text
- data Connection = Connection {}
- data Transport = Transport {
- transportDial :: !(Multiaddr -> IO RawConnection)
- transportDialFrom :: !(Maybe Multiaddr -> Multiaddr -> IO RawConnection)
- transportListen :: !(Multiaddr -> IO Listener)
- transportCanDial :: !(Multiaddr -> Bool)
- newTCPTransport :: IO Transport
- data WebSocketConfig = WebSocketConfig {}
- defaultWebSocketConfig :: IO WebSocketConfig
- webSocketServerParams :: Credential -> ServerParams
- newWebSocketTransport :: IO Transport
- newWebSocketTransportWithConfig :: WebSocketConfig -> IO Transport
- newWebTransportTransport :: KeyPair -> IO Transport
- newQUICTransport :: KeyPair -> IO Transport
- data ConnectionGater = ConnectionGater {
- gateAccept :: !(Multiaddr -> IO Bool)
- gateDialAddr :: !(Multiaddr -> IO Bool)
- gateSecured :: !(PeerId -> IO Bool)
- defaultConnectionGater :: ConnectionGater
- setConnectionGater :: Switch -> ConnectionGater -> IO ()
- registerIdentifyHandlers :: Switch -> IO ()
- requestIdentify :: Switch -> Connection -> IO (Either String IdentifyInfo)
- identifyPeer :: Switch -> Connection -> IO (Either String ())
- pushIdentify :: Switch -> IO ()
- registerPingHandler :: Switch -> IO ()
- sendPing :: Switch -> Connection -> IO (Either PingError PingResult)
- data PingSession
- openPingSession :: Switch -> Connection -> IO (Either PingError PingSession)
- ping :: PingSession -> IO (Either PingError PingResult)
- pingWithTimeout :: Int -> PingSession -> IO (Either PingError PingResult)
- closePingSession :: PingSession -> IO ()
- withPingSession :: Switch -> Connection -> (PingSession -> IO a) -> IO (Either PingError a)
- data PingResult = PingResult {}
- data PingError
- registerPerfHandler :: Switch -> IO ()
- runPerf :: Switch -> Connection -> Word64 -> Word64 -> IO (Either PerfError PerfResult)
- perfProtocolId :: Text
- data PerfResult = PerfResult {}
- data PerfError
- data DHTNode
- data DHTMode
- data Validator = Validator {
- valValidate :: ByteString -> ByteString -> Either String ()
- valSelect :: ByteString -> [ByteString] -> Either String Int
- defaultValidator :: Validator
- data DHTRecord
- recValue :: DHTRecord -> ByteString
- data ProviderEntry
- peProvider :: ProviderEntry -> PeerId
- peAddrs :: ProviderEntry -> [Multiaddr]
- data BucketEntry
- entryPeerId :: BucketEntry -> PeerId
- entryAddrs :: BucketEntry -> [Multiaddr]
- data DHTMaintenanceConfig = DHTMaintenanceConfig {}
- defaultDHTMaintenanceConfig :: DHTMaintenanceConfig
- newDHTNode :: Switch -> DHTMode -> IO DHTNode
- newDHTNodeWithConfig :: DHTMaintenanceConfig -> Switch -> DHTMode -> IO DHTNode
- stopDHTNode :: DHTNode -> IO ()
- registerDHTHandler :: DHTNode -> IO ()
- bootstrap :: DHTNode -> [PeerId] -> IO ()
- startBootstrap :: DHTNode -> [PeerId] -> Int -> IO ()
- provide :: DHTNode -> [Multiaddr] -> ByteString -> IO ()
- putValue :: DHTNode -> Validator -> ByteString -> ByteString -> IO (Either String ())
- getValue :: DHTNode -> Validator -> ByteString -> IO (Either String DHTRecord)
- findProviders :: DHTNode -> ByteString -> IO [ProviderEntry]
- findPeer :: DHTNode -> PeerId -> IO [BucketEntry]
- data DiscoveryEvent = DiscoveryEvent {
- discoveryPeerId :: !PeerId
- discoveryAddrs :: ![Multiaddr]
- newDiscoveryQueue :: IO (TQueue DiscoveryEvent)
- drainDiscoveryQueue :: TQueue DiscoveryEvent -> IO [DiscoveryEvent]
- data MDNSConfig = MDNSConfig {
- mcServiceName :: !Text
- mcPort :: !Word16
- mcAnnounceTTL :: !Word32
- mcAdvertiseInterval :: !Int
- mcAnnounceCount :: !Int
- mcAnnounceSpacingMs :: !Int
- mcMulticastLoopback :: !Bool
- mcBindIPv6 :: !Bool
- defaultMDNSConfig :: MDNSConfig
- data MDNSService = MDNSService {
- msConfig :: !MDNSConfig
- msSwitch :: !Switch
- msPeerName :: !Text
- msEvents :: !(TQueue DiscoveryEvent)
- msThreads :: [Async ()]
- msSockets :: [MDNSSocket]
- newMDNSService :: Switch -> MDNSConfig -> IO (Either String MDNSService)
- stopMDNSService :: MDNSService -> IO ()
- data RendezvousConfig = RendezvousConfig {
- rcMinTTL :: !Word64
- rcMaxTTL :: !Word64
- rcDefaultTTL :: !Word64
- rcMaxNamespaceLength :: !Int
- rcMaxPerPeer :: !Int
- rcMaxResults :: !Int
- defaultRendezvousConfig :: RendezvousConfig
- data RendezvousError
- registerRendezvousPoint :: Switch -> RendezvousConfig -> IO RendezvousPoint
- registeredCount :: RendezvousPoint -> IO Int
- registerSelf :: Switch -> Connection -> Text -> Maybe Word64 -> IO (Either RendezvousError Word64)
- unregisterSelf :: Switch -> Connection -> Text -> IO (Either RendezvousError ())
- discover :: Switch -> Connection -> Maybe Text -> DiscoverLimit -> ByteString -> IO (Either RendezvousError ([RegistrationInfo], ByteString))
- inspectRegistration :: RegistrationInfo -> Either String DiscoveryEvent
- pushDiscoverEvents :: TQueue DiscoveryEvent -> [RegistrationInfo] -> IO ()
- data NATConfig = NATConfig {}
- defaultNATConfig :: NATConfig
- data NATStatus
- data AutoNATClientConfig = AutoNATClientConfig {}
- defaultAutoNATClientConfig :: AutoNATClientConfig
- data AutoNATClientService
- data NATServices = NATServices {}
- startAutoNATClient :: Switch -> AutoNATClientConfig -> IO AutoNATClientService
- autoNATClientStatus :: AutoNATClientService -> IO NATStatus
- stopAutoNATClient :: AutoNATClientService -> IO ()
- registerNATHandlers :: Switch -> NATConfig -> IO (RelayState, CircuitState, NATServices)
- registerAutoNATHandler :: Switch -> IO ()
- registerAutoNATV2Handlers :: Switch -> AutoNATV2Config -> IO AutoNATV2State
- checkAutoNATV2 :: Switch -> AutoNATV2State -> Connection -> [AutoNATV2Request] -> IO (Either String AutoNATV2Result)
- data AutoNATV2Config = AutoNATV2Config {
- an2AllowPrivateAddrs :: !Bool
- an2ServerRPM :: !Int
- an2ServerPerPeerRPM :: !Int
- an2ServerDialDataRPM :: !Int
- an2MaxConcurrentPerPeer :: !Int
- an2MaxPeerAddresses :: !Int
- an2MinDialDataBytes :: !Word64
- an2MaxDialDataBytes :: !Word64
- an2MaxDialWaitMicros :: !Int
- an2DialBackWaitMicros :: !Int
- an2RandomWord64 :: !(IO Word64)
- an2Now :: !(IO POSIXTime)
- defaultAutoNATV2Config :: AutoNATV2Config
- data AutoNATV2State
- data AutoNATV2Request = AutoNATV2Request {}
- data AutoNATV2Result = AutoNATV2Result {
- an2ResultAddr :: !(Maybe Multiaddr)
- an2ResultIndex :: !(Maybe Int)
- an2ResultReachability :: !NATStatus
- an2AllAddrsRefused :: !Bool
- autoNATV2DialProtocolId :: Text
- autoNATV2DialBackProtocolId :: Text
- registerRelayHopHandler :: Switch -> RelayState -> IO ()
- registerRelayStopHandler :: Switch -> CircuitState -> IO ()
- registerDCUtRHandler :: Switch -> DCUtRUpgradeConfig -> IO ()
- data RelayState
- data RelayConfig = RelayConfig {}
- defaultRelayConfig :: RelayConfig
- newRelayState :: RelayConfig -> IO RelayState
- data CircuitState
- circuitTransport :: Switch -> CircuitState -> ReservationRefreshConfig -> Transport
- newCircuitState :: IO CircuitState
- data ReservationRefreshConfig = ReservationRefreshConfig {
- rrcMargin :: !POSIXTime
- rrcPollInterval :: !Int
- defaultReservationRefreshConfig :: ReservationRefreshConfig
- data GossipSubNode = GossipSubNode {
- gsnRouter :: !GossipSubRouter
- gsnSwitch :: !Switch
- gsnHeartbeat :: !(TVar (Maybe (Async ())))
- gsnStreams :: !(TVar (Map PeerId StreamIO))
- gsnStreamMeta :: !(TVar (Map PeerId GossipStreamMeta))
- gsnConnectHook :: !(IORef (Maybe (Connection -> IO ())))
- gsnDisconnectHook :: !(IORef (Maybe (Connection -> IO ())))
- gsnNotifierInstalled :: !(TVar Bool)
- gsnStarted :: !(TVar Bool)
- gsnLifecycleLock :: !(MVar ())
- gsnDirectSlots :: !DirectDialSlots
- gsnDirectConnect :: !(TVar (Maybe (Async ())))
- data GossipSubParams = GossipSubParams {
- paramD :: !Int
- paramDlo :: !Int
- paramDhi :: !Int
- paramDlazy :: !Int
- paramDscore :: !Int
- paramDout :: !Int
- paramHeartbeatInterval :: !NominalDiffTime
- paramFanoutTTL :: !NominalDiffTime
- paramSeenTTL :: !NominalDiffTime
- paramPruneBackoff :: !NominalDiffTime
- paramUnsubBackoff :: !NominalDiffTime
- paramGossipFactor :: !Double
- paramFloodPublish :: !Bool
- paramMessageIdFn :: !(PubSubMessage -> MessageId)
- paramSignaturePolicy :: !SignaturePolicy
- paramMcacheLen :: !Int
- paramMcacheGossip :: !Int
- paramPrunePeers :: !Int
- paramIWantFollowupTime :: !NominalDiffTime
- paramMaxIHaveLength :: !Int
- paramMaxIHaveMessages :: !Int
- paramMaxIDontWantLength :: !Int
- paramMaxIDontWantMessages :: !Int
- paramIDontWantMessageThreshold :: !Int
- paramIDontWantMessageTTL :: !Int
- paramDirectPeers :: !(Set PeerId)
- paramDirectConnectInterval :: !NominalDiffTime
- paramOpportunisticGraftTicks :: !Int
- paramOpportunisticGraftPeers :: !Int
- defaultGossipSubParams :: GossipSubParams
- newGossipSubNode :: Switch -> GossipSubParams -> IO GossipSubNode
- startGossipSub :: GossipSubNode -> IO ()
- stopGossipSub :: GossipSubNode -> IO ()
- enablePartialMessages :: GossipSubNode -> PartialMessagesExtension state -> IO (Either PartialMessagesError ())
- gossipJoin :: GossipSubNode -> Topic -> IO ()
- gossipJoinPartial :: GossipSubNode -> Topic -> PartialTopicMode -> IO (Either PartialMessagesError ())
- gossipLeave :: GossipSubNode -> Topic -> IO ()
- gossipPublish :: GossipSubNode -> Topic -> ByteString -> IO ()
- data PartialTopicMode
- data PartialMessage = PartialMessage {}
- data PartialMessagesExtension state
- data PartialMessagesConfig state = PartialMessagesConfig {
- partialInitialPeerState :: !state
- partialOnIncoming :: !(PeerId -> Map PeerId state -> PartialMessage -> IO (PartialCallbackResult state))
- partialOnEmitGossip :: !(Topic -> ByteString -> [PeerId] -> Map PeerId state -> IO (PartialCallbackResult state))
- partialGroupTTLHeartbeats :: !Int
- partialPeerGroupLimitPerTopic :: !Int
- partialPeerGroupLimitPerTopicPerPeer :: !Int
- data PartialCallbackResult state = PartialCallbackResult {
- partialUpdatedPeerStates :: !(Map PeerId state)
- partialPublishActions :: ![PartialPublishAction]
- data PartialPublishAction = PartialPublishAction {}
- type PartialPublishPlan state = Map PeerId state -> (PeerId -> Bool) -> IO (PartialCallbackResult state)
- data PartialMessagesError
- defaultPartialMessagesConfig :: state -> (PeerId -> Map PeerId state -> PartialMessage -> IO (PartialCallbackResult state)) -> (Topic -> ByteString -> [PeerId] -> Map PeerId state -> IO (PartialCallbackResult state)) -> PartialMessagesConfig state
- newPartialMessagesExtension :: PartialMessagesConfig state -> IO (PartialMessagesExtension state)
- partialMeshPeers :: PartialMessagesExtension state -> Topic -> IO (Either PartialMessagesError [PeerId])
- partialPeerRequests :: PartialMessagesExtension state -> PeerId -> Topic -> IO Bool
- publishPartial :: PartialMessagesExtension state -> Topic -> ByteString -> PartialPublishPlan state -> IO (Either PartialMessagesError ())
Identity
A Peer ID is a multihash of the serialized public key.
generateKeyPair :: IO (Either String KeyPair) Source #
Generate a new random Ed25519 key pair. Returns Left on cryptographic failure (should not occur with proper RNG).
fromPublicKey :: PublicKey -> PeerId Source #
Derive a Peer ID from a public key.
peerIdBytes :: PeerId -> ByteString Source #
Get the raw multihash bytes of a Peer ID.
parsePeerId :: Text -> Either String PeerId Source #
Parse a Peer ID from either a legacy base58btc multihash or CIDv1.
Legacy strings start with 1 or Qm. CIDv1 strings use a supported
multibase prefix: b (base32lower), B (base32upper), or z (base58btc).
toCIDv1 :: PeerId -> Text Source #
Encode a Peer ID as CIDv1 text (base32lower, no padding).
Format: b + base32lower(varint(1) + varint(0x72) + multihash_bytes)
Addressing
A multiaddr is a list of protocol components.
A single protocol component within a multiaddr.
Constructors
| IP4 !Word32 | IPv4 address (4 bytes big-endian) |
| IP6 !ByteString | IPv6 address (16 bytes) |
| TCP !Word16 | TCP port |
| UDP !Word16 | UDP port |
| P2P !ByteString | Peer ID as multihash bytes |
| Certhash !ByteString | TLS certificate fingerprint as multihash bytes |
| QuicV1 | QUIC v1 (no address) |
| WS | WebSocket (no address) |
| WSS | WebSocket Secure (no address) |
| DNS !Text | DNS hostname |
| DNS4 !Text | DNS4 hostname |
| DNS6 !Text | DNS6 hostname |
| DNSAddr !Text | DNSAddr hostname |
| P2PCircuit | Circuit relay marker (no address) |
| WebRTCDirect | ICE-lite WebRTC Direct (no address) |
| WebRTC | Relay-signaled WebRTC (no address) |
| WebTransport | WebTransport (no address) |
| NoiseProto | Noise protocol marker (no address) |
splitP2P :: Multiaddr -> Maybe (Multiaddr, PeerId) Source #
Split off the trailing p2ppeerId component from a multiaddr. Returns the transport address and the peer ID, or Nothing if the multiaddr does not end with a p2p component.
fromText :: Text -> Either String Multiaddr Source #
Parse a multiaddr from its text representation (e.g. "ip4127.0.0.1tcp4001").
Switch (central coordinator)
The Switch: central coordinator of the libp2p networking stack.
Manages transports, connection pool, protocol handlers, and events. All mutable state is STM-based for safe concurrent access.
Direction of a resource relative to this node.
newSwitch :: PeerId -> KeyPair -> IO Switch Source #
Create a new Switch with the given local identity. All internal state is initialized empty.
newSwitchWithConfig :: SwitchConfig -> PeerId -> KeyPair -> IO Switch Source #
Like newSwitch, with an explicit configuration.
data SwitchConfig Source #
Switch-wide settings, fixed when the Switch is created.
Constructors
| SwitchConfig | |
Fields
| |
Instances
| Show SwitchConfig Source # | |
Defined in LibP2P.Switch.Types Methods showsPrec :: Int -> SwitchConfig -> ShowS # show :: SwitchConfig -> String # showList :: [SwitchConfig] -> ShowS # | |
| Eq SwitchConfig Source # | |
Defined in LibP2P.Switch.Types | |
data YamuxConfig Source #
Session tunables that spec.md leaves to the implementation.
Constructors
| YamuxConfig | |
Fields
| |
Instances
| Show YamuxConfig Source # | |
Defined in LibP2P.Yamux.Types Methods showsPrec :: Int -> YamuxConfig -> ShowS # show :: YamuxConfig -> String # showList :: [YamuxConfig] -> ShowS # | |
| Eq YamuxConfig Source # | |
Defined in LibP2P.Yamux.Types | |
A strictly positive duration in microseconds.
mkMicros :: Int -> Maybe Micros Source #
Accept a positive number of microseconds, reject anything else.
microsToInt :: Micros -> Int Source #
The duration in microseconds, as System.Timeout.timeout takes it.
subscribeSwitchEvents :: Switch -> IO (TChan SwitchEvent) Source #
Subscribe independently to future per-connection events (no replay). Drop the channel to unsubscribe; unread channels retain queued events. Shutdown neither waits for subscribers nor signals end-of-stream.
data SwitchEvent Source #
Events emitted by the Switch for observability.
Constructors
| Connected !PeerId !Direction !Multiaddr | Connection fully upgraded |
| Disconnected !PeerId !Direction !Multiaddr | Connection closed |
Instances
| Show SwitchEvent Source # | |
Defined in LibP2P.Switch.Types Methods showsPrec :: Int -> SwitchEvent -> ShowS # show :: SwitchEvent -> String # showList :: [SwitchEvent] -> ShowS # | |
| Eq SwitchEvent Source # | |
Defined in LibP2P.Switch.Types | |
addTransport :: Switch -> Transport -> IO () Source #
Register a transport with the switch. Appends to the list of transports; order matters for selectTransport.
switchListen :: Switch -> ConnectionGater -> [Multiaddr] -> IO [Multiaddr] Source #
Start listening on the given addresses.
Stores the supplied gater on the Switch, then selects a transport for each address, binds a listener, and spawns an accept loop. The same policy applies to subsequent outbound dials. Returns the actual bound addresses. Fails if the switch is already closed.
switchListenAddrs :: Switch -> IO [Multiaddr] Source #
Get the current listen addresses from all active listeners.
switchClose :: Switch -> IO () Source #
Shut down the switch. Stops background services, cancels accept loops, closes listeners, and tears down all pooled connections.
dial :: Switch -> PeerId -> [Multiaddr] -> IO (Either DialError Connection) Source #
Dial a peer, reusing existing connections or establishing new ones.
Implements the full dial flow: 1. Pool reuse: return existing Open connection if available 2. Backoff check: reject if peer recently failed 3. Deduplication: coalesce concurrent dials to same peer via TMVar 4. Staggered parallel dial with 250ms delay (Happy Eyeballs) 5. First success: upgrade, add to pool, return 6. All fail: record backoff, return error
closeConnection :: Switch -> Connection -> IO () Source #
Tear down a connection: remove it from the pool, release its resource reservation, publish a Disconnected event, run the disconnect notifiers, and close the muxer session together with the underlying transport.
Idempotent: the state transition to ConnClosed is atomic, so concurrent calls (accept loop exit, explicit close, switchClose) perform the teardown exactly once, and the notifiers run once.
Notifiers run synchronously, after the pool removal has committed and before the muxer is closed, so a notifier that asks whether the peer still has a live connection (Circuit Relay v2 reservation cleanup) never sees the connection being torn down. Each is isolated so a failing notifier cannot abort the teardown.
newStream :: Switch -> Connection -> IO (Either StreamOpenError StreamIO) Source #
Open an outbound stream on a connection, reserving a stream slot against the peer's resource scope. The slot is released when the returned stream is closed (exactly once, even on double close).
Refuses a relay-limited connection. Protocols that must run over a
relay circuit (Identify, Ping, DCUtR) use newStreamAllowingLimited.
newStreamAllowingLimited :: Switch -> Connection -> IO (Either StreamOpenError StreamIO) Source #
Like newStream, but allows a relay-limited connection.
The circuit still dies when its budget is exhausted
(RelayCircuitExhausted). Opt in only for a
short exchange that can tolerate that.
data StreamOpenError Source #
Failure to open an outbound stream.
Constructors
| StreamResourceLimit !ResourceError | Peer or connection stream budget is exhausted |
| StreamLimitedConnection | The connection is a relay circuit with an active budget, and the caller did not opt in. No stream slot is reserved. |
Instances
| Exception StreamOpenError Source # | |
Defined in LibP2P.Switch.Connection Methods toException :: StreamOpenError -> SomeException # fromException :: SomeException -> Maybe StreamOpenError # displayException :: StreamOpenError -> String # backtraceDesired :: StreamOpenError -> Bool # | |
| Show StreamOpenError Source # | |
Defined in LibP2P.Switch.Connection Methods showsPrec :: Int -> StreamOpenError -> ShowS # show :: StreamOpenError -> String # showList :: [StreamOpenError] -> ShowS # | |
| Eq StreamOpenError Source # | |
Defined in LibP2P.Switch.Connection Methods (==) :: StreamOpenError -> StreamOpenError -> Bool # (/=) :: StreamOpenError -> StreamOpenError -> Bool # | |
data RelayCircuitLimit Source #
Budget a relay advertised for one relayed circuit (specsrelaycircuit-v2).
A component of 0, or an absent component, means that component is
unlimited. Nothing on a connection means it is not a relay circuit.
Constructors
| RelayCircuitLimit | |
Fields
| |
Instances
| Show RelayCircuitLimit Source # | |
Defined in LibP2P.Transport Methods showsPrec :: Int -> RelayCircuitLimit -> ShowS # show :: RelayCircuitLimit -> String # showList :: [RelayCircuitLimit] -> ShowS # | |
| Eq RelayCircuitLimit Source # | |
Defined in LibP2P.Transport Methods (==) :: RelayCircuitLimit -> RelayCircuitLimit -> Bool # (/=) :: RelayCircuitLimit -> RelayCircuitLimit -> Bool # | |
data RelayCircuitExhausted Source #
Why a relayed circuit was closed locally.
Instances
| Exception RelayCircuitExhausted Source # | |
Defined in LibP2P.NAT.Relay.Limit | |
| Show RelayCircuitExhausted Source # | |
Defined in LibP2P.NAT.Relay.Limit Methods showsPrec :: Int -> RelayCircuitExhausted -> ShowS # show :: RelayCircuitExhausted -> String # showList :: [RelayCircuitExhausted] -> ShowS # | |
| Eq RelayCircuitExhausted Source # | |
Defined in LibP2P.NAT.Relay.Limit Methods (==) :: RelayCircuitExhausted -> RelayCircuitExhausted -> Bool # (/=) :: RelayCircuitExhausted -> RelayCircuitExhausted -> Bool # | |
Errors that can occur during a dial operation.
Constructors
| DialBackoff | Peer is in backoff period (recently failed) |
| DialNoAddresses | No addresses provided for dialing |
| DialNoTransport !Multiaddr | No registered transport can handle this address |
| DialGatedAddress !Multiaddr | Outbound policy rejected this address |
| DialGatedPeer !PeerId | Outbound policy rejected the authenticated peer |
| DialAllFailed ![String] | All dial attempts failed |
| DialUpgradeFailed !String | Connection upgrade pipeline failed |
| DialSwitchClosed | Switch has been shut down |
| DialResourceLimit !ResourceError | Resource limit exceeded |
| DialPeerIdMismatch !PeerId !PeerId | Expected vs actual remote PeerId |
data ResourceError Source #
Resource reservation failures.
Constructors
| ResourceLimitExceeded !ScopeName !String | |
| ResourceScopeClosed !ScopeName | |
| InvalidMemoryReservation !Int | |
| InvalidParentScope !ScopeName |
Instances
| Exception ResourceError Source # | |
Defined in LibP2P.Switch.ResourceManager Methods toException :: ResourceError -> SomeException # fromException :: SomeException -> Maybe ResourceError # displayException :: ResourceError -> String # backtraceDesired :: ResourceError -> Bool # | |
| Show ResourceError Source # | |
Defined in LibP2P.Switch.ResourceManager Methods showsPrec :: Int -> ResourceError -> ShowS # show :: ResourceError -> String # showList :: [ResourceError] -> ShowS # | |
| Eq ResourceError Source # | |
Defined in LibP2P.Switch.ResourceManager Methods (==) :: ResourceError -> ResourceError -> Bool # (/=) :: ResourceError -> ResourceError -> Bool # | |
setStreamHandler :: Switch -> ProtocolId -> StreamHandler -> IO () Source #
Register a protocol stream handler. Overwrites any existing handler for the same protocol ID. The changed protocol set is pushed to connected peers via identify push (specs/identify) in the background.
removeStreamHandler :: Switch -> ProtocolId -> IO () Source #
Remove a protocol stream handler. The changed protocol set is pushed to connected peers via identify push (specs/identify) in the background.
Abstraction for stream I/O to enable testing with in-memory buffers.
Constructors
| StreamIO | |
Fields
| |
type StreamHandler = Connection -> StreamIO -> IO () Source #
A protocol stream handler.
Receives the connection the stream runs over and the stream I/O.
The connection exposes the remote peer identity (connPeerId) and
addresses (connRemoteAddr, connLocalAddr), which protocols like
Identify (observedAddr) and the NAT stack need.
The handler owns the stream, matching go-libp2p: it must close or reset on every exit path. Dispatch does not close on return, because some handlers (Circuit Relay STOP) hand the stream off as a connection. One-shot protocols (Identify, AutoNAT) close after the single exchange; long-lived protocols (DHT, Ping, GossipSub) close when the remote half-closes or the session ends.
type ProtocolId = Text Source #
A protocol identifier (e.g. "noise", "yamux/1.0.0").
data Connection Source #
An upgraded (secure + multiplexed) connection to a remote peer.
Constructors
| Connection | |
Fields
| |
Transport
Transport provides dial/listen capabilities for a specific protocol.
Constructors
| Transport | |
Fields
| |
newTCPTransport :: IO Transport Source #
Create a new TCP transport.
data WebSocketConfig Source #
Outer TLS settings for secure WebSockets.
The default client parameters use the system CA store and normal hostname verification. A WSS listener is disabled until server parameters containing a certificate are supplied explicitly.
Constructors
| WebSocketConfig | |
Fields | |
defaultWebSocketConfig :: IO WebSocketConfig Source #
Secure defaults for WebSocket dialing. WSS listening remains disabled
until webSocketServerTLSParams is configured.
webSocketServerParams :: Credential -> ServerParams Source #
Build ordinary Web-PKI server parameters from a configured credential.
newWebSocketTransport :: IO Transport Source #
Create a WebSocket transport with secure client defaults.
newWebSocketTransportWithConfig :: WebSocketConfig -> IO Transport Source #
Create a WebSocket transport using explicit outer TLS settings.
newWebTransportTransport :: KeyPair -> IO Transport Source #
Construct a WebTransport transport with one short-lived self-signed TLS
certificate. The listener address includes its SHA-256 /certhash.
newQUICTransport :: KeyPair -> IO Transport Source #
Construct a QUIC transport using the node's long-term identity key.
Connection gating
data ConnectionGater Source #
Policy hooks applied to inbound and outbound connection establishment.
Constructors
| ConnectionGater | |
Fields
| |
defaultConnectionGater :: ConnectionGater Source #
Default gater that allows all connections.
setConnectionGater :: Switch -> ConnectionGater -> IO () Source #
Set the admission policy used by future inbound and outbound connections. Configure this before starting listeners or dialing peers.
Identify protocol
registerIdentifyHandlers :: Switch -> IO () Source #
Register Identify protocol handlers on the Switch.
Registers: ipfsid/1.0.0 — respond to Identify requests ipfsidpush1.0.0 — handle Identify Push from remote
requestIdentify :: Switch -> Connection -> IO (Either String IdentifyInfo) Source #
Request Identify from a remote peer (initiator side).
Opens a new stream, negotiates ipfsid/1.0.0, then reads one
varint-length-prefixed protobuf message. The publicKey field is
validated against the connection's authenticated peer id (see
validatePublicKey).
Identify is a one-shot exchange, so the stream is closed on every exit
path — success, negotiation refusal, decode failure, timeout and
exception alike. A caller that runs this per connection would
otherwise leak a half-open stream per connection. The whole exchange
is bounded by identifyTimeoutMicros: a peer that negotiates and then
never answers must not pin a stream and a thread forever.
identifyPeer :: Switch -> Connection -> IO (Either String ()) Source #
Run Identify against a freshly established connection and record the result in the peer store (specs/identify).
This is what makes a peer's advertised addresses and protocols known
to us: without it swPeerStore only ever fills from an inbound push,
so nothing is known about a peer we dialled or accepted. go-libp2p
drives its IDService from the swarm's Connected notification for the
same reason.
Failure is returned rather than thrown: the connection stays usable, and no peer store entry is created. There is no retry — a peer that does not answer Identify now will be picked up by a later push, if it sends one.
pushIdentify :: Switch -> IO () Source #
Push our current IdentifyInfo to every connected peer (sender side of ipfsidpush1.0.0).
Per specs/identify: open a stream to each remote peer, negotiate the push protocol id, send one Identify message and close the stream. Call this whenever local state advertised via identify changes (listen addresses, registered protocols). Failures on individual peers (e.g. push protocol not supported) are ignored.
Ping protocol
registerPingHandler :: Switch -> IO () Source #
Register the Ping handler on the Switch.
The installed handler shares one PingLimiter, so concurrent inbound
ping streams are capped at maxPingStreamsPerPeer per remote peer.
sendPing :: Switch -> Connection -> IO (Either PingError PingResult) Source #
Send a single Ping to a remote peer (initiator side).
Convenience wrapper: opens a ping session, pings once, and closes the
stream. For repeated pings to the same peer, use withPingSession
to reuse one stream instead of opening one per call.
data PingSession Source #
The single outbound ping stream to a peer, negotiated and ready.
Obtain with openPingSession (or scoped via withPingSession), send
pings with ping, and always release with closePingSession. A
session whose ping failed (timeout, mismatch, I/O error) closes its
stream immediately and rejects further pings.
Concurrent ping calls on one session are serialized on psLock:
exactly one write/echo exchange runs on the stream at a time, so
concurrent callers queue instead of interleaving their 32-byte
payloads on the wire.
openPingSession :: Switch -> Connection -> IO (Either PingError PingSession) Source #
Open a ping stream on the connection and negotiate the protocol.
The stream is opened through the Switch so it is counted against the peer's stream limits; the reservation is released when the session is closed. On any failure the stream (if opened) is closed before returning.
ping :: PingSession -> IO (Either PingError PingResult) Source #
Send one ping on the session with the default timeout
(pingTimeoutMicros). The session's stream is reused across calls.
pingWithTimeout :: Int -> PingSession -> IO (Either PingError PingResult) Source #
Send one ping on the session, waiting at most the given number of microseconds for the echo. On failure the session is closed: a stream whose echo timed out or went wrong cannot be reused, because a late echo would corrupt the next ping.
The whole exchange runs under the session lock, so concurrent callers are queued one after another on the single stream. The closed check happens under the lock too: a caller queued behind a failed ping sees the session as closed instead of writing into a poisoned stream.
closePingSession :: PingSession -> IO () Source #
Close the session's stream (signalling EOF to the responder's echo loop) and release its stream reservation. Idempotent.
withPingSession :: Switch -> Connection -> (PingSession -> IO a) -> IO (Either PingError a) Source #
Run an action with a ping session, closing it afterwards even if the action throws. Returns Left if the session could not be opened.
data PingResult Source #
Successful ping result.
Constructors
| PingResult | |
Fields
| |
Instances
| Show PingResult Source # | |
Defined in LibP2P.Protocol.Ping Methods showsPrec :: Int -> PingResult -> ShowS # show :: PingResult -> String # showList :: [PingResult] -> ShowS # | |
| Eq PingResult Source # | |
Defined in LibP2P.Protocol.Ping | |
Ping error types.
Constructors
| PingTimeout | No echo within the timeout |
| PingMismatch | Response doesn't match sent bytes |
| PingStreamError !String | Stream open, negotiation, or I/O error |
Perf protocol
registerPerfHandler :: Switch -> IO () Source #
Register the perf handler on the Switch.
runPerf :: Switch -> Connection -> Word64 -> Word64 -> IO (Either PerfError PerfResult) Source #
Run one perf measurement against a connected peer: open a stream, negotiate perf1.0.0, run the exchange, and release the stream.
perfProtocolId :: Text Source #
Perf protocol ID.
data PerfResult Source #
Successful perf exchange result.
Constructors
| PerfResult | |
Fields
| |
Instances
| Show PerfResult Source # | |
Defined in LibP2P.Protocol.Perf Methods showsPrec :: Int -> PerfResult -> ShowS # show :: PerfResult -> String # showList :: [PerfResult] -> ShowS # | |
| Eq PerfResult Source # | |
Defined in LibP2P.Protocol.Perf | |
Perf error types.
Constructors
| PerfNegotiationError !String | Stream open or protocol negotiation failed |
| PerfStreamError !String | I/O error during the exchange |
Kademlia DHT
Server or client mode.
Validator interface for record validation.
valValidate checks that a value is well-formed for its key and
returns an error for records that must not be stored or served.
valSelect picks the index of the best value among conflicting
candidates for the same key (used for GET_VALUE conflict resolution).
Constructors
| Validator | |
Fields
| |
defaultValidator :: Validator Source #
The default validator set: pk records only. Additional
namespaces can be registered by building a custom
namespacedValidator and storing it in the DHT node.
recValue :: DHTRecord -> ByteString Source #
field 2
data ProviderEntry Source #
A provider record for content routing.
Instances
| Show ProviderEntry Source # | |
Defined in LibP2P.DHT Methods showsPrec :: Int -> ProviderEntry -> ShowS # show :: ProviderEntry -> String # showList :: [ProviderEntry] -> ShowS # | |
| Eq ProviderEntry Source # | |
Defined in LibP2P.DHT Methods (==) :: ProviderEntry -> ProviderEntry -> Bool # (/=) :: ProviderEntry -> ProviderEntry -> Bool # | |
peProvider :: ProviderEntry -> PeerId Source #
peAddrs :: ProviderEntry -> [Multiaddr] Source #
data BucketEntry Source #
A single entry in a k-bucket.
Instances
| Show BucketEntry Source # | |
Defined in LibP2P.DHT.Types Methods showsPrec :: Int -> BucketEntry -> ShowS # show :: BucketEntry -> String # showList :: [BucketEntry] -> ShowS # | |
| Eq BucketEntry Source # | |
Defined in LibP2P.DHT.Types | |
entryPeerId :: BucketEntry -> PeerId Source #
entryAddrs :: BucketEntry -> [Multiaddr] Source #
data DHTMaintenanceConfig Source #
Scheduling, expiry, and per-tick work limits for DHT maintenance.
Constructors
| DHTMaintenanceConfig | |
Fields
| |
defaultDHTMaintenanceConfig :: DHTMaintenanceConfig Source #
go-libp2p Amino DHT defaults: providers republish every 22 hours, value records expire after 48 hours, and value GC runs every 24 hours.
newDHTNode :: Switch -> DHTMode -> IO DHTNode Source #
Create a new DHT node with the outbound sender wired to the Switch.
Registers a disconnect notifier so a cached session is dropped when the peer's last connection closes (#279).
newDHTNodeWithConfig :: DHTMaintenanceConfig -> Switch -> DHTMode -> IO DHTNode Source #
Create a DHT node with explicit maintenance scheduling and expiry limits.
stopDHTNode :: DHTNode -> IO () Source #
Stop the DHT node: drop cached sessions and deregister the disconnect notifier so a stopped node cannot keep a callback alive on the Switch.
registerDHTHandler :: DHTNode -> IO () Source #
Register the DHT handler on the Switch.
Per specs/kad-dht (client and server mode), nodes operating in client
mode do not offer the Kademlia protocol identifier for incoming
streams, so this is a no-op for DHTClient nodes: they keep issuing
outbound queries via dhtSendRequest but never serve inbound RPC.
bootstrap :: DHTNode -> [PeerId] -> IO () Source #
Bootstrap the DHT: insert seeds, self-lookup, refresh every non-empty bucket.
Startup is explicit: call bootstrap or startBootstrap. newDHTNode
does not start a loop, matching go-libp2p's IpfsDHT.Bootstrap.
The whole run is bounded by dhtQueryTimeout (default 10s).
startBootstrap :: DHTNode -> [PeerId] -> Int -> IO () Source #
Start a periodic bootstrap loop. Runs one refresh immediately, then
every intervalMicros. Cancelled by stopDHTNode.
provide :: DHTNode -> [Multiaddr] -> ByteString -> IO () Source #
Announce that the local node provides a given content key.
Performs an iterative FIND_NODE lookup for the content key, then sends ADD_PROVIDER messages to the k closest peers found. The local peer's listen addresses are included so remote peers can dial back.
putValue :: DHTNode -> Validator -> ByteString -> ByteString -> IO (Either String ()) Source #
Store a value in the DHT under the given key.
Performs an iterative FIND_NODE lookup for the key, then sends
PUT_VALUE messages to the k closest peers. Also stores the value
locally. The value is validated using the node's configured validator;
if validation fails, the function returns Left with an error message.
getValue :: DHTNode -> Validator -> ByteString -> IO (Either String DHTRecord) Source #
Retrieve a value from the DHT.
Convenience wrapper around iterativeGetValue.
findProviders :: DHTNode -> ByteString -> IO [ProviderEntry] Source #
Find providers for a content key.
Convenience wrapper around iterativeGetProviders.
findPeer :: DHTNode -> PeerId -> IO [BucketEntry] Source #
Find the closest known peers to a target peer ID.
Convenience wrapper around iterativeFindNode.
Discovery
data DiscoveryEvent Source #
A peer found by a discovery mechanism, with the addresses it
advertised. Deduplication is the consumer's job, not the queue's:
discovery runs concurrently with the Switch's peer store, and
suppressing re-announcements would hide refreshed address lists.
A TQueue is unbounded, so producing never blocks; applications
are expected to drain or poll at their own cadence.
Constructors
| DiscoveryEvent | |
Fields
| |
Instances
| Show DiscoveryEvent Source # | |
Defined in LibP2P.Discovery.Types Methods showsPrec :: Int -> DiscoveryEvent -> ShowS # show :: DiscoveryEvent -> String # showList :: [DiscoveryEvent] -> ShowS # | |
| Eq DiscoveryEvent Source # | |
Defined in LibP2P.Discovery.Types Methods (==) :: DiscoveryEvent -> DiscoveryEvent -> Bool # (/=) :: DiscoveryEvent -> DiscoveryEvent -> Bool # | |
newDiscoveryQueue :: IO (TQueue DiscoveryEvent) Source #
Create a discovery event queue.
drainDiscoveryQueue :: TQueue DiscoveryEvent -> IO [DiscoveryEvent] Source #
Drain every currently queued event, in order.
mDNS
data MDNSConfig Source #
mDNS service settings; defaultMDNSConfig tracks the spec
(service _p2p._udp.local, port 5353, both address families).
Constructors
| MDNSConfig | |
Fields
| |
Instances
| Show MDNSConfig Source # | |
Defined in LibP2P.Discovery.MDNS Methods showsPrec :: Int -> MDNSConfig -> ShowS # show :: MDNSConfig -> String # showList :: [MDNSConfig] -> ShowS # | |
| Eq MDNSConfig Source # | |
Defined in LibP2P.Discovery.MDNS | |
data MDNSService Source #
A running mDNS discovery service.
Constructors
| MDNSService | |
Fields
| |
newMDNSService :: Switch -> MDNSConfig -> IO (Either String MDNSService) Source #
Start the mDNS service: open the multicast sockets (IPv4, and
IPv6 if configured and possible), join the groups, and start the
responder threads. Returns Left only when no socket could be
opened at all; failing one stack (an IPv4-only host, for example)
degrades the service to the other.
stopMDNSService :: MDNSService -> IO () Source #
Stop the service: send the goodbye (records with TTL 0), cancel the threads, close the sockets.
Rendezvous
data RendezvousConfig Source #
Rendezvous point configuration. Defaults follow the spec's "Recommendations for Rendezvous Points configurations": minimum TTL 2h, maximum TTL 72h, namespace length 255, 1000 registrations per peer, 1000 registrations returned per namespace query.
Constructors
| RendezvousConfig | |
Fields
| |
Instances
| Show RendezvousConfig Source # | |
Defined in LibP2P.Discovery.Rendezvous Methods showsPrec :: Int -> RendezvousConfig -> ShowS # show :: RendezvousConfig -> String # showList :: [RendezvousConfig] -> ShowS # | |
| Eq RendezvousConfig Source # | |
Defined in LibP2P.Discovery.Rendezvous Methods (==) :: RendezvousConfig -> RendezvousConfig -> Bool # (/=) :: RendezvousConfig -> RendezvousConfig -> Bool # | |
data RendezvousError Source #
Client-side failure. Rejections carry the rendezvous point's
status (ResponseStatus) so the
application can distinguish, say, an invalid TTL from an
unauthorized registration.
Constructors
| RendezvousTimeout | No answer within the exchange timeout |
| RendezvousTransport !String | Stream/negotiation failure |
| RendezvousRejected !ResponseStatus !(Maybe Text) | Rendezvous point rejected the request, with its status text |
| RendezvousDecode !String | Malformed response |
Instances
| Show RendezvousError Source # | |
Defined in LibP2P.Discovery.Rendezvous Methods showsPrec :: Int -> RendezvousError -> ShowS # show :: RendezvousError -> String # showList :: [RendezvousError] -> ShowS # | |
| Eq RendezvousError Source # | |
Defined in LibP2P.Discovery.Rendezvous Methods (==) :: RendezvousError -> RendezvousError -> Bool # (/=) :: RendezvousError -> RendezvousError -> Bool # | |
registerRendezvousPoint :: Switch -> RendezvousConfig -> IO RendezvousPoint Source #
Serve rendezvous1.0.0 on the Switch, making this node act as a
rendezvous point. Returns the point so callers can query state
(registeredCount) for tests and observability.
registeredCount :: RendezvousPoint -> IO Int Source #
Number of currently valid registrations across all namespaces,
excluding expired ones. Expired entries are pruned lazily (on
discovery; nothing scans in the background), so rcMaxPerPeer
counts live registrations: a peer that keeps re-registering a fresh
record keeps one slot per namespace.
registerSelf :: Switch -> Connection -> Text -> Maybe Word64 -> IO (Either RendezvousError Word64) Source #
Register ourselves in a namespace (client side of REGISTER). A signed peer record over our current listen addresses is built here; the granted TTL is returned so the application knows when to refresh.
unregisterSelf :: Switch -> Connection -> Text -> IO (Either RendezvousError ()) Source #
Cancel our registration in a namespace (client side of UNREGISTER). No reply is sent by the rendezvous point; the write succeeding is the outcome.
discover :: Switch -> Connection -> Maybe Text -> DiscoverLimit -> ByteString -> IO (Either RendezvousError ([RegistrationInfo], ByteString)) Source #
Discover registrations (client side of DISCOVER). Pass Nothing
for the namespace to query every namespace; pass the cookie from a
previous response to list only registrations made since (progressive
refresh, specs/rendezvous §The Protocol). Returns the registrations
and the cookie for the next poll.
inspectRegistration :: RegistrationInfo -> Either String DiscoveryEvent Source #
Validate a received registration's signed peer record envelope and extract the peer identity and dialable addresses it advertises.
pushDiscoverEvents :: TQueue DiscoveryEvent -> [RegistrationInfo] -> IO () Source #
Push decoded discovery events for registrations onto a queue; registrations whose record does not verify are dropped rather than poisoning the feed.
NAT traversal (AutoNAT, Circuit Relay v2, DCUtR)
Configuration for the NAT traversal handlers.
Constructors
| NATConfig | |
Fields
| |
defaultNATConfig :: NATConfig Source #
Default NAT configuration: default relay limits and refresh tuning.
Detected NAT status.
Constructors
| NATPublic | |
| NATPrivate | |
| NATUnknown |
data AutoNATClientConfig Source #
AutoNAT client scheduling and resource bounds.
Constructors
| AutoNATClientConfig | |
Fields
| |
Instances
| Show AutoNATClientConfig Source # | |
Defined in LibP2P.NAT.AutoNAT.Service Methods showsPrec :: Int -> AutoNATClientConfig -> ShowS # show :: AutoNATClientConfig -> String # showList :: [AutoNATClientConfig] -> ShowS # | |
| Eq AutoNATClientConfig Source # | |
Defined in LibP2P.NAT.AutoNAT.Service Methods (==) :: AutoNATClientConfig -> AutoNATClientConfig -> Bool # (/=) :: AutoNATClientConfig -> AutoNATClientConfig -> Bool # | |
defaultAutoNATClientConfig :: AutoNATClientConfig Source #
go-libp2p scheduling defaults, with four peers per cycle to satisfy the AutoNAT v1 requirement for more than three agreeing dial reports.
data AutoNATClientService Source #
Handle for observing and stopping the background client.
data NATServices Source #
Handles returned by registerNATHandlers.
Constructors
| NATServices | |
Fields
| |
startAutoNATClient :: Switch -> AutoNATClientConfig -> IO AutoNATClientService Source #
Start periodic reachability probing and attach its lifetime to the Switch.
autoNATClientStatus :: AutoNATClientService -> IO NATStatus Source #
Read the most recently aggregated reachability status.
stopAutoNATClient :: AutoNATClientService -> IO () Source #
Stop the client and cancel any in-flight request.
registerNATHandlers :: Switch -> NATConfig -> IO (RelayState, CircuitState, NATServices) Source #
Register the NAT protocol handlers and the circuit client transport on the Switch.
Returns the relay server state, circuit client state, and AutoNAT service
handles. The background v1 client is stopped automatically by
switchClose; the v2 state is used by checkAutoNATV2.
registerAutoNATHandler :: Switch -> IO () Source #
Register the AutoNAT server handler (libp2pautonat/1.0.0).
The dial-back deliberately bypasses the connection pool: reusing the requester's existing connection would always report success. Instead a fresh transport dial + upgrade verifies both reachability and identity, and the probe connection is closed immediately (go-libp2p uses a separate dialer host for the same reason).
registerAutoNATV2Handlers :: Switch -> AutoNATV2Config -> IO AutoNATV2State Source #
Register both AutoNAT v2 protocol handlers and return the state used to correlate request nonces with fresh dial-back connections.
checkAutoNATV2 :: Switch -> AutoNATV2State -> Connection -> [AutoNATV2Request] -> IO (Either String AutoNATV2Result) Source #
Run an AutoNAT v2 request over an existing connection.
data AutoNATV2Config Source #
AutoNAT v2 limits and injectable time/randomness.
Constructors
| AutoNATV2Config | |
Fields
| |
defaultAutoNATV2Config :: AutoNATV2Config Source #
go-libp2p-compatible AutoNAT v2 defaults.
data AutoNATV2State Source #
data AutoNATV2Request Source #
One address offered by the client.
Constructors
| AutoNATV2Request | |
Fields
| |
Instances
| Show AutoNATV2Request Source # | |
Defined in LibP2P.NAT.AutoNAT.V2 Methods showsPrec :: Int -> AutoNATV2Request -> ShowS # show :: AutoNATV2Request -> String # showList :: [AutoNATV2Request] -> ShowS # | |
| Eq AutoNATV2Request Source # | |
Defined in LibP2P.NAT.AutoNAT.V2 Methods (==) :: AutoNATV2Request -> AutoNATV2Request -> Bool # (/=) :: AutoNATV2Request -> AutoNATV2Request -> Bool # | |
data AutoNATV2Result Source #
Address-specific reachability outcome.
Constructors
| AutoNATV2Result | |
Fields
| |
Instances
| Show AutoNATV2Result Source # | |
Defined in LibP2P.NAT.AutoNAT.V2 Methods showsPrec :: Int -> AutoNATV2Result -> ShowS # show :: AutoNATV2Result -> String # showList :: [AutoNATV2Result] -> ShowS # | |
| Eq AutoNATV2Result Source # | |
Defined in LibP2P.NAT.AutoNAT.V2 Methods (==) :: AutoNATV2Result -> AutoNATV2Result -> Bool # (/=) :: AutoNATV2Result -> AutoNATV2Result -> Bool # | |
autoNATV2DialProtocolId :: Text Source #
Protocol used for one AutoNAT v2 reachability request.
autoNATV2DialBackProtocolId :: Text Source #
Protocol used by the server to return the request nonce.
registerRelayHopHandler :: Switch -> RelayState -> IO () Source #
Register the Circuit Relay v2 hop handler (libp2pcircuitrelay0.2.0/hop): serve RESERVE and CONNECT requests.
registerRelayStopHandler :: Switch -> CircuitState -> IO () Source #
Register the Circuit Relay v2 stop handler (libp2pcircuitrelay0.2.0/stop).
After the CONNECT/OK exchange the stop stream *is* the relayed connection (specsrelaycircuit-v2), so it is handed to the circuit transport's listener for the relay it arrived over. The Switch then upgrades it like any other inbound raw connection.
The relay's advertised limit is enforced on the relayed stream (issue #269) before the Switch upgrades it.
registerDCUtRHandler :: Switch -> DCUtRUpgradeConfig -> IO () Source #
Register the DCUtR handler (libp2pdcutr).
Answers the CONNECT/SYNC exchange with our listen addresses and dials the initiator's addresses through the Switch for the hole punch.
data RelayState Source #
Mutable relay server state.
data RelayConfig Source #
Relay server configuration.
Constructors
| RelayConfig | |
Fields
| |
Instances
| Show RelayConfig Source # | |
Defined in LibP2P.NAT.Relay Methods showsPrec :: Int -> RelayConfig -> ShowS # show :: RelayConfig -> String # showList :: [RelayConfig] -> ShowS # | |
| Eq RelayConfig Source # | |
Defined in LibP2P.NAT.Relay | |
defaultRelayConfig :: RelayConfig Source #
Default relay configuration.
newRelayState :: RelayConfig -> IO RelayState Source #
Create new relay state from configuration.
data CircuitState Source #
Per-Switch state shared between the circuit transport and the stop
protocol handler: one inbound queue per relay we hold a reservation on.
circuitTransport :: Switch -> CircuitState -> ReservationRefreshConfig -> Transport Source #
The Circuit Relay v2 client transport.
Captures the Switch so it can dial the relay; register it after
newSwitch with addTransport.
newCircuitState :: IO CircuitState Source #
Create empty circuit state.
data ReservationRefreshConfig Source #
Tuning for client-side reservation refresh (specsrelaycircuit-v2: "the reservation becomes invalid after this time and it's the responsibility of the client to refresh").
Values follow go-libp2p's autorelay relay finder
(rsvpExpirationSlack / rsvpRefreshInterval): refresh once the
reservation is within rrcMargin of its expiry, checked every
rrcPollInterval.
Constructors
| ReservationRefreshConfig | |
Fields
| |
Instances
| Show ReservationRefreshConfig Source # | |
Defined in LibP2P.NAT.Relay.Transport Methods showsPrec :: Int -> ReservationRefreshConfig -> ShowS # show :: ReservationRefreshConfig -> String # showList :: [ReservationRefreshConfig] -> ShowS # | |
| Eq ReservationRefreshConfig Source # | |
Defined in LibP2P.NAT.Relay.Transport Methods (==) :: ReservationRefreshConfig -> ReservationRefreshConfig -> Bool # (/=) :: ReservationRefreshConfig -> ReservationRefreshConfig -> Bool # | |
defaultReservationRefreshConfig :: ReservationRefreshConfig Source #
Default refresh tuning: a 2 minute margin, checked every minute.
GossipSub
data GossipSubNode Source #
A GossipSub node: Router + Switch integration.
Constructors
| GossipSubNode | |
Fields
| |
data GossipSubParams Source #
GossipSub router parameters.
Constructors
| GossipSubParams | |
Fields
| |
defaultGossipSubParams :: GossipSubParams Source #
Default GossipSub parameters per spec.
newGossipSubNode :: Switch -> GossipSubParams -> IO GossipSubNode Source #
Create a new GossipSub node with a Router wired to the Switch.
The Router's gsSendRPC callback opens/reuses outbound streams to peers via the Switch's connection pool. Accepted peer-exchange records are stored and dialed through the same Switch (#247).
startGossipSub :: GossipSubNode -> IO () Source #
Start the GossipSub node: register stream handler, notifier, and start heartbeat.
Idempotent. A second start does not stack connection notifiers or
heartbeats. stopGossipSub clears the notifier body so a later
connection does not open a stream (#283).
stopGossipSub :: GossipSubNode -> IO () Source #
Stop the GossipSub node: disable the connection notifier, cancel heartbeat, and unregister handlers.
The wrapper stays on swNotifiers but reads a cleared hook, so a
connection established after stop does not open a stream or call
addPeer. A later start re-arms the same wrapper (#283).
enablePartialMessages :: GossipSubNode -> PartialMessagesExtension state -> IO (Either PartialMessagesError ()) Source #
Enable partial messages before starting the node.
gossipJoin :: GossipSubNode -> Topic -> IO () Source #
Subscribe to a topic.
gossipJoinPartial :: GossipSubNode -> Topic -> PartialTopicMode -> IO (Either PartialMessagesError ()) Source #
Subscribe while supporting or requesting partial messages.
gossipLeave :: GossipSubNode -> Topic -> IO () Source #
Unsubscribe from a topic.
gossipPublish :: GossipSubNode -> Topic -> ByteString -> IO () Source #
Publish a message to a topic (signed with the Switch's identity key).
data PartialTopicMode Source #
Per-topic partial-message behavior advertised in subscription RPCs.
Constructors
| SupportsPartialMessages | |
| RequestsPartialMessages |
Instances
| Show PartialTopicMode Source # | |
Defined in LibP2P.Protocol.GossipSub.Types Methods showsPrec :: Int -> PartialTopicMode -> ShowS # show :: PartialTopicMode -> String # showList :: [PartialTopicMode] -> ShowS # | |
| Eq PartialTopicMode Source # | |
Defined in LibP2P.Protocol.GossipSub.Types Methods (==) :: PartialTopicMode -> PartialTopicMode -> Bool # (/=) :: PartialTopicMode -> PartialTopicMode -> Bool # | |
data PartialMessage Source #
Opaque application-defined partial-message data for one topic/group.
Constructors
| PartialMessage | |
Fields
| |
Instances
| Show PartialMessage Source # | |
Defined in LibP2P.Protocol.GossipSub.Types Methods showsPrec :: Int -> PartialMessage -> ShowS # show :: PartialMessage -> String # showList :: [PartialMessage] -> ShowS # | |
| Eq PartialMessage Source # | |
Defined in LibP2P.Protocol.GossipSub.Types Methods (==) :: PartialMessage -> PartialMessage -> Bool # (/=) :: PartialMessage -> PartialMessage -> Bool # | |
data PartialMessagesExtension state Source #
data PartialMessagesConfig state Source #
Application callbacks and bounded-state limits.
Callbacks are serialized with partial-message state updates. They should
return sends through partialPublishActions rather than recursively calling
publishPartial.
Constructors
| PartialMessagesConfig | |
Fields
| |
data PartialCallbackResult state Source #
Updated application state plus per-peer messages to send.
Constructors
| PartialCallbackResult | |
Fields
| |
data PartialPublishAction Source #
One application-defined partial-message send.
Constructors
| PartialPublishAction | |
Fields | |
Instances
| Show PartialPublishAction Source # | |
Defined in LibP2P.Protocol.GossipSub.PartialMessages Methods showsPrec :: Int -> PartialPublishAction -> ShowS # show :: PartialPublishAction -> String # showList :: [PartialPublishAction] -> ShowS # | |
| Eq PartialPublishAction Source # | |
Defined in LibP2P.Protocol.GossipSub.PartialMessages Methods (==) :: PartialPublishAction -> PartialPublishAction -> Bool # (/=) :: PartialPublishAction -> PartialPublishAction -> Bool # | |
type PartialPublishPlan state = Map PeerId state -> (PeerId -> Bool) -> IO (PartialCallbackResult state) Source #
Plan sends for a locally published or updated group. The predicate reports whether a peer requested partial data; metadata-only peers return False.
data PartialMessagesError Source #
Configuration and lifecycle errors exposed to callers.
Constructors
| PartialMessagesAlreadyInstalled | |
| PartialMessagesNodeStarted | |
| PartialMessagesNotInstalled | |
| PartialMessagesNotEnabledForTopic |
Instances
| Exception PartialMessagesError Source # | |
Defined in LibP2P.Protocol.GossipSub.PartialMessages | |
| Show PartialMessagesError Source # | |
Defined in LibP2P.Protocol.GossipSub.PartialMessages Methods showsPrec :: Int -> PartialMessagesError -> ShowS # show :: PartialMessagesError -> String # showList :: [PartialMessagesError] -> ShowS # | |
| Eq PartialMessagesError Source # | |
Defined in LibP2P.Protocol.GossipSub.PartialMessages Methods (==) :: PartialMessagesError -> PartialMessagesError -> Bool # (/=) :: PartialMessagesError -> PartialMessagesError -> Bool # | |
defaultPartialMessagesConfig :: state -> (PeerId -> Map PeerId state -> PartialMessage -> IO (PartialCallbackResult state)) -> (Topic -> ByteString -> [PeerId] -> Map PeerId state -> IO (PartialCallbackResult state)) -> PartialMessagesConfig state Source #
Go-compatible defaults for group state limits and lifetime.
newPartialMessagesExtension :: PartialMessagesConfig state -> IO (PartialMessagesExtension state) Source #
partialMeshPeers :: PartialMessagesExtension state -> Topic -> IO (Either PartialMessagesError [PeerId]) Source #
Compatible mesh/fanout peers for an enabled topic.
partialPeerRequests :: PartialMessagesExtension state -> PeerId -> Topic -> IO Bool Source #
Whether a peer requested partial data for a topic.
publishPartial :: PartialMessagesExtension state -> Topic -> ByteString -> PartialPublishPlan state -> IO (Either PartialMessagesError ()) Source #
Publish or update one application-defined partial-message group. The application owns the encoding of data and metadata; this runtime only routes the opaque bytes and bounds group state.