-- | GossipSub Switch integration handler (Phase 10b).
--
-- Bridges the GossipSub Router with the Switch by:
-- 1. Registering StreamHandlers for inbound GossipSub protocol versions
-- 2. Providing a sendRPC callback that opens/reuses outbound streams
-- 3. Managing lifecycle (heartbeat start/stop)
--
-- GossipSub maintains persistent bidirectional RPC streams, unlike
-- Identify/Ping which are one-shot. Each peer has at most one cached
-- outbound stream.
module LibP2P.Protocol.GossipSub.Handler
  ( -- * Types
    GossipSubNode (..)
    -- * Construction
  , newGossipSubNode
    -- * Stream handling
  , handleGossipSubStream
  , sendCurrentSubscriptions
    -- * Lifecycle
  , startGossipSub
  , stopGossipSub
    -- * Convenience API
  , enablePartialMessages
  , gossipJoin
  , gossipJoinPartial
  , gossipLeave
  , gossipPublish
    -- * Constants
  , gossipSubProtocolId
  , gossipSubProtocolIdV12
  , gossipSubProtocolIdV11
  , gossipSubProtocolIdV10
  , floodSubProtocolId
  ) where

import Control.Concurrent.Async (Async, async, cancel)
import Control.Concurrent.MVar (MVar, newMVar, withMVar)
import Control.Concurrent.STM
  ( STM
  , TVar
  , atomically
  , newTVarIO
  , readTVar
  , readTVarIO
  , writeTVar
  , modifyTVar'
  )
import Control.Exception (SomeException, catch, finally, mask_, onException)
import Control.Monad (void, when)
import Data.ByteString (ByteString)
import Data.IORef (IORef, newIORef, readIORef, writeIORef)
import qualified Data.Map.Strict as Map
import Data.Maybe (isJust, isNothing)
import Data.Time.Clock (getCurrentTime)
import LibP2P.Crypto.PeerId (PeerId)
import LibP2P.MultistreamSelect.Negotiation
  ( NegotiationResult (..)
  , ProtocolId
  , StreamIO (..)
  , closeQuietly
  , negotiateInitiator
  )
import LibP2P.Protocol.GossipSub.DirectConnect
  ( DirectDialSlots
  , cancelDirectDials
  , newDirectDialSlots
  , reconnectDirectPeer
  , runDirectConnectLoop
  )
import LibP2P.Protocol.GossipSub.Extensions
  ( attachExtensionsToHello
  , markExtensionAdvertisementSent
  )
import LibP2P.Protocol.GossipSub.Heartbeat (runHeartbeat)
import LibP2P.Protocol.GossipSub.PeerExchange (installPeerExchange)
import LibP2P.Protocol.GossipSub.Message (readRPCMessage, writeRPCMessage)
import LibP2P.Core.Binary (word32BE)
import LibP2P.Multiaddr (protocols)
import LibP2P.Multiaddr.Protocol (Protocol (..))
import LibP2P.Protocol.GossipSub.Router
  ( addPeer
  , handleRPC
  , join
  , joinPartial
  , leave
  , newRouter
  , publish
  , removePeer
  , setPeerIP
  , setSignedPeerRecord
  )
import LibP2P.Protocol.GossipSub.PartialMessages
  ( PartialMessagesError (..)
  , PartialMessagesExtension
  )
import qualified LibP2P.Protocol.GossipSub.PartialMessages as PartialMessages
import LibP2P.Protocol.Identify.Message (IdentifyInfo (..))
import qualified Data.Set as Set
import qualified LibP2P.Protocol.GossipSub.Types as Types
import LibP2P.Protocol.GossipSub.Types
  ( GossipSubParams
  , GossipSubRouter (..)
  , PartialTopicMode
  , PeerProtocol (..)
  , RPC (..)
  , SubOpts (..)
  , Topic
  , emptyRPC
  , maxRPCSize
  )
import LibP2P.Switch.Connection (newStream)
import LibP2P.Switch.ConnPool (lookupConn)
import LibP2P.Switch (removeStreamHandler, setStreamHandler)
import LibP2P.Switch.Types
  ( ConnState
  , Connection (..)
  , Switch (..)
  )

-- | GossipSub v1.3 protocol ID (preferred).
gossipSubProtocolId :: ProtocolId
gossipSubProtocolId :: ProtocolId
gossipSubProtocolId = ProtocolId
Types.gossipSubProtocolId

-- | GossipSub v1.2 protocol ID, retained for backwards compatibility.
gossipSubProtocolIdV12 :: ProtocolId
gossipSubProtocolIdV12 :: ProtocolId
gossipSubProtocolIdV12 = ProtocolId
Types.gossipSubProtocolIdV12

-- | GossipSub v1.1 protocol ID, retained for backwards compatibility.
gossipSubProtocolIdV11 :: ProtocolId
gossipSubProtocolIdV11 :: ProtocolId
gossipSubProtocolIdV11 = ProtocolId
Types.gossipSubProtocolIdV11

-- | GossipSub v1.0 protocol ID, retained for backwards compatibility.
gossipSubProtocolIdV10 :: ProtocolId
gossipSubProtocolIdV10 :: ProtocolId
gossipSubProtocolIdV10 = ProtocolId
Types.gossipSubProtocolIdV10

-- | FloodSub protocol ID, advertised alongside the meshsub protocols so
-- that floodsub-only peers still get a pubsub stream (#157,
-- gossipsub-v1.0.md "Compatibility with FloodSub").
floodSubProtocolId :: ProtocolId
floodSubProtocolId :: ProtocolId
floodSubProtocolId = ProtocolId
Types.floodSubProtocolId

-- | All protocol IDs we register and offer, preferred first.
gossipSubProtocolIds :: [ProtocolId]
gossipSubProtocolIds :: [ProtocolId]
gossipSubProtocolIds =
  [ ProtocolId
gossipSubProtocolId
  , ProtocolId
gossipSubProtocolIdV12
  , ProtocolId
gossipSubProtocolIdV11
  , ProtocolId
gossipSubProtocolIdV10
  , ProtocolId
floodSubProtocolId
  ]

-- | Map a negotiated protocol ID to the peer's protocol version.
protocolFor :: ProtocolId -> PeerProtocol
protocolFor :: ProtocolId -> PeerProtocol
protocolFor ProtocolId
proto
  | ProtocolId
proto ProtocolId -> ProtocolId -> Bool
forall a. Eq a => a -> a -> Bool
== ProtocolId
gossipSubProtocolId    = PeerProtocol
GossipSubV13Peer
  | ProtocolId
proto ProtocolId -> ProtocolId -> Bool
forall a. Eq a => a -> a -> Bool
== ProtocolId
gossipSubProtocolIdV12 = PeerProtocol
GossipSubV12Peer
  | ProtocolId
proto ProtocolId -> ProtocolId -> Bool
forall a. Eq a => a -> a -> Bool
== ProtocolId
gossipSubProtocolIdV11 = PeerProtocol
GossipSubPeer
  | ProtocolId
proto ProtocolId -> ProtocolId -> Bool
forall a. Eq a => a -> a -> Bool
== ProtocolId
gossipSubProtocolIdV10 = PeerProtocol
GossipSubV10Peer
  | ProtocolId
proto ProtocolId -> ProtocolId -> Bool
forall a. Eq a => a -> a -> Bool
== ProtocolId
floodSubProtocolId     = PeerProtocol
FloodSubPeer
  | Bool
otherwise                       = PeerProtocol
GossipSubPeer

-- | Identity and owning connection for a cached outbound stream.
data GossipStreamMeta = GossipStreamMeta
  { GossipStreamMeta -> TVar ConnState
gsmOwner :: !(TVar ConnState)
  , GossipStreamMeta -> IORef ()
gsmToken :: !(IORef ())
  }

