-- | GossipSub v1.3 extension advertisement and dispatch.
module LibP2P.Protocol.GossipSub.Extensions
  ( attachExtensionsToHello
  , markExtensionAdvertisementSent
  , handleExtensionAdvertisement
  , handlePartialMessageRPC
  , peerSupportsPartialExtension
  , peerRequestsPartial
  , peerSupportsSendingPartial
  , localPartialMode
  , runPartialHeartbeat
  , emitPartialGossip
  , notifyPartialPeerDisconnected
  ) where

import Control.Concurrent.STM
import Control.Monad (when)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe, isJust)
import qualified Data.Set as Set
import LibP2P.Crypto.PeerId (PeerId)
import LibP2P.Protocol.GossipSub.Score (addP7Penalty)
import LibP2P.Protocol.GossipSub.Types

-- | Add our supported extensions to the first outbound v1.3 RPC.
attachExtensionsToHello :: GossipSubRouter -> PeerProtocol -> RPC -> IO RPC
attachExtensionsToHello :: GossipSubRouter -> PeerProtocol -> RPC -> IO RPC
attachExtensionsToHello GossipSubRouter
router PeerProtocol
proto RPC
rpc
  | PeerProtocol
proto PeerProtocol -> PeerProtocol -> Bool
forall a. Eq a => a -> a -> Bool
/= PeerProtocol
GossipSubV13Peer = RPC -> IO RPC
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure RPC
rpc
  | Bool
otherwise = do
      hooks <- TVar (Maybe PartialMessagesHooks)
-> IO (Maybe PartialMessagesHooks)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Maybe PartialMessagesHooks)
gsPartialMessagesHooks GossipSubRouter
router)
      pure $ case hooks of
        Maybe PartialMessagesHooks
Nothing -> RPC
rpc
        Just PartialMessagesHooks
_ ->
          RPC
rpc
            { rpcControl =
                Just
                  control
                    { ctrlExtensions = Just (ControlExtensions True)
                    }
            }
 where
  control :: ControlMessage
control = ControlMessage -> Maybe ControlMessage -> ControlMessage
forall a. a -> Maybe a -> a
fromMaybe ControlMessage
emptyControlMessage (RPC -> Maybe ControlMessage
rpcControl RPC
rpc)

-- | Record that our extension advertisement was successfully sent.
markExtensionAdvertisementSent :: GossipSubRouter -> PeerId -> IO ()
markExtensionAdvertisementSent :: GossipSubRouter -> PeerId -> IO ()
markExtensionAdvertisementSent GossipSubRouter
router PeerId
pid =
  STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$
    TVar (Set PeerId) -> (Set PeerId -> Set PeerId) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (GossipSubRouter -> TVar (Set PeerId)
gsSentExtensions GossipSubRouter
router) (PeerId -> Set PeerId -> Set PeerId
forall a. Ord a => a -> Set a -> Set a
Set.insert PeerId
pid)

-- | Record the first v1.3 extension advertisement and penalize repeats.
handleExtensionAdvertisement :: GossipSubRouter -> PeerId -> RPC -> IO ()
handleExtensionAdvertisement :: GossipSubRouter -> PeerId -> RPC -> IO ()
handleExtensionAdvertisement GossipSubRouter
router PeerId
sender RPC
rpc = do
  peers <- TVar (Map PeerId PeerState) -> IO (Map PeerId PeerState)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Map PeerId PeerState)
gsPeers GossipSubRouter
router)
  if not (supportsExtensions peers sender)
    then pure ()
    else atomically $ do
      advertised <- readTVar (gsPeerExtensions router)
      let extension = RPC -> Maybe ControlMessage
rpcControl RPC
rpc Maybe ControlMessage
-> (ControlMessage -> Maybe ControlExtensions)
-> Maybe ControlExtensions
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ControlMessage -> Maybe ControlExtensions
ctrlExtensions
      if Map.member sender advertised
        then when (isJust extension) (penalize router sender)
        else
          writeTVar
            (gsPeerExtensions router)
            (Map.insert sender (fromMaybe noExtensions extension) advertised)

