-- | GossipSub v1.2 IDONTWANT processing and bounded suppression state.
module LibP2P.Protocol.GossipSub.IDontWant (
  announceIDontWant,
  handleIDontWant,
  peerRejectsMessage,
  filterAllowedPeers,
  expireIDontWantState,
) where

import Control.Concurrent.STM
import Control.Monad (filterM, unless, when)
import Crypto.Hash qualified as Hash
import Data.ByteArray qualified as BA
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import LibP2P.Crypto.PeerId (PeerId)
import LibP2P.Protocol.GossipSub.Extensions
  ( localPartialMode
  , peerSupportsPartialExtension
  , peerSupportsSendingPartial
  )
import LibP2P.Protocol.GossipSub.Types

{- | Immediately tell v1.2 mesh peers not to send a duplicate large message.
The propagation source is excluded and older protocol versions never receive
the v1.2 control field.
-}
announceIDontWant :: GossipSubRouter -> PeerId -> PubSubMessage -> IO ()
announceIDontWant :: GossipSubRouter -> PeerId -> PubSubMessage -> IO ()
announceIDontWant GossipSubRouter
router PeerId
sender PubSubMessage
msg =
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
when (ByteString -> Int
BS.length (PubSubMessage -> ByteString
msgData PubSubMessage
msg) Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= GossipSubParams -> Int
paramIDontWantMessageThreshold GossipSubParams
params) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
    let mid :: ByteString
mid = GossipSubParams -> PubSubMessage -> ByteString
paramMessageIdFn GossipSubParams
params PubSubMessage
msg
    seen <- TVar (Map ByteString UTCTime) -> IO (Map ByteString UTCTime)
forall a. TVar a -> IO a
readTVarIO (GossipSubRouter -> TVar (Map ByteString UTCTime)
gsSeen GossipSubRouter
router)
    unless (Map.member mid seen) $ do
      mesh <- readTVarIO (gsMesh router)
      peers <- readTVarIO (gsPeers router)
      let topicPeers = Set PeerId -> Topic -> Map Topic (Set PeerId) -> Set PeerId
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Set PeerId
forall a. Set a
Set.empty (PubSubMessage -> Topic
msgTopic PubSubMessage
msg) Map Topic (Set PeerId)
mesh
          targets = (PeerId -> Bool) -> Set PeerId -> Set PeerId
forall a. (a -> Bool) -> Set a -> Set a
Set.filter (Map PeerId PeerState -> PeerId -> Bool
supportsIDontWant Map PeerId PeerState
peers) (PeerId -> Set PeerId -> Set PeerId
forall a. Ord a => a -> Set a -> Set a
Set.delete PeerId
sender Set PeerId
topicPeers)
          rpc =
            RPC
emptyRPC
              { rpcControl =
                  Just
                    emptyControlMessage
                      { ctrlIDontWant = [IDontWant [mid]]
                      }
              }
      recipients <- filterM (shouldReceiveIDontWant router (msgTopic msg))
        (Set.toList targets)
      mapM_ (\PeerId
pid -> GossipSubRouter -> PeerId -> RPC -> IO ()
gsSendRPC GossipSubRouter
router PeerId
pid RPC
rpc) recipients
 where
  params :: GossipSubParams
params = GossipSubRouter -> GossipSubParams
gsParams GossipSubRouter
router

supportsIDontWant :: Map.Map PeerId PeerState -> PeerId -> Bool
supportsIDontWant :: Map PeerId PeerState -> PeerId -> Bool
supportsIDontWant 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
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [PeerProtocol
GossipSubV13Peer, PeerProtocol
GossipSubV12Peer]) (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)

shouldReceiveIDontWant :: GossipSubRouter -> Topic -> PeerId -> IO Bool
shouldReceiveIDontWant :: GossipSubRouter -> Topic -> PeerId -> IO Bool
shouldReceiveIDontWant GossipSubRouter
router Topic
topic PeerId
pid = do
  mode <- GossipSubRouter -> Topic -> IO (Maybe PartialTopicMode)