-- | A GossipSub node: Router + Switch integration.
data GossipSubNode = GossipSubNode
  { GossipSubNode -> GossipSubRouter
gsnRouter    :: !GossipSubRouter
  , GossipSubNode -> Switch
gsnSwitch    :: !Switch
  , GossipSubNode -> TVar (Maybe (Async ()))
gsnHeartbeat :: !(TVar (Maybe (Async ())))
  , GossipSubNode -> TVar (Map PeerId StreamIO)
gsnStreams   :: !(TVar (Map.Map PeerId StreamIO))  -- ^ Cached outbound streams per peer
  , GossipSubNode -> TVar (Map PeerId GossipStreamMeta)
gsnStreamMeta :: !(TVar (Map.Map PeerId GossipStreamMeta))
    -- ^ Owner and identity of each managed stream in 'gsnStreams'.
  , GossipSubNode -> IORef (Maybe (Connection -> IO ()))
gsnConnectHook :: !(IORef (Maybe (Connection -> IO ())))
    -- ^ Connection notifier body. Cleared while the node is stopped.
  , GossipSubNode -> IORef (Maybe (Connection -> IO ()))
gsnDisconnectHook :: !(IORef (Maybe (Connection -> IO ())))
    -- ^ Disconnect notifier body. Cleared while the node is stopped.
  , GossipSubNode -> TVar Bool
gsnNotifierInstalled :: !(TVar Bool)
    -- ^ The Switch holds one connect wrapper for this node.
  , GossipSubNode -> TVar Bool
gsnStarted :: !(TVar Bool)
    -- ^ True between a successful start and stop.
  , GossipSubNode -> MVar ()
gsnLifecycleLock :: !(MVar ())
    -- ^ Serializes start and stop so heartbeat ownership cannot race.
  , GossipSubNode -> DirectDialSlots
gsnDirectSlots :: !DirectDialSlots
    -- ^ In-flight dials of configured direct peers (#259).
  , GossipSubNode -> TVar (Maybe (Async ()))
gsnDirectConnect :: !(TVar (Maybe (Async ())))
    -- ^ Connectivity checker. Cancelled by 'stopGossipSub'.
  }

-- | 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).
newGossipSubNode :: Switch -> GossipSubParams -> IO GossipSubNode
newGossipSubNode :: Switch -> GossipSubParams -> IO GossipSubNode
newGossipSubNode Switch
sw GossipSubParams
params = do
  streamsVar <- Map PeerId StreamIO -> IO (TVar (Map PeerId StreamIO))
forall a. a -> IO (TVar a)
newTVarIO Map PeerId StreamIO
forall k a. Map k a
Map.empty
  streamMetaVar <- newTVarIO Map.empty
  hbVar <- newTVarIO Nothing
  connectHook <- newIORef Nothing
  disconnectHook <- newIORef Nothing
  installed <- newTVarIO False
  started <- newTVarIO False
  lifecycleLock <- newMVar ()
  directSlots <- newDirectDialSlots
  directConnect <- newTVarIO Nothing
  routerRef <- newIORef Nothing
  -- Create router with real sendRPC that uses the Switch
  let localPid = Switch -> PeerId
swLocalPeerId Switch
sw
  router <- newRouter params localPid
    (sendRPCviaSwitch sw started streamsVar streamMetaVar routerRef) getCurrentTime
  writeIORef routerRef (Just router)
  let node = GossipSubNode
        { gsnRouter :: GossipSubRouter
gsnRouter    = GossipSubRouter
router
        , gsnSwitch :: Switch
gsnSwitch    = Switch
sw
        , gsnHeartbeat :: TVar (Maybe (Async ()))
gsnHeartbeat = TVar (Maybe (Async ()))
hbVar
        , gsnStreams :: TVar (Map PeerId StreamIO)
gsnStreams   = TVar (Map PeerId StreamIO)
streamsVar
        , gsnStreamMeta :: TVar (Map PeerId GossipStreamMeta)
gsnStreamMeta = TVar (Map PeerId GossipStreamMeta)
streamMetaVar
        , gsnConnectHook :: IORef (Maybe (Connection -> IO ()))
gsnConnectHook = IORef (Maybe (Connection -> IO ()))
connectHook
        , gsnDisconnectHook :: IORef (Maybe (Connection -> IO ()))
gsnDisconnectHook = IORef (Maybe (Connection -> IO ()))
disconnectHook
        , gsnNotifierInstalled :: TVar Bool
gsnNotifierInstalled = TVar Bool
installed
        , gsnStarted :: TVar Bool
gsnStarted = TVar Bool
started
        , gsnLifecycleLock :: MVar ()
gsnLifecycleLock = MVar ()
lifecycleLock
        , gsnDirectSlots :: DirectDialSlots
gsnDirectSlots = DirectDialSlots
directSlots
        , gsnDirectConnect :: TVar (Maybe (Async ()))
gsnDirectConnect = TVar (Maybe (Async ()))
directConnect
        }
  installPeerExchange sw router
  atomically $ modifyTVar' (swDisconnectNotifiers sw)
    (runGossipDisconnect disconnectHook :)
  pure node

-- | Send an RPC to a peer via cached or newly opened stream.
sendRPCviaSwitch
  :: Switch
  -> TVar Bool
  -> TVar (Map.Map PeerId StreamIO)
  -> TVar (Map.Map PeerId GossipStreamMeta)
  -> IORef (Maybe GossipSubRouter)
  -> PeerId
  -> RPC
  -> IO ()
sendRPCviaSwitch :: Switch
-> TVar Bool
-> TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> IORef (Maybe GossipSubRouter)
-> PeerId
-> RPC
-> IO ()
sendRPCviaSwitch Switch
sw TVar Bool
startedVar TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar IORef (Maybe GossipSubRouter)
routerRef PeerId
pid RPC
rpc = do
  mCached <- STM (Maybe (StreamIO, Maybe (IORef ())))
-> IO (Maybe (StreamIO, Maybe (IORef ())))
forall a. STM a -> IO a
atomically (STM (Maybe (StreamIO, Maybe (IORef ())))
 -> IO (Maybe (StreamIO, Maybe (IORef ()))))
-> STM (Maybe (StreamIO, Maybe (IORef ())))
-> IO (Maybe (StreamIO, Maybe (IORef ())))
forall a b. (a -> b) -> a -> b
$ TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> STM (Maybe (StreamIO, Maybe (IORef ())))
lookupCachedStream TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar PeerId
pid
  case mCached of
    Just (StreamIO
stream, Maybe (IORef ())
token) -> do
      sent <- StreamIO -> RPC -> IO (Either () ())
trySend StreamIO
stream RPC
rpc
      case sent of
        Right () -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Left () -> do
          TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> Maybe (IORef ())
-> StreamIO
-> IO ()
evictCachedStream TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar PeerId
pid Maybe (IORef ())
token StreamIO
stream
          Switch
-> TVar Bool
-> TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> IORef (Maybe GossipSubRouter)
-> PeerId
-> RPC
-> IO ()
openAndSend Switch
sw TVar Bool
startedVar TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar IORef (Maybe GossipSubRouter)
routerRef PeerId
pid RPC
rpc
    Maybe (StreamIO, Maybe (IORef ()))
Nothing -> Switch
-> TVar Bool
-> TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> IORef (Maybe GossipSubRouter)
-> PeerId
-> RPC
-> IO ()
openAndSend Switch
sw TVar Bool
startedVar TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar IORef (Maybe GossipSubRouter)
routerRef PeerId
pid RPC
rpc

-- | Open a new outbound stream to a peer and send an RPC.
openAndSend
  :: Switch
  -> TVar Bool
  -> TVar (Map.Map PeerId StreamIO)
  -> TVar (Map.Map PeerId GossipStreamMeta)
  -> IORef (Maybe GossipSubRouter)
  -> PeerId
  -> RPC
  -> IO ()
openAndSend :: Switch
-> TVar Bool
-> TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> IORef (Maybe GossipSubRouter)
-> PeerId
-> RPC
-> IO ()
openAndSend Switch
sw TVar Bool
startedVar TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar IORef (Maybe GossipSubRouter)
routerRef PeerId
pid RPC
rpc = do
  started <- STM Bool -> IO Bool