-- | Dispatch a partial-message RPC only when both peers advertised support.
handlePartialMessageRPC :: GossipSubRouter -> PeerId -> RPC -> IO ()
handlePartialMessageRPC :: GossipSubRouter -> PeerId -> RPC -> IO ()
handlePartialMessageRPC GossipSubRouter
router PeerId
sender RPC
rpc =
  case RPC -> Maybe PartialMessage
rpcPartial RPC
rpc of
    Maybe PartialMessage
Nothing -> () -> IO ()
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure ()
    Just PartialMessage
partial -> do
      hooks <- TVar (Maybe PartialMessagesHooks)
-> IO (Maybe PartialMessagesHooks)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Maybe PartialMessagesHooks)
gsPartialMessagesHooks GossipSubRouter
router)
      supported <- peerSupportsPartialExtension router sender
      case hooks of
        Just PartialMessagesHooks
runtime | Bool
supported -> do
          violation <- PartialMessagesHooks -> PeerId -> PartialMessage -> IO Bool
pmhHandleRPC PartialMessagesHooks
runtime PeerId
sender PartialMessage
partial
          when violation $ atomically (penalize router sender)
        Maybe PartialMessagesHooks
_ -> STM () -> IO ()
forall a. STM a -> IO a
atomically (GossipSubRouter -> PeerId -> STM ()
penalize GossipSubRouter
router PeerId
sender)

-- | Whether a peer advertised the partial-messages extension on v1.3.
peerSupportsPartialExtension :: GossipSubRouter -> PeerId -> IO Bool
peerSupportsPartialExtension :: GossipSubRouter -> PeerId -> IO Bool
peerSupportsPartialExtension GossipSubRouter
router PeerId
pid = do
  advertised <- TVar (Map PeerId ControlExtensions)
-> IO (Map PeerId ControlExtensions)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Map PeerId ControlExtensions)
gsPeerExtensions GossipSubRouter
router)
  sent <- readTVarIO (gsSentExtensions router)
  pure $
    Set.member pid sent
      && maybe False extPartialMessages (Map.lookup pid advertised)

-- | Whether a peer requested partial messages for a topic.
peerRequestsPartial :: GossipSubRouter -> PeerId -> Topic -> IO Bool
peerRequestsPartial :: GossipSubRouter -> PeerId -> Topic -> IO Bool
peerRequestsPartial GossipSubRouter
router PeerId
pid Topic
topic = do
  peers <- TVar (Map PeerId PeerState) -> IO (Map PeerId PeerState)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Map PeerId PeerState)
gsPeers GossipSubRouter
router)
  pure $ case Map.lookup pid peers >>= Map.lookup topic . psPartialTopics of
    Just PartialTopicMode
RequestsPartialMessages -> Bool
True
    Maybe PartialTopicMode
_ -> Bool
False

-- | Whether a peer can send partial messages for a topic.
peerSupportsSendingPartial :: GossipSubRouter -> PeerId -> Topic -> IO Bool
peerSupportsSendingPartial :: GossipSubRouter -> PeerId -> Topic -> IO Bool
peerSupportsSendingPartial GossipSubRouter
router PeerId
pid Topic
topic = do
  peers <- TVar (Map PeerId PeerState) -> IO (Map PeerId PeerState)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Map PeerId PeerState)
gsPeers GossipSubRouter
router)
  pure $ case Map.lookup pid peers >>= Map.lookup topic . psPartialTopics of
    Just PartialTopicMode
SupportsPartialMessages -> Bool
True
    Just PartialTopicMode
RequestsPartialMessages -> Bool
True
    Maybe PartialTopicMode
Nothing -> Bool
False