localPartialMode GossipSubRouter
router Topic
topic
  peerSupports <- peerSupportsSendingPartial router pid topic
  extension <- peerSupportsPartialExtension router pid
  pure (mode /= Just RequestsPartialMessages || not (peerSupports && extension))

-- | Record bounded IDONTWANT state received from a peer.
handleIDontWant :: GossipSubRouter -> PeerId -> [IDontWant] -> IO ()
handleIDontWant :: GossipSubRouter -> PeerId -> [IDontWant] -> IO ()
handleIDontWant GossipSubRouter
router PeerId
sender [IDontWant]
batches = Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([IDontWant] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [IDontWant]
batches) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  accepted <- 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
$ GossipSubRouter -> PeerId -> STM Bool
reserveBatch GossipSubRouter
router PeerId
sender
  when accepted $ do
    let params = GossipSubRouter -> GossipSubParams
gsParams GossipSubRouter
router
        mids =
          Int -> [ByteString] -> [ByteString]
forall a. Int -> [a] -> [a]
take
            (Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (GossipSubParams -> Int
paramMaxIDontWantLength GossipSubParams
params))
            ((IDontWant -> [ByteString]) -> [IDontWant] -> [ByteString]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap IDontWant -> [ByteString]
idontwantMessageIds [IDontWant]
batches)
        ttl = GossipSubParams -> Int
paramIDontWantMessageTTL GossipSubParams
params
    when
      (ttl > 0 && not (null mids))
      ( atomically
          ( modifyTVar'
              (gsDontSendMessageIds router)
              ( Map.insertWith
                  Map.union
                  sender
                  (Map.fromList [(messageIdDigest mid, ttl) | mid <- mids])
              )
          )
      )

reserveBatch :: GossipSubRouter -> PeerId -> STM Bool
reserveBatch :: GossipSubRouter -> PeerId -> STM Bool
reserveBatch GossipSubRouter
router PeerId
sender = do
  counts <- TVar (Map PeerId Int) -> STM (Map PeerId Int)
forall a. TVar a -> STM a
readTVar (GossipSubRouter -> TVar (Map PeerId Int)
gsIDontWantCounts GossipSubRouter
router)
  let current = Int -> PeerId -> Map PeerId Int -> Int
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault Int
0 PeerId
sender Map PeerId Int
counts
      limit = Int -> Int -> Int
forall a. Ord a => a -> a -> a
max Int
0 (GossipSubParams -> Int
paramMaxIDontWantMessages (GossipSubRouter -> GossipSubParams
gsParams GossipSubRouter
router))
  if current >= limit
    then pure False
    else do
      writeTVar (gsIDontWantCounts router) (Map.insert sender (current + 1) counts)
      pure True

-- | Test whether a peer has rejected a message ID that is still live.
peerRejectsMessage ::
  Map.Map PeerId (Map.Map ByteString Int) -> PeerId -> MessageId -> Bool
peerRejectsMessage :: Map PeerId (Map ByteString Int) -> PeerId -> ByteString -> Bool
peerRejectsMessage Map PeerId (Map ByteString Int)
unwanted PeerId
pid ByteString
mid =
  Bool
-> (Map ByteString Int -> Bool)
-> Maybe (Map ByteString Int)
-> Bool
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Bool
False (ByteString -> Map ByteString Int -> Bool
forall k a. Ord k => k -> Map k a -> Bool
Map.member (ByteString -> ByteString
messageIdDigest ByteString
mid)) (PeerId
-> Map PeerId (Map ByteString Int) -> Maybe (Map ByteString Int)
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PeerId
pid Map PeerId (Map ByteString Int)
unwanted)

-- | Remove peers that have rejected the message ID from a target set.
filterAllowedPeers ::
  Map.Map PeerId (Map.Map ByteString Int) ->
  MessageId ->
  Set.Set PeerId ->
  Set.Set PeerId