forall a. STM a -> IO a
atomically (STM Bool -> IO Bool) -> STM Bool -> IO Bool
forall a b. (a -> b) -> a -> b
$ TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar TVar Bool
startedVar
  mOpened <- if started then openStreamToPeer sw pid else pure Nothing
  case mOpened of
    Maybe (Connection, StreamIO, PeerProtocol)
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Just (Connection
conn, StreamIO
stream, PeerProtocol
proto) -> do
      mToken <- TVar Bool
-> TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> Connection
-> StreamIO
-> IO (Maybe (IORef ()))
cacheGossipStream TVar Bool
startedVar TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar PeerId
pid Connection
conn StreamIO
stream
      case mToken of
        Maybe (IORef ())
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Just IORef ()
token -> do
          mRouter <- IORef (Maybe GossipSubRouter) -> IO (Maybe GossipSubRouter)
forall a. IORef a -> IO a
readIORef IORef (Maybe GossipSubRouter)
routerRef
          helloSent <- case mRouter of
            Maybe GossipSubRouter
Nothing -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True
            Just GossipSubRouter
router -> do
              now <- IO UTCTime
getCurrentTime
              addPeer router pid proto True now
              sendHelloChecked router pid stream proto
          sent <- if helloSent then trySend stream rpc else pure (Left ())
          case sent of
            Right () -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
            Left () -> TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> Maybe (IORef ())
-> StreamIO
-> IO ()
evictCachedStream TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar PeerId
pid (IORef () -> Maybe (IORef ())
forall a. a -> Maybe a
Just IORef ()
token) StreamIO
stream

-- | Open a new mux stream to a peer and negotiate GossipSub protocol.
openStreamToPeer :: Switch -> PeerId -> IO (Maybe (Connection, StreamIO, PeerProtocol))
openStreamToPeer :: Switch -> PeerId -> IO (Maybe (Connection, StreamIO, PeerProtocol))
openStreamToPeer Switch
sw PeerId
pid = do
  mConn <- STM (Maybe Connection) -> IO (Maybe Connection)
forall a. STM a -> IO a
atomically (STM (Maybe Connection) -> IO (Maybe Connection))
-> STM (Maybe Connection) -> IO (Maybe Connection)
forall a b. (a -> b) -> a -> b
$ TVar (Map PeerId [Connection]) -> PeerId -> STM (Maybe Connection)
lookupConn (Switch -> TVar (Map PeerId [Connection])
swConnPool Switch
sw) PeerId
pid
  case mConn of
    Maybe Connection
Nothing -> Maybe (Connection, StreamIO, PeerProtocol)
-> IO (Maybe (Connection, StreamIO, PeerProtocol))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (Connection, StreamIO, PeerProtocol)
forall a. Maybe a
Nothing
    Just Connection
conn -> do
      result <- (Maybe (StreamIO, PeerProtocol)
-> Either () (Maybe (StreamIO, PeerProtocol))
forall a b. b -> Either a b
Right (Maybe (StreamIO, PeerProtocol)
 -> Either () (Maybe (StreamIO, PeerProtocol)))
-> IO (Maybe (StreamIO, PeerProtocol))
-> IO (Either () (Maybe (StreamIO, PeerProtocol)))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Switch -> Connection -> IO (Maybe (StreamIO, PeerProtocol))
openAndNegotiate Switch
sw Connection
conn) IO (Either () (Maybe (StreamIO, PeerProtocol)))
-> (SomeException
    -> IO (Either () (Maybe (StreamIO, PeerProtocol))))