-- | Local partial-message mode for a subscribed topic.
localPartialMode :: GossipSubRouter -> Topic -> IO (Maybe PartialTopicMode)
localPartialMode :: GossipSubRouter -> Topic -> IO (Maybe PartialTopicMode)
localPartialMode GossipSubRouter
router Topic
topic =
  Topic -> Map Topic PartialTopicMode -> Maybe PartialTopicMode
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup Topic
topic (Map Topic PartialTopicMode -> Maybe PartialTopicMode)
-> IO (Map Topic PartialTopicMode) -> IO (Maybe PartialTopicMode)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> TVar (Map Topic PartialTopicMode)
-> IO (Map Topic PartialTopicMode)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Map Topic PartialTopicMode)
gsPartialTopics GossipSubRouter
router)

-- | Run partial-message state expiry during the GossipSub heartbeat.
runPartialHeartbeat :: GossipSubRouter -> IO ()
runPartialHeartbeat :: GossipSubRouter -> IO ()
runPartialHeartbeat GossipSubRouter
router = do
  hooks <- TVar (Maybe PartialMessagesHooks)
-> IO (Maybe PartialMessagesHooks)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Maybe PartialMessagesHooks)
gsPartialMessagesHooks GossipSubRouter
router)
  mapM_ pmhHeartbeat hooks

-- | Ask the partial-message runtime to gossip groups to selected peers.
emitPartialGossip :: GossipSubRouter -> Topic -> [PeerId] -> IO ()
emitPartialGossip :: GossipSubRouter -> Topic -> [PeerId] -> IO ()
emitPartialGossip GossipSubRouter
router Topic
topic [PeerId]
peers = do
  hooks <- TVar (Maybe PartialMessagesHooks)
-> IO (Maybe PartialMessagesHooks)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Maybe PartialMessagesHooks)
gsPartialMessagesHooks GossipSubRouter
router)
  mapM_ (\PartialMessagesHooks
runtime -> PartialMessagesHooks -> Topic -> [PeerId] -> IO ()
pmhEmitGossip PartialMessagesHooks
runtime Topic
topic [PeerId]
peers) hooks

-- | Remove per-peer partial-message state after disconnect.
notifyPartialPeerDisconnected :: GossipSubRouter -> PeerId -> IO ()
notifyPartialPeerDisconnected :: GossipSubRouter -> PeerId -> IO ()
notifyPartialPeerDisconnected GossipSubRouter
router PeerId
pid = do
  hooks <- TVar (Maybe PartialMessagesHooks)
-> IO (Maybe PartialMessagesHooks)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Maybe PartialMessagesHooks)
gsPartialMessagesHooks GossipSubRouter
router)
  mapM_ (`pmhPeerDisconnected` pid) hooks

supportsExtensions :: Map.Map PeerId PeerState -> PeerId -> Bool
supportsExtensions :: Map PeerId PeerState -> PeerId -> Bool
supportsExtensions Map PeerId PeerState
peers PeerId
pid =
  Bool -> (PeerState -> Bool) -> Maybe PeerState -> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False ((PeerProtocol -> PeerProtocol -> Bool
forall a. Eq a => a -> a -> Bool
== PeerProtocol
GossipSubV13Peer) (PeerProtocol -> Bool)
-> (PeerState -> PeerProtocol) -> PeerState -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. PeerState -> PeerProtocol
psProtocol) (PeerId -> Map PeerId PeerState -> Maybe PeerState
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PeerId
pid Map PeerId PeerState
peers)

noExtensions :: ControlExtensions
noExtensions :: ControlExtensions
noExtensions = Bool -> ControlExtensions
ControlExtensions Bool
False

penalize :: GossipSubRouter -> PeerId -> STM ()
penalize :: GossipSubRouter -> PeerId -> STM ()
penalize GossipSubRouter
router PeerId
pid =
  TVar (Map PeerId PeerState)
-> (Map PeerId PeerState -> Map PeerId PeerState) -> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (GossipSubRouter -> TVar (Map PeerId PeerState)
gsPeers GossipSubRouter
router) ((PeerState -> PeerState)
-> PeerId -> Map PeerId PeerState -> Map PeerId PeerState
forall k a. Ord k => (a -> a) -> k -> Map k a -> Map k a
Map.adjust PeerState -> PeerState
addP7Penalty PeerId
pid)