filterAllowedPeers :: Map PeerId (Map ByteString Int)
-> ByteString -> Set PeerId -> Set PeerId
filterAllowedPeers Map PeerId (Map ByteString Int)
unwanted ByteString
mid =
  (PeerId -> Bool) -> Set PeerId -> Set PeerId
forall a. (a -> Bool) -> Set a -> Set a
Set.filter (\PeerId
pid -> Bool -> Bool
not (Map PeerId (Map ByteString Int) -> PeerId -> ByteString -> Bool
peerRejectsMessage Map PeerId (Map ByteString Int)
unwanted PeerId
pid ByteString
mid))

-- | Reset the per-heartbeat receive budget and age suppression entries.
expireIDontWantState :: GossipSubRouter -> IO ()
expireIDontWantState :: GossipSubRouter -> IO ()
expireIDontWantState GossipSubRouter
router = STM () -> IO ()
forall a. STM a -> IO a
atomically (STM () -> IO ()) -> STM () -> IO ()
forall a b. (a -> b) -> a -> b
$ do
  TVar (Map PeerId Int) -> Map PeerId Int -> STM ()
forall a. TVar a -> a -> STM ()
writeTVar (GossipSubRouter -> TVar (Map PeerId Int)
gsIDontWantCounts GossipSubRouter
router) Map PeerId Int
forall k a. Map k a
Map.empty
  TVar (Map PeerId (Map ByteString Int))
-> (Map PeerId (Map ByteString Int)
    -> Map PeerId (Map ByteString Int))
-> STM ()
forall a. TVar a -> (a -> a) -> STM ()
modifyTVar' (GossipSubRouter -> TVar (Map PeerId (Map ByteString Int))
gsDontSendMessageIds GossipSubRouter
router) ((Map PeerId (Map ByteString Int)
  -> Map PeerId (Map ByteString Int))
 -> STM ())
-> (Map PeerId (Map ByteString Int)
    -> Map PeerId (Map ByteString Int))
-> STM ()
forall a b. (a -> b) -> a -> b
$ (Map ByteString Int -> Maybe (Map ByteString Int))
-> Map PeerId (Map ByteString Int)
-> Map PeerId (Map ByteString Int)
forall a b k. (a -> Maybe b) -> Map k a -> Map k b
Map.mapMaybe Map ByteString Int -> Maybe (Map ByteString Int)
forall {a} {k}. (Ord a, Num a) => Map k a -> Maybe (Map k a)
agePeer
 where
  agePeer :: Map k a -> Maybe (Map k a)
agePeer Map k a
mids =
    let live :: Map k a
live = (a -> Maybe a) -> Map k a -> Map k a
forall a b k. (a -> Maybe b) -> Map k a -> Map k b
Map.mapMaybe a -> Maybe a
forall {a}. (Ord a, Num a) => a -> Maybe a
age Map k a
mids
     in if Map k a -> Bool
forall k a. Map k a -> Bool
Map.null Map k a
live then Maybe (Map k a)
forall a. Maybe a
Nothing else Map k a -> Maybe (Map k a)
forall a. a -> Maybe a
Just Map k a
live
  age :: a -> Maybe a
age a
ttl
    | a
ttl a -> a -> Bool
forall a. Ord a => a -> a -> Bool
<= a
1 = Maybe a
forall a. Maybe a
Nothing
    | Bool
otherwise = a -> Maybe a
forall a. a -> Maybe a
Just (a
ttl a -> a -> a
forall a. Num a => a -> a -> a
- a
1)

messageIdDigest :: MessageId -> ByteString
messageIdDigest :: ByteString -> ByteString
messageIdDigest ByteString
mid =
  Digest SHA256 -> ByteString
forall bin bout.
(ByteArrayAccess bin, ByteArray bout) =>
bin -> bout
BA.convert (ByteString -> Digest SHA256
forall ba a.
(ByteArrayAccess ba, HashAlgorithm a) =>
ba -> Digest a
Hash.hash ByteString
mid :: Hash.Digest Hash.SHA256)