-> IO (Either () (Maybe (StreamIO, PeerProtocol)))
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch`
                  (\(SomeException
_ :: SomeException) -> Either () (Maybe (StreamIO, PeerProtocol))
-> IO (Either () (Maybe (StreamIO, PeerProtocol)))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either () (Maybe (StreamIO, PeerProtocol))
forall a b. a -> Either a b
Left ()))
      case result of
        Left () -> Maybe (Connection, StreamIO, PeerProtocol)
-> IO (Maybe (Connection, StreamIO, PeerProtocol))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (Connection, StreamIO, PeerProtocol)
forall a. Maybe a
Nothing
        Right Maybe (StreamIO, PeerProtocol)
mStream -> Maybe (Connection, StreamIO, PeerProtocol)
-> IO (Maybe (Connection, StreamIO, PeerProtocol))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe (Connection, StreamIO, PeerProtocol)
 -> IO (Maybe (Connection, StreamIO, PeerProtocol)))
-> Maybe (Connection, StreamIO, PeerProtocol)
-> IO (Maybe (Connection, StreamIO, PeerProtocol))
forall a b. (a -> b) -> a -> b
$ (\(StreamIO
stream, PeerProtocol
proto) -> (Connection
conn, StreamIO
stream, PeerProtocol
proto)) ((StreamIO, PeerProtocol) -> (Connection, StreamIO, PeerProtocol))
-> Maybe (StreamIO, PeerProtocol)
-> Maybe (Connection, StreamIO, PeerProtocol)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Maybe (StreamIO, PeerProtocol)
mStream

-- | Read a cached stream together with its identity token, when managed.
lookupCachedStream
  :: TVar (Map.Map PeerId StreamIO)
  -> TVar (Map.Map PeerId GossipStreamMeta)
  -> PeerId
  -> STM (Maybe (StreamIO, Maybe (IORef ())))
lookupCachedStream :: TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> STM (Maybe (StreamIO, Maybe (IORef ())))
lookupCachedStream TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar PeerId
pid = do
  streams <- TVar (Map PeerId StreamIO) -> STM (Map PeerId StreamIO)
forall a. TVar a -> STM a
readTVar TVar (Map PeerId StreamIO)
streamsVar
  metadata <- readTVar metaVar
  pure $ (\StreamIO
stream -> (StreamIO
stream, GossipStreamMeta -> IORef ()
gsmToken (GossipStreamMeta -> IORef ())
-> Maybe GossipStreamMeta -> Maybe (IORef ())
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PeerId -> Map PeerId GossipStreamMeta -> Maybe GossipStreamMeta
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PeerId
pid Map PeerId GossipStreamMeta
metadata))
    <$> Map.lookup pid streams

-- | Cache a managed stream only while the node is active.
cacheGossipStream
  :: TVar Bool
  -> TVar (Map.Map PeerId StreamIO)
  -> TVar (Map.Map PeerId GossipStreamMeta)
  -> PeerId
  -> Connection
  -> StreamIO
  -> IO (Maybe (IORef ()))
cacheGossipStream :: TVar Bool
-> TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> Connection
-> StreamIO
-> IO (Maybe (IORef ()))
cacheGossipStream TVar Bool
startedVar TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar PeerId
pid Connection
conn StreamIO
stream = IO (Maybe (IORef ())) -> IO (Maybe (IORef ()))
forall a. IO a -> IO a
mask_ (IO (Maybe (IORef ())) -> IO (Maybe (IORef ())))
-> IO (Maybe (IORef ())) -> IO (Maybe (IORef ()))
forall a b. (a -> b) -> a -> b
$ do
  token <- () -> IO (IORef ())
forall a. a -> IO (IORef a)
newIORef ()
  result <- atomically $ do
    started <- readTVar startedVar
    if not started
      then pure (Left ())
      else do
        streams <- readTVar streamsVar
        metadata <- readTVar metaVar
        writeTVar streamsVar (Map.insert pid stream streams)
        writeTVar metaVar
          (Map.insert pid (GossipStreamMeta (connState conn) token) metadata)
        pure (Right (Map.lookup pid streams))
  case result of
    Left () -> StreamIO -> IO ()
closeQuietly StreamIO
stream IO () -> IO (Maybe (IORef ())) -> IO (Maybe (IORef ()))
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Maybe (IORef ()) -> IO (Maybe (IORef ()))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (IORef ())
forall a. Maybe a
Nothing
    Right Maybe StreamIO
mOld -> (StreamIO -> IO ()) -> Maybe StreamIO -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ StreamIO -> IO ()
closeQuietly Maybe StreamIO
mOld IO () -> IO (Maybe (IORef ())) -> IO (Maybe (IORef ()))
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Maybe (IORef ()) -> IO (Maybe (IORef ()))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (IORef () -> Maybe (IORef ())
forall a. a -> Maybe a
Just IORef ()
token)

-- | Remove the currently cached stream for a peer.
removeCachedStream
  :: TVar (Map.Map PeerId StreamIO)
  -> TVar (Map.Map PeerId GossipStreamMeta)
  -> PeerId
  -> STM (Maybe StreamIO)
removeCachedStream :: TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> STM (Maybe StreamIO)
removeCachedStream TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar PeerId
pid = do
  streams <- TVar (Map PeerId StreamIO) -> STM (Map PeerId StreamIO)
forall a. TVar a -> STM a
readTVar TVar (Map PeerId StreamIO)
streamsVar
  metadata <- readTVar metaVar
  writeTVar streamsVar (Map.delete pid streams)
  writeTVar metaVar (Map.delete pid metadata)
  pure (Map.lookup pid streams)

-- | Close a stream and evict it only if its cache token is still current.
evictCachedStream
  :: TVar (Map.Map PeerId StreamIO)
  -> TVar (Map.Map PeerId GossipStreamMeta)
  -> PeerId
  -> Maybe (IORef ())
  -> StreamIO
  -> IO ()
evictCachedStream :: TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> Maybe (IORef ())
-> StreamIO
-> IO ()
evictCachedStream TVar (Map PeerId StreamIO)
streamsVar TVar (Map PeerId GossipStreamMeta)
metaVar PeerId
pid Maybe (IORef ())
expectedToken StreamIO
stream = IO () -> IO ()
forall a. IO a -> IO a
mask_ (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  _ <- STM (Maybe StreamIO) -> IO (Maybe StreamIO)
forall a. STM a -> IO a
atomically (STM (Maybe StreamIO) -> IO (Maybe StreamIO))
-> STM (Maybe StreamIO) -> IO (Maybe StreamIO)
forall a b. (a -> b) -> a -> b
$ do
    metadata <- TVar (Map PeerId GossipStreamMeta)
-> STM (Map PeerId GossipStreamMeta)
forall a. TVar a -> STM a
readTVar TVar (Map PeerId GossipStreamMeta)
metaVar
    let currentToken = GossipStreamMeta -> IORef ()
gsmToken (GossipStreamMeta -> IORef ())
-> Maybe GossipStreamMeta -> Maybe (IORef ())
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> PeerId -> Map PeerId GossipStreamMeta -> Maybe GossipStreamMeta
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PeerId
pid Map PeerId GossipStreamMeta
metadata
        matches = case (Maybe (IORef ())
expectedToken, Maybe (IORef ())
currentToken) of
          (Maybe (IORef ())
Nothing, Maybe (IORef ())
Nothing) -> Bool
True
          (Just IORef ()
expected, Just IORef ()
current) -> IORef ()
expected IORef () -> IORef () -> Bool
forall a. Eq a => a -> a -> Bool
== IORef ()
current
          (Maybe (IORef ()), Maybe (IORef ()))
_ -> Bool
False
    if matches
      then removeCachedStream streamsVar metaVar pid
      else pure Nothing
  closeQuietly stream

-- | Open a mux stream and negotiate a GossipSub protocol, preferring
-- v1.3 and falling back through v1.2, v1.1, v1.0, and FloodSub.
openAndNegotiate :: Switch -> Connection -> IO (Maybe (StreamIO, PeerProtocol))
openAndNegotiate :: Switch -> Connection -> IO (Maybe (StreamIO, PeerProtocol))
openAndNegotiate Switch
sw Connection
conn = do
  opened <- Switch -> Connection -> IO (Either StreamOpenError StreamIO)
newStream Switch
sw Connection
conn
  case opened of
    Left StreamOpenError
_ -> Maybe (StreamIO, PeerProtocol)
-> IO (Maybe (StreamIO, PeerProtocol))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (StreamIO, PeerProtocol)
forall a. Maybe a
Nothing
    Right StreamIO
stream -> do
      negResult <- StreamIO -> [ProtocolId] -> IO NegotiationResult
negotiateInitiator StreamIO
stream [ProtocolId]
gossipSubProtocolIds
        IO NegotiationResult -> IO () -> IO NegotiationResult
forall a b. IO a -> IO b -> IO a
`onException` StreamIO -> IO ()
closeQuietly StreamIO
stream
      case negResult of
        Accepted ProtocolId
proto -> Maybe (StreamIO, PeerProtocol)
-> IO (Maybe (StreamIO, PeerProtocol))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ((StreamIO, PeerProtocol) -> Maybe (StreamIO, PeerProtocol)
forall a. a -> Maybe a
Just (StreamIO
stream, ProtocolId -> PeerProtocol
protocolFor ProtocolId
proto))
        NegotiationResult
NoProtocol -> do
          StreamIO -> IO ()
closeQuietly StreamIO
stream
          Maybe (StreamIO, PeerProtocol)
-> IO (Maybe (StreamIO, PeerProtocol))
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe (StreamIO, PeerProtocol)
forall a. Maybe a
Nothing

-- | Extract the remote IP bytes (4 for IPv4, 16 for IPv6) from a
-- connection's multiaddr, for P6 IP colocation scoring.
remoteIPBytes :: Connection -> Maybe ByteString
remoteIPBytes :: Connection -> Maybe ByteString
remoteIPBytes Connection
conn = [Protocol] -> Maybe ByteString
go (Multiaddr -> [Protocol]
protocols (Connection -> Multiaddr
connRemoteAddr Connection
conn))
  where
    go :: [Protocol] -> Maybe ByteString
go (IP4 Word32
w  : [Protocol]
_)   = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just (Word32 -> ByteString
word32BE Word32
w)
    go (IP6 ByteString
bs : [Protocol]
_)   = ByteString -> Maybe ByteString
forall a. a -> Maybe a
Just ByteString
bs
    go (Protocol
_      : [Protocol]
ps)  = [Protocol] -> Maybe ByteString
go [Protocol]
ps
    go []             = Maybe ByteString
forall a. Maybe a
Nothing

-- | Try to send an RPC on a stream, catching exceptions.
trySend :: StreamIO -> RPC -> IO (Either () ())
trySend :: StreamIO -> RPC -> IO (Either () ())
trySend StreamIO
stream RPC
rpc =
  (StreamIO -> RPC -> IO ()
writeRPCMessage StreamIO
stream RPC
rpc IO () -> IO (Either () ()) -> IO (Either () ())
forall a b. IO a -> IO b -> IO b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Either () () -> IO (Either () ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either () ()
forall a b. b -> Either a b
Right ()))
    IO (Either () ())
-> (SomeException -> IO (Either () ())) -> IO (Either () ())
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(SomeException
_ :: SomeException) -> Either () () -> IO (Either () ())
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (() -> Either () ()
forall a b. a -> Either a b
Left ()))

-- | Handle an inbound GossipSub stream.
--
-- Reads framed RPCs in a loop and dispatches each to the Router's handleRPC.
-- The peer's negotiated protocol version gates v1.1 control extensions.
-- On error or EOF, removes the inbound peer state. The independent outbound
-- stream stays cached until its own loop fails or its connection closes.
handleGossipSubStream :: GossipSubNode -> StreamIO -> PeerId -> PeerProtocol
                      -> Maybe ByteString -> IO ()
handleGossipSubStream :: GossipSubNode
-> StreamIO -> PeerId -> PeerProtocol -> Maybe ByteString -> IO ()
handleGossipSubStream GossipSubNode
node StreamIO
stream PeerId
pid PeerProtocol
proto Maybe ByteString
mIP = do
  -- Register peer with router (IP feeds P6 colocation scoring)
  now <- IO UTCTime
getCurrentTime
  addPeer (gsnRouter node) pid proto False now
  mapM_ (setPeerIP (gsnRouter node) pid) mIP
  syncSignedPeerRecord node pid
  -- The inbound stream is distinct from the cached outbound stream.
  -- Do not evict the latter when only this direction reaches EOF.
  readLoop `finally` removePeer (gsnRouter node) pid
  where
    readLoop :: IO ()
readLoop = do
      result <- StreamIO -> Int -> IO (Either String RPC)
readRPCMessage StreamIO
stream Int
maxRPCSize
      case result of
        Left String
_ -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()  -- Error/EOF: stop loop
        Right RPC
rpc -> do
          GossipSubRouter -> PeerId -> RPC -> IO ()
handleRPC (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node) PeerId
pid RPC
rpc
          IO ()
readLoop

-- | Feed the peer's signed peer record (obtained via identify, already
-- verified against the authenticated peer id on receipt) from the
-- Switch's peer store into the router, so PRUNE-with-PX can attach it
-- when advertising this peer (#230).
syncSignedPeerRecord :: GossipSubNode -> PeerId -> IO ()
syncSignedPeerRecord :: GossipSubNode -> PeerId -> IO ()
syncSignedPeerRecord GossipSubNode
node PeerId
pid = do
  store <- STM (Map PeerId IdentifyInfo) -> IO (Map PeerId IdentifyInfo)
forall a. STM a -> IO a
atomically (STM (Map PeerId IdentifyInfo) -> IO (Map PeerId IdentifyInfo))
-> STM (Map PeerId IdentifyInfo) -> IO (Map PeerId IdentifyInfo)
forall a b. (a -> b) -> a -> b
$ TVar (Map PeerId IdentifyInfo) -> STM (Map PeerId IdentifyInfo)
forall a. TVar a -> STM a
readTVar (Switch -> TVar (Map PeerId IdentifyInfo)
swPeerStore (GossipSubNode -> Switch
gsnSwitch GossipSubNode
node))
  mapM_ (setSignedPeerRecord (gsnRouter node) pid)
    (Map.lookup pid store >>= idSignedPeerRecord)

-- | 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).
startGossipSub :: GossipSubNode -> IO ()
startGossipSub :: GossipSubNode -> IO ()
startGossipSub GossipSubNode
node = MVar () -> (() -> IO ()) -> IO ()
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar (GossipSubNode -> MVar ()
gsnLifecycleLock GossipSubNode
node) ((() -> IO ()) -> IO ()) -> (() -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \()
_ -> do
  claimed <- GossipSubNode -> IO Bool
claimStart GossipSubNode
node
  when claimed $
    activateGossipSub node `onException` rollbackGossipSubStart node

-- | Arm callbacks, handlers, and heartbeat after claiming the lifecycle.
activateGossipSub :: GossipSubNode -> IO ()
activateGossipSub :: GossipSubNode -> IO ()
activateGossipSub GossipSubNode
node = do
  IORef (Maybe (Connection -> IO ()))
-> Maybe (Connection -> IO ()) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef (GossipSubNode -> IORef (Maybe (Connection -> IO ()))
gsnConnectHook GossipSubNode
node) ((Connection -> IO ()) -> Maybe (Connection -> IO ())
forall a. a -> Maybe a
Just (GossipSubNode -> Connection -> IO ()
onNewConnection GossipSubNode
node))
  IORef (Maybe (Connection -> IO ()))
-> Maybe (Connection -> IO ()) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef (GossipSubNode -> IORef (Maybe (Connection -> IO ()))
gsnDisconnectHook GossipSubNode
node)
    ((Connection -> IO ()) -> Maybe (Connection -> IO ())
forall a. a -> Maybe a
Just (GossipSubNode -> Connection -> IO ()
onGossipDisconnect GossipSubNode
node))
  GossipSubNode -> IO ()
installConnectNotifier GossipSubNode
node
  GossipSubNode -> IO ()
registerHandlers GossipSubNode
node
  hbAsync <- GossipSubRouter -> IO (Async ())
runHeartbeat (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node)
  atomically $ writeTVar (gsnHeartbeat node) (Just hbAsync)
  startDirectMaintenance node

-- | Restore the stopped state if activation fails partway through.
rollbackGossipSubStart :: GossipSubNode -> IO ()
rollbackGossipSubStart :: GossipSubNode -> IO ()
rollbackGossipSubStart GossipSubNode
node = do
  IORef (Maybe (Connection -> IO ()))
-> Maybe (Connection -> IO ()) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef (GossipSubNode -> IORef (Maybe (Connection -> IO ()))
gsnConnectHook GossipSubNode
node) Maybe (Connection -> IO ())
forall a. Maybe a
Nothing
  IORef (Maybe (Connection -> IO ()))
-> Maybe (Connection -> IO ()) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef (GossipSubNode -> IORef (Maybe (Connection -> IO ()))
gsnDisconnectHook GossipSubNode
node) Maybe (Connection -> IO ())
forall a. Maybe a
Nothing
  STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TVar Bool -> Bool -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (GossipSubNode -> TVar Bool
gsnStarted GossipSubNode
node) Bool
False
  (ProtocolId -> IO ()) -> [ProtocolId] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (Switch -> ProtocolId -> IO ()
removeStreamHandler (GossipSubNode -> Switch
gsnSwitch GossipSubNode
node)) [ProtocolId]
gossipSubProtocolIds
  GossipSubNode -> IO ()
closeCachedStreams GossipSubNode
node
  GossipSubNode -> IO ()
stopDirectMaintenance GossipSubNode
node

-- | Claim the start so two concurrent or repeated starts share one heartbeat.
claimStart :: GossipSubNode -> IO Bool
claimStart :: GossipSubNode -> IO Bool
claimStart GossipSubNode
node = STM Bool -> IO Bool
forall a. STM a -> IO a
atomically (STM Bool -> IO Bool) -> STM Bool -> IO Bool
forall a b. (a -> b) -> a -> b
$ do
  started <- TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar (GossipSubNode -> TVar Bool
gsnStarted GossipSubNode
node)
  if started
    then pure False
    else do
      writeTVar (gsnStarted node) True
      pure True

-- | Install the connection-notifier wrapper once. Later starts reuse it.
installConnectNotifier :: GossipSubNode -> IO ()
installConnectNotifier :: GossipSubNode -> IO ()
installConnectNotifier GossipSubNode
node = do
  install <- STM Bool -> IO Bool
forall a. STM a -> IO a
atomically (STM Bool -> IO Bool) -> STM Bool -> IO Bool
forall a b. (a -> b) -> a -> b
$ do
    installed <- TVar Bool -> STM Bool
forall a. TVar a -> STM a
readTVar (GossipSubNode -> TVar Bool
gsnNotifierInstalled GossipSubNode
node)
    if installed
      then pure False
      else do
        writeTVar (gsnNotifierInstalled node) True
        pure True
  when install $ atomically $
    modifyTVar' (swNotifiers (gsnSwitch node))
      (runConnectHook (gsnConnectHook node) :)

-- | Run the current connect hook, or do nothing after stop.
runConnectHook :: IORef (Maybe (Connection -> IO ())) -> Connection -> IO ()
runConnectHook :: IORef (Maybe (Connection -> IO ())) -> Connection -> IO ()
runConnectHook IORef (Maybe (Connection -> IO ()))
hook Connection
conn = do
  mAct <- IORef (Maybe (Connection -> IO ()))
-> IO (Maybe (Connection -> IO ()))
forall a. IORef a -> IO a
readIORef IORef (Maybe (Connection -> IO ()))
hook
  mapM_ ($ conn) mAct

-- | Register inbound stream handlers for every advertised protocol id.
registerHandlers :: GossipSubNode -> IO ()
registerHandlers :: GossipSubNode -> IO ()
registerHandlers GossipSubNode
node =
  (ProtocolId -> IO ()) -> [ProtocolId] -> IO ()
forall (t :: * -> *) (m :: * -> *) a b.
(Foldable t, Monad m) =>
(a -> m b) -> t a -> m ()
mapM_ (\ProtocolId
protoId ->
      Switch -> ProtocolId -> StreamHandler -> IO ()
setStreamHandler (GossipSubNode -> Switch
gsnSwitch GossipSubNode
node) ProtocolId
protoId
        (\Connection
conn StreamIO
stream ->
          GossipSubNode
-> StreamIO -> PeerId -> PeerProtocol -> Maybe ByteString -> IO ()
handleGossipSubStream GossipSubNode
node StreamIO
stream (Connection -> PeerId
connPeerId Connection
conn)
            (ProtocolId -> PeerProtocol
protocolFor ProtocolId
protoId) (Connection -> Maybe ByteString
remoteIPBytes Connection
conn)))
    [ProtocolId]
gossipSubProtocolIds

-- | Called on new connection: open a GossipSub stream to the peer.
-- Caches the stream for outbound writes and starts a read loop
-- on it to receive RPCs sent back by the remote peer (e.g. subscriptions).
onNewConnection :: GossipSubNode -> Connection -> IO ()
onNewConnection :: GossipSubNode -> Connection -> IO ()
onNewConnection GossipSubNode
node Connection
conn = do
  let pid :: PeerId
pid = Connection -> PeerId
connPeerId Connection
conn
  mStream <- Switch -> Connection -> IO (Maybe (StreamIO, PeerProtocol))
openAndNegotiate (GossipSubNode -> Switch
gsnSwitch GossipSubNode
node) Connection
conn
  case mStream of
    Maybe (StreamIO, PeerProtocol)
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Just (StreamIO
stream, PeerProtocol
proto) -> MVar () -> (() -> IO ()) -> IO ()
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar (GossipSubNode -> MVar ()
gsnLifecycleLock GossipSubNode
node) ((() -> IO ()) -> IO ()) -> (() -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \()
_ -> do
      mToken <- TVar Bool
-> TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> Connection
-> StreamIO
-> IO (Maybe (IORef ()))
cacheGossipStream
        (GossipSubNode -> TVar Bool
gsnStarted GossipSubNode
node) (GossipSubNode -> TVar (Map PeerId StreamIO)
gsnStreams GossipSubNode
node) (GossipSubNode -> TVar (Map PeerId GossipStreamMeta)
gsnStreamMeta GossipSubNode
node)
        PeerId
pid Connection
conn StreamIO
stream
      case mToken of
        Maybe (IORef ())
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Just IORef ()
token -> do
          now <- IO UTCTime
getCurrentTime
          addPeer (gsnRouter node) pid proto True now
          mapM_ (setPeerIP (gsnRouter node) pid) (remoteIPBytes conn)
          syncSignedPeerRecord node pid
          sent <- sendHelloChecked (gsnRouter node) pid stream proto
          if sent
            then void $ async $ outboundReadLoop node stream pid token
            else evictCachedStream
              (gsnStreams node) (gsnStreamMeta node) pid (Just token) stream

-- | Send current topic subscriptions to a newly connected peer.
-- This ensures peers joining after we've already subscribed still learn
-- about our subscriptions (standard GossipSub behavior).
-- Writes directly to the stream to avoid any routing issues.
sendCurrentSubscriptions :: GossipSubNode -> StreamIO -> IO ()
sendCurrentSubscriptions :: GossipSubNode -> StreamIO -> IO ()
sendCurrentSubscriptions GossipSubNode
node StreamIO
stream =
  IO Bool -> IO ()
forall (f :: * -> *) a. Functor f => f a -> f ()
void (GossipSubNode -> StreamIO -> IO Bool
sendCurrentSubscriptionsChecked GossipSubNode
node StreamIO
stream)

-- | Send subscriptions and report whether the stream stayed writable.
sendCurrentSubscriptionsChecked :: GossipSubNode -> StreamIO -> IO Bool
sendCurrentSubscriptionsChecked :: GossipSubNode -> StreamIO -> IO Bool
sendCurrentSubscriptionsChecked GossipSubNode
node StreamIO
stream = do
  rpc <- GossipSubRouter -> IO RPC
currentSubscriptionsRPC (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node)
  if null (rpcSubscriptions rpc)
    then pure True
    else either (const False) (const True) <$> trySend stream rpc

sendHelloChecked :: GossipSubRouter -> PeerId -> StreamIO -> PeerProtocol -> IO Bool
sendHelloChecked :: GossipSubRouter -> PeerId -> StreamIO -> PeerProtocol -> IO Bool
sendHelloChecked GossipSubRouter
router PeerId
pid StreamIO
stream PeerProtocol
proto = do
  subscriptions <- GossipSubRouter -> IO RPC
currentSubscriptionsRPC GossipSubRouter
router
  hello <- attachExtensionsToHello router proto subscriptions
  if hello == emptyRPC
    then pure True
    else do
      result <- trySend stream hello
      case result of
        Left () -> Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False
        Right () -> do
          Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (RPC -> Bool
hasExtensionAdvertisement RPC
hello) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
            GossipSubRouter -> PeerId -> IO ()
markExtensionAdvertisementSent GossipSubRouter
router PeerId
pid
          Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
True

hasExtensionAdvertisement :: RPC -> Bool
hasExtensionAdvertisement :: RPC -> Bool
hasExtensionAdvertisement RPC
rpc =
  Bool -> (ControlMessage -> Bool) -> Maybe ControlMessage -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (Maybe ControlExtensions -> Bool
forall a. Maybe a -> Bool
isJust (Maybe ControlExtensions -> Bool)
-> (ControlMessage -> Maybe ControlExtensions)
-> ControlMessage
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ControlMessage -> Maybe ControlExtensions
Types.ctrlExtensions) (RPC -> Maybe ControlMessage
rpcControl RPC
rpc)

currentSubscriptionsRPC :: GossipSubRouter -> IO RPC
currentSubscriptionsRPC :: GossipSubRouter -> IO RPC
currentSubscriptionsRPC GossipSubRouter
router = do
  (subs, partialTopics) <- STM (Set ProtocolId, Map ProtocolId PartialTopicMode)
-> IO (Set ProtocolId, Map ProtocolId PartialTopicMode)
forall a. STM a -> IO a
atomically (STM (Set ProtocolId, Map ProtocolId PartialTopicMode)
 -> IO (Set ProtocolId, Map ProtocolId PartialTopicMode))
-> STM (Set ProtocolId, Map ProtocolId PartialTopicMode)
-> IO (Set ProtocolId, Map ProtocolId PartialTopicMode)
forall a b. (a -> b) -> a -> b
$
    (,) (Set ProtocolId
 -> Map ProtocolId PartialTopicMode
 -> (Set ProtocolId, Map ProtocolId PartialTopicMode))
-> STM (Set ProtocolId)
-> STM
     (Map ProtocolId PartialTopicMode
      -> (Set ProtocolId, Map ProtocolId PartialTopicMode))
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TVar (Set ProtocolId) -> STM (Set ProtocolId)
forall a. TVar a -> STM a
readTVar (GossipSubRouter -> TVar (Set ProtocolId)
gsSubscriptions GossipSubRouter
router) STM
  (Map ProtocolId PartialTopicMode
   -> (Set ProtocolId, Map ProtocolId PartialTopicMode))
-> STM (Map ProtocolId PartialTopicMode)
-> STM (Set ProtocolId, Map ProtocolId PartialTopicMode)
forall a b. STM (a -> b) -> STM a -> STM b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> TVar (Map ProtocolId PartialTopicMode)
-> STM (Map ProtocolId PartialTopicMode)
forall a. TVar a -> STM a
readTVar (GossipSubRouter -> TVar (Map ProtocolId PartialTopicMode)
gsPartialTopics GossipSubRouter
router)
  pure emptyRPC
    { rpcSubscriptions = map (subscriptionOption partialTopics) (Set.toList subs) }

subscriptionOption :: Map.Map Topic PartialTopicMode -> Topic -> SubOpts
subscriptionOption :: Map ProtocolId PartialTopicMode -> ProtocolId -> SubOpts
subscriptionOption Map ProtocolId PartialTopicMode
partialTopics ProtocolId
topic = SubOpts
  { subSubscribe :: Bool
subSubscribe = Bool
True
  , subTopicId :: ProtocolId
subTopicId = ProtocolId
topic
  , subRequestsPartial :: Bool
subRequestsPartial = Maybe PartialTopicMode
mode Maybe PartialTopicMode -> Maybe PartialTopicMode -> Bool
forall a. Eq a => a -> a -> Bool
== PartialTopicMode -> Maybe PartialTopicMode
forall a. a -> Maybe a
Just PartialTopicMode
Types.RequestsPartialMessages
  , subSupportsSendingPartial :: Bool
subSupportsSendingPartial = Maybe PartialTopicMode -> Bool
forall a. Maybe a -> Bool
isJust Maybe PartialTopicMode
mode
  }
 where
  mode :: Maybe PartialTopicMode
mode = ProtocolId
-> Map ProtocolId PartialTopicMode -> Maybe PartialTopicMode
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup ProtocolId
topic Map ProtocolId PartialTopicMode
partialTopics

-- | Read loop on the outbound stream.
-- Handles RPCs sent back by the remote peer on the same yamux stream
-- (e.g. subscription announcements). Does NOT remove the peer on
-- EOF since the inbound handler or another mechanism manages peer lifecycle.
outboundReadLoop :: GossipSubNode -> StreamIO -> PeerId -> IORef () -> IO ()
outboundReadLoop :: GossipSubNode -> StreamIO -> PeerId -> IORef () -> IO ()
outboundReadLoop GossipSubNode
node StreamIO
stream PeerId
pid IORef ()
token =
  IO ()
loop IO () -> IO () -> IO ()
forall a b. IO a -> IO b -> IO a
`finally` TVar (Map PeerId StreamIO)
-> TVar (Map PeerId GossipStreamMeta)
-> PeerId
-> Maybe (IORef ())
-> StreamIO
-> IO ()
evictCachedStream
    (GossipSubNode -> TVar (Map PeerId StreamIO)
gsnStreams GossipSubNode
node) (GossipSubNode -> TVar (Map PeerId GossipStreamMeta)
gsnStreamMeta GossipSubNode
node) PeerId
pid (IORef () -> Maybe (IORef ())
forall a. a -> Maybe a
Just IORef ()
token) StreamIO
stream
  where
    loop :: IO ()
loop = do
      result <- StreamIO -> Int -> IO (Either String RPC)
readRPCMessage StreamIO
stream Int
maxRPCSize
      case result of
        Left String
_ -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
        Right RPC
rpc -> do
          GossipSubRouter -> PeerId -> RPC -> IO ()
handleRPC (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node) PeerId
pid RPC
rpc
          IO ()
loop

-- | 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).
stopGossipSub :: GossipSubNode -> IO ()
stopGossipSub :: GossipSubNode -> IO ()
stopGossipSub GossipSubNode
node = MVar () -> (() -> IO ()) -> IO ()
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar (GossipSubNode -> MVar ()
gsnLifecycleLock GossipSubNode
node) ((() -> IO ()) -> IO ()) -> (() -> IO ()) -> IO ()
forall a b. (a -> b) -> a -> b
$ \()
_ -> do
  IORef (Maybe (Connection -> IO ()))
-> Maybe (Connection -> IO ()) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef (GossipSubNode -> IORef (Maybe (Connection -> IO ()))
gsnConnectHook GossipSubNode
node) Maybe (Connection -> IO ())
forall a. Maybe a
Nothing
  IORef (Maybe (Connection -> IO ()))
-> Maybe (Connection -> IO ()) -> IO ()
forall a. IORef a -> a -> IO ()
writeIORef (GossipSubNode -> IORef (Maybe (Connection -> IO ()))
gsnDisconnectHook GossipSubNode
node) Maybe (Connection -> IO ())
forall a. Maybe a
Nothing
  STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ TVar Bool -> Bool -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (GossipSubNode -> TVar Bool
gsnStarted GossipSubNode
node) Bool
False
  mHb <- STM (Maybe (Async ())) -> IO (Maybe (Async ()))
forall a. STM a -> IO a
atomically (STM (Maybe (Async ())) -> IO (Maybe (Async ())))
-> STM (Maybe (Async ())) -> IO (Maybe (Async ()))
forall a b. (a -> b) -> a -> b
$ do
    hb <- TVar (Maybe (Async ())) -> STM (Maybe (Async ()))
forall a. TVar a -> STM a
readTVar (GossipSubNode -> TVar (Maybe (Async ()))
gsnHeartbeat GossipSubNode
node)
    writeTVar (gsnHeartbeat node) Nothing
    pure hb
  case mHb of
    Just Async ()
hbAsync -> Async () -> IO ()
forall a. Async a -> IO ()
cancel Async ()
hbAsync IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` (\(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ())
    Maybe (Async ())
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
  mapM_ (removeStreamHandler (gsnSwitch node)) gossipSubProtocolIds
  closeCachedStreams node
  stopDirectMaintenance node

-- | Close every cached outbound stream, releasing its resource slot.
closeCachedStreams :: GossipSubNode -> IO ()
closeCachedStreams :: GossipSubNode -> IO ()
closeCachedStreams GossipSubNode
node = IO () -> IO ()
forall a. IO a -> IO a
mask_ (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  streams <- STM [StreamIO] -> IO [StreamIO]
forall a. STM a -> IO a
atomically (STM [StreamIO] -> IO [StreamIO])
-> STM [StreamIO] -> IO [StreamIO]
forall a b. (a -> b) -> a -> b
$ do
    m <- TVar (Map PeerId StreamIO) -> STM (Map PeerId StreamIO)
forall a. TVar a -> STM a
readTVar (GossipSubNode -> TVar (Map PeerId StreamIO)
gsnStreams GossipSubNode
node)
    writeTVar (gsnStreams node) Map.empty
    writeTVar (gsnStreamMeta node) Map.empty
    pure (Map.elems m)
  mapM_ closeQuietly streams

-- | Run the disconnect hook unless 'stopGossipSub' has cleared it.
runGossipDisconnect :: IORef (Maybe (Connection -> IO ())) -> Connection -> IO ()
runGossipDisconnect :: IORef (Maybe (Connection -> IO ())) -> Connection -> IO ()
runGossipDisconnect IORef (Maybe (Connection -> IO ()))
hook Connection
conn = do
  mAct <- IORef (Maybe (Connection -> IO ()))
-> IO (Maybe (Connection -> IO ()))
forall a. IORef a -> IO a
readIORef IORef (Maybe (Connection -> IO ()))
hook
  mapM_ ($ conn) mAct

-- | Drop a cached stream when its owning connection closes.
dropCachedGossipStream :: GossipSubNode -> Connection -> IO ()
dropCachedGossipStream :: GossipSubNode -> Connection -> IO ()
dropCachedGossipStream GossipSubNode
node Connection
conn = do
  let pid :: PeerId
pid = Connection -> PeerId
connPeerId Connection
conn
  mStream <- STM (Maybe StreamIO) -> IO (Maybe StreamIO)
forall a. STM a -> IO a
atomically (STM (Maybe StreamIO) -> IO (Maybe StreamIO))
-> STM (Maybe StreamIO) -> IO (Maybe StreamIO)
forall a b. (a -> b) -> a -> b
$ do
    metadata <- TVar (Map PeerId GossipStreamMeta)
-> STM (Map PeerId GossipStreamMeta)
forall a. TVar a -> STM a
readTVar (GossipSubNode -> TVar (Map PeerId GossipStreamMeta)
gsnStreamMeta GossipSubNode
node)
    remaining <- lookupConn (swConnPool (gsnSwitch node)) pid
    let owned = Bool
-> (GossipStreamMeta -> Bool) -> Maybe GossipStreamMeta -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False ((TVar ConnState -> TVar ConnState -> Bool
forall a. Eq a => a -> a -> Bool
== Connection -> TVar ConnState
connState Connection
conn) (TVar ConnState -> Bool)
-> (GossipStreamMeta -> TVar ConnState) -> GossipStreamMeta -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. GossipStreamMeta -> TVar ConnState
gsmOwner) (PeerId -> Map PeerId GossipStreamMeta -> Maybe GossipStreamMeta
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PeerId
pid Map PeerId GossipStreamMeta
metadata)
        unownedLast = PeerId -> Map PeerId GossipStreamMeta -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.notMember PeerId
pid Map PeerId GossipStreamMeta
metadata Bool -> Bool -> Bool
&& Maybe Connection -> Bool
forall a. Maybe a -> Bool
isNothing Maybe Connection
remaining
    if owned || unownedLast
      then removeCachedStream (gsnStreams node) (gsnStreamMeta node) pid
      else pure Nothing
  mapM_ closeQuietly mStream

-- | Start the direct-peer checker. The first pass runs immediately.
startDirectMaintenance :: GossipSubNode -> IO ()
startDirectMaintenance :: GossipSubNode -> IO ()
startDirectMaintenance GossipSubNode
node = do
  worker <- IO () -> IO (Async ())
forall a. IO a -> IO (Async a)
async (IO () -> IO (Async ())) -> IO () -> IO (Async ())
forall a b. (a -> b) -> a -> b
$
    Switch -> GossipSubRouter -> TVar Bool -> DirectDialSlots -> IO ()
runDirectConnectLoop (GossipSubNode -> Switch
gsnSwitch GossipSubNode
node) (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node)
      (GossipSubNode -> TVar Bool
gsnStarted GossipSubNode
node) (GossipSubNode -> DirectDialSlots
gsnDirectSlots GossipSubNode
node)
  atomically $ writeTVar (gsnDirectConnect node) (Just worker)

-- | Cancel the checker and any dial it has claimed.
stopDirectMaintenance :: GossipSubNode -> IO ()
stopDirectMaintenance :: GossipSubNode -> IO ()
stopDirectMaintenance GossipSubNode
node = do
  worker <- STM (Maybe (Async ())) -> IO (Maybe (Async ()))
forall a. STM a -> IO a
atomically (STM (Maybe (Async ())) -> IO (Maybe (Async ())))
-> STM (Maybe (Async ())) -> IO (Maybe (Async ()))
forall a b. (a -> b) -> a -> b
$ do
    current <- TVar (Maybe (Async ())) -> STM (Maybe (Async ()))
forall a. TVar a -> STM a
readTVar (GossipSubNode -> TVar (Maybe (Async ()))
gsnDirectConnect GossipSubNode
node)
    writeTVar (gsnDirectConnect node) Nothing
    pure current
  mapM_ cancelQuiet worker
  cancelDirectDials (gsnDirectSlots node)

-- | Drop the cached stream, then redial if this was a direct peer.
onGossipDisconnect :: GossipSubNode -> Connection -> IO ()
onGossipDisconnect :: GossipSubNode -> Connection -> IO ()
onGossipDisconnect GossipSubNode
node Connection
conn = do
  GossipSubNode -> Connection -> IO ()
dropCachedGossipStream GossipSubNode
node Connection
conn
  started <- TVar Bool -> IO Bool
forall a. TVar a -> IO a
readTVarIO (GossipSubNode -> TVar Bool
gsnStarted GossipSubNode
node)
  when started $ reconnectDirectPeer (gsnSwitch node) (gsnRouter node)
    (gsnDirectSlots node) (connPeerId conn)

cancelQuiet :: Async () -> IO ()
cancelQuiet :: Async () -> IO ()
cancelQuiet Async ()
worker =
  Async () -> IO ()
forall a. Async a -> IO ()
cancel Async ()
worker IO () -> (SomeException -> IO ()) -> IO ()
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
`catch` \(SomeException
_ :: SomeException) -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()

-- | Enable partial messages before starting the node.
enablePartialMessages
  :: GossipSubNode
  -> PartialMessagesExtension state
  -> IO (Either PartialMessagesError ())
enablePartialMessages :: forall state.
GossipSubNode
-> PartialMessagesExtension state
-> IO (Either PartialMessagesError ())
enablePartialMessages GossipSubNode
node PartialMessagesExtension state
extension =
  MVar ()
-> (() -> IO (Either PartialMessagesError ()))
-> IO (Either PartialMessagesError ())
forall a b. MVar a -> (a -> IO b) -> IO b
withMVar (GossipSubNode -> MVar ()
gsnLifecycleLock GossipSubNode
node) ((() -> IO (Either PartialMessagesError ()))
 -> IO (Either PartialMessagesError ()))
-> (() -> IO (Either PartialMessagesError ()))
-> IO (Either PartialMessagesError ())
forall a b. (a -> b) -> a -> b
$ \()
_ -> do
    started <- TVar Bool -> IO Bool
forall a. TVar a -> IO a
readTVarIO (GossipSubNode -> TVar Bool
gsnStarted GossipSubNode
node)
    if started
      then pure (Left PartialMessagesNodeStarted)
      else PartialMessages.installPartialMessages (gsnRouter node) extension

-- | Subscribe to a topic.
gossipJoin :: GossipSubNode -> Topic -> IO ()
gossipJoin :: GossipSubNode -> ProtocolId -> IO ()
gossipJoin GossipSubNode
node ProtocolId
topic = GossipSubRouter -> ProtocolId -> IO ()
join (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node) ProtocolId
topic

-- | Subscribe while supporting or requesting partial messages.
gossipJoinPartial
  :: GossipSubNode
  -> Topic
  -> PartialTopicMode
  -> IO (Either PartialMessagesError ())
gossipJoinPartial :: GossipSubNode
-> ProtocolId
-> PartialTopicMode
-> IO (Either PartialMessagesError ())
gossipJoinPartial GossipSubNode
node ProtocolId
topic PartialTopicMode
mode = do
  installed <- Maybe PartialMessagesHooks -> Bool
forall a. Maybe a -> Bool
isJust (Maybe PartialMessagesHooks -> Bool)
-> IO (Maybe PartialMessagesHooks) -> IO Bool
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TVar (Maybe PartialMessagesHooks)
-> IO (Maybe PartialMessagesHooks)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Maybe PartialMessagesHooks)
gsPartialMessagesHooks (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node))
  if installed
    then joinPartial (gsnRouter node) topic mode >> pure (Right ())
    else pure (Left PartialMessagesNotInstalled)

-- | Unsubscribe from a topic.
gossipLeave :: GossipSubNode -> Topic -> IO ()
gossipLeave :: GossipSubNode -> ProtocolId -> IO ()
gossipLeave GossipSubNode
node ProtocolId
topic = GossipSubRouter -> ProtocolId -> IO ()
leave (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node) ProtocolId
topic

-- | Publish a message to a topic (signed with the Switch's identity key).
gossipPublish :: GossipSubNode -> Topic -> ByteString -> IO ()
gossipPublish :: GossipSubNode -> ProtocolId -> ByteString -> IO ()
gossipPublish GossipSubNode
node ProtocolId
topic ByteString
payload =
  GossipSubRouter
-> ProtocolId -> ByteString -> Maybe KeyPair -> IO ()
publish (GossipSubNode -> GossipSubRouter
gsnRouter GossipSubNode
node) ProtocolId
topic ByteString
payload (KeyPair -> Maybe KeyPair
forall a. a -> Maybe a
Just (Switch -> KeyPair
swIdentityKey (GossipSubNode -> Switch
gsnSwitch GossipSubNode
node)))