diff --git a/README.md b/README.md index 56ca0f74..f437aa6a 100644 --- a/README.md +++ b/README.md @@ -111,15 +111,24 @@ documentation][topology-file]. However, the fields: `bootstrapPeers` and ### Ledger Peers -To use ledger peers, as `cardano-node` does there are additional requrements: +`dmq-node` requires node-to-client V23, available since `cardano-node` 10.7, +to fetch stake data for signature validation. By default, it also fetches a +ledger peer snapshot on each stake refresh. Set `"LedgerPeers": false` in the +DMQ configuration file to skip the snapshot query. -* You need `cardano-node-10.7` or newer to support ledger peer snapshot query - over `cardano-node`'s node-to-client protocol. -* You need to configure `cardano-node` & `dmq-node` to use SRV records according to [CIP#155] -* You need to set `LedgerPeers: true` in the configuration file. +The topology field `useLedgerAfterSlot` controls when DMQ uses ledger peers. +Set it to `0` to allow them immediately, or to a positive slot number to use +snapshots from that slot onward. Set it to `-1` or omit it to disable ledger +peer selection. -Currently ledger peers are disabled by default, but in a near future we will -enable them by default. +To advertise a DMQ relay, publish a DNS SRV record at +`_dmq._mithril._cardano._tcp.`, where `` is registered as an +SRV relay for your stake pool. See [CIP#155]. + +With a positive `useLedgerAfterSlot`, DMQ currently uses the big ledger peer +snapshot even for ordinary peer requests. To bootstrap when only smaller +pools advertise DMQ relays, add a reachable DMQ relay to the `localRoots` +group in your topology. See the [example topology](./dmq-node/topology.json). ### Tracing @@ -128,14 +137,11 @@ the new tracing system for `cardano-node`). ### Configuration example -Note: it requires `cardano-node-10.7.x` for `LedgerPeers`, if you're running it -against an earlier `cardano-node` turn the option off. - The `Prometheus` requires a different port number than `cardano-node`'s `Prometheus`. ```json -{ "LedgerPeers": true, +{ "CardanoNodeSocket": "/var/run/cardano-node.socket", "TraceOptions": { "": { diff --git a/dmq-node/CHANGELOG.md b/dmq-node/CHANGELOG.md index 1c5c275c..3ce99c73 100644 --- a/dmq-node/CHANGELOG.md +++ b/dmq-node/CHANGELOG.md @@ -2,6 +2,62 @@ + +## 0.8.0.0 -- 2026-11-27 + +### Breaking + +- Signatures issued by the same pool are rate limited by their `sigExpiresAt` + rather than by the time they were received: `sigExpiresAt` of any two + signatures of a pool must be at least `minSigDelay` apart + (`DMQ.Protocol.SigSubmission.SigSpacing`). A burst of well-spaced signatures + passes the spacing check in any order if none of its signed expiries conflicts + with the receiver's history for that pool. A node can still reject a + signature whose OCert counter is below one it already accepted. + Previously a burst of signatures which accumulated in a node's mempool was + rejected with `SigTooFrequent` by its peers, which disconnected them + (issue #82). +- `NodeToNodeV_3` supports sending these bursts over `SigSubmissionV2`. + On V1 and V2 connections, the sender waits `minSigDelay` after the peer + acknowledges a signature ID before announcing another from the same pool. + Upgraded nodes apply the same signature validation rules on every connection. +- `SigTooFrequent` is checked after the cryptographic checks, and it no + longer disconnects a node-to-node peer: the pool might have sent conflicting + signatures to different nodes, which is not the peer's fault. +- `PoolValidationCtx`: removed `vctxNow`, `vctxLastSigByPoolId` was replaced + with `vctxSigSpacing`; `withPoolValidationCtx` takes only `UTCTime`. +- `NodeKernel`: `lastSigByPoolIdVar` was replaced with `sigSpacingVar`. +- `DMQ.Mempool` re-exports `getWriter` from `ouroboros-network`. + +### Non-Breaking + +- Define directional mux ingress limits for signature submission and peer sharing in DMQ's policy. + Signature replies use the larger queue on the V1 responder and the V2 initiator. +- Trace node-wide mux counters under `Net.Mux.Counters` at the diffusion default interval. +- LedgerPeers are now enabled by default. + +### Patch + +- Updated `ouroboros-consensus` to version `5.1.0.1`. + +- Updated `ouroboros-consensus` to version `5.2`, `ouroboros-network` to version `2.0` and `network-mux` to version `1.0`. + +- The first sig a node accepted was never diffused nor delivered over + `LocalMsgNotification`: `Mempool.empty` gave it index -1, the same as + `mempoolZeroIdx`. The mempool now starts at index 0. +- `LocalMsgNotification` sent messages again on the next request: the server + kept the index of the first message of a reply, not of the last. + +- `InvalidOCertCounter` no longer disconnects a node-to-node peer: whether it + fails depends on the order in which a node received signatures signed with + different operational certificates, so the peer might have accepted the + signature legitimately. The counter is now checked after the cryptographic + checks, so a forged signature is still rejected with an error which + disconnects the peer. + +- Update to `ouroboros-network-2.1.0.0`, `cardano-diffusion-1.4.0.0`, + `network-mux-1.1.0.0` and the compatible `ouroboros-consensus-5.4.0.1` revision. + ## 0.7.2.1 -- 2026-10-12 diff --git a/dmq-node/app/Main.hs b/dmq-node/app/Main.hs index 4e7cfead..4a9d7a6d 100644 --- a/dmq-node/app/Main.hs +++ b/dmq-node/app/Main.hs @@ -198,16 +198,16 @@ runDMQ commandLineConfig = do let sigSize :: Sig StandardCrypto -> SizeInBytes sigSize = fromIntegral . BSL.length . sigRawBytes - mempoolReader = Mempool.getReader sigId sigSize (mempool nodeKernel) + ntcMempoolReader = Mempool.getReader sigId sigSize (mempool nodeKernel) + ntnMempoolReader = Mempool.getIndexedReader sigId sigSize (mempool nodeKernel) dmqNtNApps = let ntnMempoolWriter = Mempool.getWriter SigDuplicate sigId - (\(utcNow, now) sigs -> + (\utcNow sigs -> withPoolValidationCtx (stakePools nodeKernel) utcNow - now (validateSig validationCfg sigs) ) (traverse_ $ \(sigid, reason) -> do @@ -218,12 +218,31 @@ runDMQ commandLineConfig = do NotInitialized -> return () PoolNotEligible -> return () UnrecognizedPool -> return () - err -> throwIO (SigValidationException sigid err) + -- the signature might conflict + -- with a signature received from + -- another peer, if the pool sent + -- conflicting signatures to + -- different nodes; this is not + -- the peer's fault. + SigTooFrequent {} -> return () + -- the peer might have received + -- the signature before one signed + -- with a newer operational + -- certificate. + InvalidOCertCounter {} -> return () + err@InvalidSigId -> throwIO (SigValidationException sigid err) + err@InvalidKESSignature {} -> throwIO (SigValidationException sigid err) + err@InvalidSignatureOCERT {} -> throwIO (SigValidationException sigid err) + err@KESBeforeStartOCERT {} -> throwIO (SigValidationException sigid err) + err@KESAfterEndOCERT {} -> throwIO (SigValidationException sigid err) + err@SigExpiresAtTooFarInTheFuture {} + -> throwIO (SigValidationException sigid err) + err@SigResultOther {} -> throwIO (SigValidationException sigid err) ) (mempool nodeKernel) in ntnApps dmqTracers dmqConfig - mempoolReader + ntnMempoolReader ntnMempoolWriter sigSize nodeKernel @@ -236,11 +255,10 @@ runDMQ commandLineConfig = do let ntcMempoolWriter = Mempool.getWriter SigDuplicate sigId - (\(utcNow, now) sigs -> + (\utcNow sigs -> withPoolValidationCtx (stakePools nodeKernel) utcNow - now (validateSig validationCfg sigs) ) (traverse_ $ \(sigid, reason) -> @@ -248,7 +266,7 @@ runDMQ commandLineConfig = do ) (mempool nodeKernel) in NtC.ntcApps dmqTracers dmqConfig - mempoolReader ntcMempoolWriter + ntcMempoolReader ntcMempoolWriter NtC.dmqCodecs dmqDiffusionArguments = diffusionArguments nullTracer diff --git a/dmq-node/changelog.d/20261012_164204_coot_ouroboros_consensus_5_1_0_1.md b/dmq-node/changelog.d/20261012_164204_coot_ouroboros_consensus_5_1_0_1.md deleted file mode 100644 index 1ab51a8d..00000000 --- a/dmq-node/changelog.d/20261012_164204_coot_ouroboros_consensus_5_1_0_1.md +++ /dev/null @@ -1,23 +0,0 @@ - - - - -### Patch - -- Updated `ouroboros-consensus` to version `5.1.0.1`. - diff --git a/dmq-node/changelog.d/20261026_123832_kolam_network_2_0_consensus_5_2.md b/dmq-node/changelog.d/20261026_123832_kolam_network_2_0_consensus_5_2.md deleted file mode 100644 index 273f0b68..00000000 --- a/dmq-node/changelog.d/20261026_123832_kolam_network_2_0_consensus_5_2.md +++ /dev/null @@ -1,22 +0,0 @@ - - - - -### Patch - -- Updated `ouroboros-consensus` to version `5.2`, `ouroboros-network` to version `2.0` and `network-mux` to version `1.0`. diff --git a/dmq-node/changelog.d/20261112_200000_michael_first_sig_and_notification_index.md b/dmq-node/changelog.d/20261112_200000_michael_first_sig_and_notification_index.md deleted file mode 100644 index c0bb820d..00000000 --- a/dmq-node/changelog.d/20261112_200000_michael_first_sig_and_notification_index.md +++ /dev/null @@ -1,26 +0,0 @@ - - - - -### Patch - -- The first sig a node accepted was never diffused nor delivered over - `LocalMsgNotification`: `Mempool.empty` gave it index -1, the same as - `mempoolZeroIdx`. The mempool now starts at index 0. -- `LocalMsgNotification` sent messages again on the next request: the server - kept the index of the first message of a reply, not of the last. diff --git a/dmq-node/changelog.d/20261124_171500_network_2_1.md b/dmq-node/changelog.d/20261124_171500_network_2_1.md deleted file mode 100644 index 4f05fd0c..00000000 --- a/dmq-node/changelog.d/20261124_171500_network_2_1.md +++ /dev/null @@ -1,10 +0,0 @@ -### Non-Breaking - -- Define directional mux ingress limits for signature submission and peer sharing in DMQ's policy. - Signature replies use the larger queue on the V1 responder and the V2 initiator. -- Trace node-wide mux counters under `Net.Mux.Counters` at the diffusion default interval. - -### Patch - -- Update to `ouroboros-network-2.1.0.0`, `cardano-diffusion-1.4.0.0`, - `network-mux-1.1.0.0` and the compatible `ouroboros-consensus-5.4.0.1` revision. diff --git a/dmq-node/dmq-node.cabal b/dmq-node/dmq-node.cabal index 466748c3..bf5f38ec 100644 --- a/dmq-node/dmq-node.cabal +++ b/dmq-node/dmq-node.cabal @@ -1,6 +1,6 @@ cabal-version: 3.4 name: dmq-node -version: 0.7.2.2 +version: 0.8.0.0 synopsis: Decentralised Message Queue Node description: Decentralised Message Queue Node based on Cardano Diffusion @@ -76,6 +76,7 @@ library DMQ.NodeToClient.LocalStateQueryClient.Types DMQ.NodeToClient.Version DMQ.NodeToNode + DMQ.NodeToNode.SigSubmission DMQ.NodeToNode.Version DMQ.Policy DMQ.Protocol.LocalMsgNotification.Client @@ -87,6 +88,7 @@ library DMQ.Protocol.LocalMsgSubmission.Server DMQ.Protocol.LocalMsgSubmission.Type DMQ.Protocol.SigSubmission.Codec + DMQ.Protocol.SigSubmission.SigSpacing DMQ.Protocol.SigSubmission.Type DMQ.Protocol.SigSubmission.Validate DMQ.Protocol.SigSubmissionV2.Codec @@ -200,8 +202,10 @@ test-suite dmq-tests DMQ.Protocol.SigSubmissionV2.Test Test.DMQ.NodeToClient Test.DMQ.NodeToNode + Test.DMQ.NodeToNode.SigSubmission Test.DMQ.PeerSelection.PeerMetric Test.DMQ.SigSubmission.App + Test.DMQ.SigSubmission.SigSpacing Test.DMQ.SigSubmission.Types type: exitcode-stdio-1.0 @@ -209,6 +213,7 @@ test-suite dmq-tests main-is: Main.hs build-depends: QuickCheck, + aeson, base >=4.14 && <4.23, bytestring, cardano-binary, @@ -227,6 +232,7 @@ test-suite dmq-tests psqueues, quickcheck-instances, serialise, + singletons, tasty, tasty-quickcheck, time, diff --git a/dmq-node/src/DMQ/Configuration.hs b/dmq-node/src/DMQ/Configuration.hs index 9cb24ded..f3fbe919 100644 --- a/dmq-node/src/DMQ/Configuration.hs +++ b/dmq-node/src/DMQ/Configuration.hs @@ -137,7 +137,8 @@ data Configuration' f = dmqcTargetOfEstablishedBigLedgerPeers :: f Int, dmqcTargetOfActiveBigLedgerPeers :: f Int, - -- | Minimal delay between signatures from the same peer. + -- | Minimal distance between `sigExpiresAt` of two signatures issued by + -- the same pool, see `DMQ.Protocol.SigSubmission.SigSpacing`. -- dmqcMinSigDelay :: f DiffTime, @@ -221,7 +222,7 @@ defaultConfiguration = Configuration { dmqcProtocolIdleTimeout = I defaultProtocolIdleTimeout, dmqcChurnInterval = I defaultDeadlineChurnInterval, dmqcPeerSharing = I PeerSharingEnabled, - dmqcLedgerPeers = I False, + dmqcLedgerPeers = I True, dmqcMinSigDelay = I Policy.minSigDelay, diff --git a/dmq-node/src/DMQ/Diffusion/NodeKernel.hs b/dmq-node/src/DMQ/Diffusion/NodeKernel.hs index c5efcc2c..cb209dc0 100644 --- a/dmq-node/src/DMQ/Diffusion/NodeKernel.hs +++ b/dmq-node/src/DMQ/Diffusion/NodeKernel.hs @@ -21,7 +21,6 @@ import "contra-tracer" Control.Tracer (nullTracer) import Data.Function (on) import Data.Map.Strict qualified as Map -import Data.OrdPSQ qualified as OrdPSQ import Data.Proxy import Data.Sequence (Seq) import Data.Sequence qualified as Seq @@ -69,6 +68,7 @@ import DMQ.Mempool (Mempool (..), MempoolSeq (..), WithIndex (..)) import DMQ.Mempool qualified as Mempool import DMQ.NodeToClient.LocalStateQueryClient import DMQ.Policy qualified as Policy +import DMQ.Protocol.SigSubmission.SigSpacing qualified as SigSpacing import DMQ.Protocol.SigSubmission.Type (Sig (sigExpiresAt, sigId), SigId) import DMQ.Tracer @@ -98,27 +98,27 @@ newNodeKernel rng ShelleyGenesis {sgMaxKESEvolutions} = do stakePoolsVar, ledgerBigPeersVar, ledgerPeersVar, - lastSigByPoolIdVar) + sigSpacingVar) <- atomically $ (,,,,,) <$> newTVar NotReady <*> newTVar Map.empty <*> newTVar Map.empty <*> newTVar Nothing <*> newEmptyTMVar - <*> newTVar OrdPSQ.empty + <*> newTVar SigSpacing.empty let withPoolValidationCtx - :: forall a. UTCTime -> Time -> (PoolValidationCtx -> (a, PoolValidationCtx)) -> STM m a - withPoolValidationCtx utcNow now f = do - ctx <- PoolValidationCtx utcNow now + :: forall a. UTCTime -> (PoolValidationCtx -> (a, PoolValidationCtx)) -> STM m a + withPoolValidationCtx utcNow f = do + ctx <- PoolValidationCtx utcNow <$> readTVar readinessVar <*> readTVar stakePoolsVar <*> readTVar ocertCountersVar <*> pure sgMaxKESEvolutions - <*> readTVar lastSigByPoolIdVar - let (a, PoolValidationCtx {vctxOcertMap, vctxLastSigByPoolId}) = f ctx + <*> readTVar sigSpacingVar + let (a, PoolValidationCtx {vctxOcertMap, vctxSigSpacing}) = f ctx writeTVar ocertCountersVar vctxOcertMap - writeTVar lastSigByPoolIdVar vctxLastSigByPoolId + writeTVar sigSpacingVar vctxSigSpacing return a stakePools = StakePools { @@ -148,7 +148,7 @@ newNodeKernel rng ShelleyGenesis {sgMaxKESEvolutions} = do , readinessVar , stakePools , peerMetric - , lastSigByPoolIdVar + , sigSpacingVar } diff --git a/dmq-node/src/DMQ/Diffusion/NodeKernel/Types.hs b/dmq-node/src/DMQ/Diffusion/NodeKernel/Types.hs index 72af4fc9..4452772d 100644 --- a/dmq-node/src/DMQ/Diffusion/NodeKernel/Types.hs +++ b/dmq-node/src/DMQ/Diffusion/NodeKernel/Types.hs @@ -16,7 +16,6 @@ import Control.Monad.Class.MonadTime.SI import Data.Aeson qualified as Aeson import Data.Map.Strict (Map) -import Data.OrdPSQ (OrdPSQ) import Data.Word import System.Random (StdGen) @@ -31,6 +30,7 @@ import Ouroboros.Network.TxSubmission.Inbound.V2 import DMQ.Diffusion.PeerSelection.PeerMetric (PeerMetric) import DMQ.Mempool (Mempool (..)) +import DMQ.Protocol.SigSubmission.SigSpacing (SigSpacing) import DMQ.Protocol.SigSubmission.Type (PoolId, Sig, SigId) @@ -58,7 +58,10 @@ data NodeKernel crypto ntnAddr m = , stakePools :: !(StakePools m) , readinessVar :: !(StrictTVar m Readiness) , peerMetric :: !(PeerMetric m SigId ntnAddr) - , lastSigByPoolIdVar :: !(StrictTVar m (OrdPSQ PoolId Time ())) + + -- | `sigExpiresAt` of recently accepted signatures, see + -- `DMQ.Protocol.SigSubmission.SigSpacing`. + , sigSpacingVar :: !(StrictTVar m (SigSpacing PoolId)) } data StakePools m = StakePools { @@ -76,7 +79,7 @@ data StakePools m = StakePools { -- First argument is the current time inserted into `PoolValidationCtx`, -- other fields are read from share state available in `STM` action. , withPoolValidationCtx - :: forall a. UTCTime -> Time -> (PoolValidationCtx -> (a, PoolValidationCtx)) -> STM m a + :: forall a. UTCTime -> (PoolValidationCtx -> (a, PoolValidationCtx)) -> STM m a -- | provides only those big peers which provide SRV endpoints -- as otherwise those are cardano-nodes @@ -90,29 +93,28 @@ data StakePools m = StakePools { data PoolValidationCtx = PoolValidationCtx { - vctxUTCNow :: !UTCTime + vctxUTCNow :: !UTCTime -- ^ current UTC time - , vctxNow :: !Time - -- ^ current time - , vctxReadiness :: !Readiness + , vctxReadiness :: !Readiness -- ^ if pool validation ctx was initialised by local state query -- mini-prototocol - , vctxStakeMap :: !(Map PoolId LedgerQuery.StakeSnapshot) + , vctxStakeMap :: !(Map PoolId LedgerQuery.StakeSnapshot) -- ^ for signature validation - , vctxOcertMap :: !(Map PoolId Word64) + , vctxOcertMap :: !(Map PoolId Word64) -- ^ ocert counters to check monotonicity - , vctxPraosMaxKESEvo :: !Word64 + , vctxPraosMaxKESEvo :: !Word64 -- ^ maximum number of KES iterations (read from the Shelley genesis file) - , vctxLastSigByPoolId :: !(OrdPSQ PoolId Time ()) - -- ^ last valid signature by PoolId, to limit frequency of submitted - -- signatures + , vctxSigSpacing :: !(SigSpacing PoolId) + -- ^ `sigExpiresAt` of recently accepted signatures, to limit how often + -- a pool can issue signatures } deriving Show newtype ValidationCfg = ValidationCfg { vcMinSigDelay :: DiffTime - -- ^ minimal delay between signatures created by the same SPO. It can be + -- ^ minimal distance between `sigExpiresAt` of two signatures issued by + -- the same pool, see `DMQ.Protocol.SigSubmission.SigSpacing`. It can be -- modified with an internal CLI option. The default value is -- `DMQ.Policy.minSigDelay`. } diff --git a/dmq-node/src/DMQ/Mempool.hs b/dmq-node/src/DMQ/Mempool.hs index 234e1f58..98b36432 100644 --- a/dmq-node/src/DMQ/Mempool.hs +++ b/dmq-node/src/DMQ/Mempool.hs @@ -1,13 +1,16 @@ module DMQ.Mempool ( module Mempool , empty - , getWriter + , getIndexedReader ) where import Control.Concurrent.Class.MonadSTM.Strict -import Control.Monad.Class.MonadTime.SI -import Ouroboros.Network.TxSubmission.Mempool.Simple as Mempool hiding (empty, - getWriter) +import Data.Foldable (toList) +import Data.Map.Strict qualified as Map + +import Ouroboros.Network.SizeInBytes (SizeInBytes) +import Ouroboros.Network.TxSubmission.Mempool.Reader (MempoolSnapshot (..)) +import Ouroboros.Network.TxSubmission.Mempool.Simple as Mempool hiding (empty) -- | An empty mempool. -- @@ -17,24 +20,21 @@ import Ouroboros.Network.TxSubmission.Mempool.Simple as Mempool hiding (empty, empty :: (MonadSTM m, Ord txid) => (tx -> txid) -> m (Mempool m txid tx) empty getTxId = new getTxId [] -getWriter - :: forall tx txid failure m. - ( MonadSTM m - , MonadTime m - , MonadMonotonicTime m - , Ord txid - ) - => failure - -- ^ duplicate tx error - -> (tx -> txid) - -- ^ get transaction hash - -> ((UTCTime, Time) -> [tx] -> STM m [Either (txid, failure) tx]) - -- ^ validate a tx in an `STM` transaction, this allows acquiring and - -- updating validation context. - -> ([(txid, failure)] -> m ()) - -- ^ handle invalid txs, e.g. logging, throwing exceptions, etc - -> Mempool m txid tx - -- ^ mempool - -> TxSubmissionMempoolWriter txid tx Integer m failure -getWriter = getWriterWithCtx (\_ -> (,) <$> getCurrentTime <*> getMonotonicTime) +-- | Legacy outbound peers look up the issuing pool of each candidate. Share +-- one index across those lookups in a snapshot. ID-only queries stay lazy. +getIndexedReader :: (MonadSTM m, Ord sigId) + => (sig -> sigId) + -> (sig -> SizeInBytes) + -> Mempool m sigId sig + -> TxSubmissionMempoolReader sigId sig Integer m +getIndexedReader idOf sizeOf mempool@(Mempool contents) = + reader { mempoolGetSnapshot = do + snapshot <- mempoolGetSnapshot reader + MempoolSeq {mempoolSeq} <- readTVar contents + let byIndex = Map.fromDistinctAscList + [ (idx, sig) | WithIndex idx sig <- toList mempoolSeq ] + pure snapshot { mempoolLookupTx = (`Map.lookup` byIndex) } + } + where + reader = getReader idOf sizeOf mempool diff --git a/dmq-node/src/DMQ/NodeToNode.hs b/dmq-node/src/DMQ/NodeToNode.hs index cfe12db1..959eb942 100644 --- a/dmq-node/src/DMQ/NodeToNode.hs +++ b/dmq-node/src/DMQ/NodeToNode.hs @@ -5,6 +5,7 @@ {-# LANGUAGE PackageImports #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeApplications #-} module DMQ.NodeToNode ( RemoteAddress @@ -51,11 +52,15 @@ import Network.Mux.Types (Mode (..)) import Network.Mux.Types qualified as Mx import Network.TypedProtocol.Codec (AnnotatedCodec, Codec) +import Cardano.Crypto.DSIGN.Class (DSIGNAlgorithm (hashVerKeyDSIGN)) import Cardano.KESAgent.KES.Crypto (Crypto (..)) +import Cardano.Ledger.Hashes (ADDRHASH) -import DMQ.Configuration (Configuration) +import DMQ.Configuration (Configuration, Configuration' (dmqcMinSigDelay), + I (..)) import DMQ.Diffusion.NodeKernel.Types (NodeKernel (..)) import DMQ.Diffusion.PeerSelection.PeerMetric qualified as PeerMetric +import DMQ.NodeToNode.SigSubmission qualified as SigSubmission import DMQ.NodeToNode.Version import DMQ.Policy qualified as Policy import DMQ.Protocol.SigSubmission.Codec (byteLimitsSigSubmission, @@ -65,10 +70,8 @@ import DMQ.Protocol.SigSubmission.Type (NumTxIdsToAck (..), NumTxIdsToReq (..), import DMQ.Protocol.SigSubmissionV2.Codec import DMQ.Protocol.SigSubmissionV2.Inbound (sigSubmissionV2InboundPeerPipelined) -import DMQ.Protocol.SigSubmissionV2.Outbound (sigSubmissionV2OutboundPeer) import DMQ.Protocol.SigSubmissionV2.Type import DMQ.SigSubmissionV2.Inbound (sigSubmissionInbound) -import DMQ.SigSubmissionV2.Outbound (sigSubmissionOutbound) import DMQ.Tracer import Ouroboros.Network.BlockFetch.ClientRegistry (bracketKeepAliveClient) @@ -112,10 +115,8 @@ import Ouroboros.Network.Protocol.PeerSharing.Codec (byteLimitsPeerSharing, codecPeerSharing, timeLimitsPeerSharing) import Ouroboros.Network.Protocol.PeerSharing.Server (peerSharingServerPeer) import Ouroboros.Network.Protocol.PeerSharing.Type qualified as Protocol -import Ouroboros.Network.Protocol.TxSubmission2.Client (txSubmissionClientPeer) import Ouroboros.Network.Protocol.TxSubmission2.Server (txSubmissionServerPeerPipelined) -import Ouroboros.Network.TxSubmission.Outbound (txSubmissionOutbound) -- TODO: if we add `versionNumber` to `ctx` we could use `RunMiniProtocolCb`. @@ -162,6 +163,7 @@ data Apps addr m a b = ntnApps :: forall crypto m ntnAddr ntcAddr idx. ( Typeable crypto + , DSIGNAlgorithm (DSIGN crypto) , Alternative (STM m) , MonadAsync m , MonadDelay m @@ -196,7 +198,7 @@ ntnApps , keepAliveProtocolTracer , peerSharingProtocolTracer } - _ + config mempoolReader mempoolWriter sigSize @@ -238,6 +240,9 @@ ntnApps , aPeerSharingServer } where + I minSigDelay = dmqcMinSigDelay config + poolKey = hashVerKeyDSIGN @(DSIGN crypto) @ADDRHASH . getSigColdKey . sigColdKey + aSigSubmissionV2Client :: NodeToNodeVersion -> ExpandedInitiatorContext ntnAddr NoExtraFlags m @@ -287,7 +292,7 @@ ntnApps -> ExpandedInitiatorContext ntnAddr NoExtraFlags m -> Channel m BL.ByteString -> m ((), Maybe BL.ByteString) - aSigSubmissionV1Client version + aSigSubmissionV1Client _version ExpandedInitiatorContext { eicConnectionId = connId, eicControlMessage = controlMessage @@ -298,12 +303,10 @@ ntnApps sigSubmissionSizeLimitsV1 sigSubmissionTimeLimitsV1 channel - $ txSubmissionClientPeer - $ txSubmissionOutbound + $ SigSubmission.outboundV1 minSigDelay poolKey (Mx.WithBearer connId >$< sigSubmissionOutboundV1Tracer) (NumTxIdsToAck . getNumTxIdsToReq $ maxUnacknowledgedTxIds) mempoolReader - version controlMessage @@ -319,12 +322,10 @@ ntnApps sigSubmissionSizeLimitsV2 sigSubmissionTimeLimitsV2 channel - $ sigSubmissionV2OutboundPeer - $ sigSubmissionOutbound + $ SigSubmission.outboundV2 version minSigDelay poolKey (Mx.WithBearer connId >$< sigSubmissionOutboundV2Tracer) (NumIdsAck . getNumTxIdsToReq $ maxUnacknowledgedTxIds) mempoolReader - version aSigSubmissionV1Server :: NodeToNodeVersion @@ -554,7 +555,8 @@ initiatorProtocols limitsAndTimeouts InitiatorProtocolOnly (MiniProtocolCb (case version of NodeToNodeV_1 -> aSigSubmissionV1Client version - NodeToNodeV_2 -> aSigSubmissionV2Client version)) + NodeToNodeV_2 -> aSigSubmissionV2Client version + NodeToNodeV_3 -> aSigSubmissionV2Client version)) , keepAliveProtocol = InitiatorProtocolOnly (MiniProtocolCb (aKeepAliveClient version)) , peerSharingProtocol = @@ -563,7 +565,8 @@ initiatorProtocols limitsAndTimeouts version initiatorAndResponderProtocols - :: LimitsAndTimeouts crypto addr + :: forall crypto addr m a b. + LimitsAndTimeouts crypto addr -> Apps addr m a b -> NodeToNodeVersion -> NodeToNodeVersionData @@ -585,14 +588,9 @@ initiatorAndResponderProtocols limitsAndTimeouts (Protocols { sigSubmissionProtocol = case version of - NodeToNodeV_1 -> - InitiatorAndResponderProtocol - (MiniProtocolCb (aSigSubmissionV1Client version)) - (MiniProtocolCb (aSigSubmissionV1Server version)) - NodeToNodeV_2 -> - InitiatorAndResponderProtocol - (MiniProtocolCb (aSigSubmissionV2Client version)) - (MiniProtocolCb (aSigSubmissionV2Server version)) + NodeToNodeV_1 -> sigSubmissionV1 + NodeToNodeV_2 -> sigSubmissionV2 + NodeToNodeV_3 -> sigSubmissionV2 , keepAliveProtocol = InitiatorAndResponderProtocol (MiniProtocolCb (aKeepAliveClient version)) @@ -603,6 +601,25 @@ initiatorAndResponderProtocols limitsAndTimeouts (MiniProtocolCb (aPeerSharingServer version)) }) version + where + sigSubmissionV1, + sigSubmissionV2 + :: RunMiniProtocol + InitiatorResponderMode + (ExpandedInitiatorContext addr NoExtraFlags m) + (ResponderContext addr) + BL.ByteString m a b + + sigSubmissionV1 = + InitiatorAndResponderProtocol + (MiniProtocolCb (aSigSubmissionV1Client version)) + (MiniProtocolCb (aSigSubmissionV1Server version)) + + sigSubmissionV2 = + InitiatorAndResponderProtocol + (MiniProtocolCb (aSigSubmissionV2Client version)) + (MiniProtocolCb (aSigSubmissionV2Server version)) + data Codecs crypto addr m = Codecs { diff --git a/dmq-node/src/DMQ/NodeToNode/SigSubmission.hs b/dmq-node/src/DMQ/NodeToNode/SigSubmission.hs new file mode 100644 index 00000000..87409c62 --- /dev/null +++ b/dmq-node/src/DMQ/NodeToNode/SigSubmission.hs @@ -0,0 +1,263 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE PackageImports #-} + +module DMQ.NodeToNode.SigSubmission + ( outboundV1 + , outboundV2 + ) where + +import Control.Concurrent.Class.MonadSTM qualified as STM +import Control.Monad (when) +import Control.Monad.Class.MonadThrow (MonadThrow) +import Control.Monad.Class.MonadTimer.SI +import "contra-tracer" Control.Tracer (Tracer) +import Data.Map.Strict (Map) +import Data.Map.Strict qualified as Map +import Data.Sequence qualified as Seq +import Network.TypedProtocol.Core (IsPipelined (NonPipelined), + PeerRole (AsClient, AsServer)) +import Network.TypedProtocol.Peer (Peer) + +import DMQ.NodeToNode.Version (NodeToNodeVersion (..)) +import DMQ.Protocol.SigSubmissionV2.Outbound +import DMQ.Protocol.SigSubmissionV2.Type qualified as V2 +import DMQ.SigSubmissionV2.Outbound (TraceSigSubmissionOutbound, + sigSubmissionOutbound) + +import Ouroboros.Network.ControlMessage (ControlMessageSTM) +import Ouroboros.Network.Protocol.TxSubmission2.Client qualified as V1 +import Ouroboros.Network.Protocol.TxSubmission2.Type qualified as V1 +import Ouroboros.Network.SizeInBytes (SizeInBytes) +import Ouroboros.Network.TxSubmission.Mempool.Reader +import Ouroboros.Network.TxSubmission.Outbound (TraceTxSubmissionOutbound, + txSubmissionOutbound) + +outboundV1 + :: forall m idx sigId sig pool. + (MonadTimer m, MonadThrow m, Ord idx, Ord sigId, Show sigId, Ord pool) + => DiffTime -> (sig -> pool) + -> Tracer m (TraceTxSubmissionOutbound sigId sig) -> V1.NumTxIdsToAck + -> TxSubmissionMempoolReader sigId sig idx m -> ControlMessageSTM m + -> Peer (V1.TxSubmission2 sigId sig) AsClient NonPipelined V1.StInit m () +outboundV1 delay poolOf tracer maxUnacked reader controlMessage = + V1.txSubmissionClientPeer $ + if delay <= 0 + then client reader + else V1.TxSubmissionClient $ do + (paced, acknowledge) <- newPacedReader delay poolOf reader + V1.runTxSubmissionClient (paceLegacyClient acknowledge (client paced)) + where + client :: Ord i => TxSubmissionMempoolReader sigId sig i m + -> V1.TxSubmissionClient sigId sig m () + client r = txSubmissionOutbound tracer maxUnacked r NodeToNodeV_1 controlMessage + +-- | V2 and V3 share the SigSubmissionV2 wire protocol. Only V3 peers can +-- receive bursts. Both inbound protocols use the same validating writer. +outboundV2 + :: forall m idx sigId sig pool. + (MonadTimer m, MonadThrow m, Ord idx, Ord sigId, Show sigId, Ord pool) + => NodeToNodeVersion -> DiffTime -> (sig -> pool) + -> Tracer m (TraceSigSubmissionOutbound sigId sig) -> V2.NumIdsAck + -> TxSubmissionMempoolReader sigId sig idx m + -> Peer (V2.SigSubmissionV2 sigId sig) AsServer NonPipelined V2.StIdle m () +outboundV2 version delay poolOf tracer maxUnacked reader = + sigSubmissionV2OutboundPeer $ + case version of + NodeToNodeV_1 -> pacedOutbound + NodeToNodeV_2 -> pacedOutbound + NodeToNodeV_3 -> outbound reader + where + pacedOutbound :: SigSubmissionOutbound sigId sig m () + pacedOutbound + | delay <= 0 = outbound reader + | otherwise = SigSubmissionOutbound $ do + (pacedReader, acknowledge) <- newPacedReader delay poolOf reader + let acknowledgeSigIds = acknowledge . V1.NumTxIdsToAck . V2.getNumIdsAck + runSigSubmissionOutbound (paceLegacyOutbound acknowledgeSigIds (outbound pacedReader)) + + outbound :: Ord i + => TxSubmissionMempoolReader sigId sig i m + -> SigSubmissionOutbound sigId sig m () + outbound r = sigSubmissionOutbound tracer maxUnacked r version + +-- | Notify the paced reader before answering each ID request. +paceLegacyOutbound :: Monad m + => (V2.NumIdsAck -> m ()) + -> SigSubmissionOutbound sigId sig m a + -> SigSubmissionOutbound sigId sig m a +paceLegacyOutbound acknowledge (SigSubmissionOutbound start) = + SigSubmissionOutbound (pace <$> start) + where + pace idle = idle { + recvMsgRequestSigIds = \blocking ack req -> do + acknowledge ack + recvMsgRequestSigIds idle blocking ack req >>= \case + SendMsgReplySigIds ids next -> pure (SendMsgReplySigIds ids (pace next)) + SendMsgReplyNoSigIds next -> pure (SendMsgReplyNoSigIds (pace next)) + , recvMsgRequestSigs = \ids -> do + SendMsgReplySigs sigs next <- recvMsgRequestSigs idle ids + pure (SendMsgReplySigs sigs (pace next)) + } + +-- | V1 carries the acknowledgement on the TxSubmission client. +paceLegacyClient :: Monad m + => (V1.NumTxIdsToAck -> m ()) + -> V1.TxSubmissionClient sigId sig m a + -> V1.TxSubmissionClient sigId sig m a +paceLegacyClient acknowledge (V1.TxSubmissionClient start) = + V1.TxSubmissionClient (pace <$> start) + where + pace idle = V1.ClientStIdle { + V1.recvMsgRequestTxIds = \blocking ack req -> do + acknowledge ack + V1.recvMsgRequestTxIds idle blocking ack req >>= \case + V1.SendMsgReplyTxIds ids next -> pure (V1.SendMsgReplyTxIds ids (pace next)) + done@V1.SendMsgDone{} -> pure done + , V1.recvMsgRequestTxs = \ids -> do + V1.SendMsgReplyTxs sigs next <- V1.recvMsgRequestTxs idle ids + pure (V1.SendMsgReplyTxs sigs (pace next)) + } + +-- | Position in a connection's announcement order. Zero precedes the first +-- announcement. +newtype AnnouncementId = AnnouncementId Integer + deriving (Eq, Ord) + +advanceAnnouncementId + :: AnnouncementId + -> V1.NumTxIdsToAck + -> AnnouncementId +advanceAnnouncementId (AnnouncementId current) count = + AnnouncementId (current + toInteger count) + +-- | The submission protocols advance a cursor only for IDs actually announced. +-- The first field orders announcements even when a deferred signature has a +-- smaller mempool index than one already sent for another pool. +data Cursor idx sigId pool = Cursor + !AnnouncementId -- announcement number + !idx -- index for looking up the body + !idx -- highest mempool index visited + !(Map idx (sigId, SizeInBytes)) -- deferred entries, in insertion order + !(Map pool AnnouncementId) -- last announcement still holding each pool back + deriving (Eq, Ord) + +-- | A peer may collect or request bodies long after it learns their IDs. Start +-- the delay at its FIFO acknowledgement, so the peer has finished processing +-- the previous ID before the next one for that pool becomes available. +newPacedReader + :: forall m sigId sig idx pool. + (MonadTimer m, Ord idx, Ord pool) + => DiffTime + -> (sig -> pool) + -> TxSubmissionMempoolReader sigId sig idx m + -> m ( TxSubmissionMempoolReader sigId sig (Cursor idx sigId pool) m + , V1.NumTxIdsToAck -> m () + ) +newPacedReader delay poolOf reader = do + -- A whole acknowledgement batch shares one timer. A blocking ID request + -- wakes when the oldest timer fires independently of mempool changes. + acks <- STM.newTVarIO (AnnouncementId 0, Seq.empty) + let acknowledge :: V1.NumTxIdsToAck -> m () + acknowledge n = when (n > 0) $ do + !timer <- registerDelay delay + STM.atomically $ STM.modifyTVar' acks $ \(ready, waiting) -> + let !waiting' = waiting Seq.|> (n, timer) in + (ready, waiting') + + -- The running total spans every acknowledgement batch on the connection. + advance :: AnnouncementId + -- ^ Last announcement whose acknowledgement delay has elapsed. + -- Return this position at the first pending timer. + -> Seq.Seq (V1.NumTxIdsToAck, STM.TVar m Bool) + -> STM.STM m (AnnouncementId, Seq.Seq (V1.NumTxIdsToAck, STM.TVar m Bool)) + advance !ready waiting = case Seq.viewl waiting of + Seq.EmptyL -> pure (ready, waiting) + (n, timer) Seq.:< rest -> do + elapsed <- STM.readTVar timer + if elapsed + then -- client acknowledged `n` sigids, we can advance the + -- `AnnoucmentId` + advance (advanceAnnouncementId ready n) rest + else pure (ready, waiting) + + paced = TxSubmissionMempoolReader { + mempoolGetSnapshot = do + (ready, waiting) <- STM.readTVar acks + (ready', waiting') <- advance ready waiting + when (ready /= ready') $ STM.writeTVar acks (ready', waiting') + pacedSnapshot poolOf ready' <$> mempoolGetSnapshot reader + , mempoolZeroIdx = Cursor (AnnouncementId 0) zero zero Map.empty Map.empty + } + pure (paced, acknowledge) + where + zero = mempoolZeroIdx reader + +-- | Reconsider deferred entries before fresh ones, so each pool retains its +-- mempool order while other pools can pass it. The submission protocol keeps +-- the cursor of the last ID that fits in the reply. +pacedSnapshot + :: forall pool sigId sig idx. + (Ord idx, Ord pool) + => (sig -> pool) + -- ^ @poolOf@ identifies the pool that issued a signature. + -> AnnouncementId + -- ^ An ID counts towards @ready@ once a full pacing delay has elapsed + -- since the peer acknowledged it on this connection. All `AnnouncementId`s + -- smaller or equal to it can be released. + -> MempoolSnapshot sigId sig idx + -- ^ @mempoolSnapshot@ lists IDs in mempool order and looks up signature + -- bodies by their original mempool index. + -> MempoolSnapshot sigId sig (Cursor idx sigId pool) + -- ^ Each eligible ID has a cursor for looking up its body and resuming + -- the scan. +pacedSnapshot poolOf ready mempoolSnapshot = + mempoolSnapshot + { mempoolTxIdsAfter = \(Cursor annId _ high deferred held) -> + let fresh = [ (idx, (sigid, size)) + | (sigid, idx, size) <- mempoolTxIdsAfter mempoolSnapshot high ] + in offers annId high deferred + -- release all held entries with announcement ID smaller or + -- equal to `ready`. They were already acknowledged by the + -- peer and the pacing delay has elapsed. + (Map.filter (> ready) held) + (Map.toAscList deferred ++ fresh) + , mempoolLookupTx = \(Cursor _ idx _ _ _) -> mempoolLookupTx mempoolSnapshot idx + } + where + offers :: AnnouncementId + -- ^ @annId@ is the announcement ID of the current `Cursor`. Each + -- new offer advances it by one. + -> idx + -- ^ @high@ is the greatest mempool index examined so far, including + -- deferred entries. A fresh scan reads new entries after this index. + -> Map idx (sigId, SizeInBytes) + -- ^ @deferred@ keeps IDs and sizes skipped while their pools were + -- held, keyed by mempool index so they can be retried in order. + -> Map pool AnnouncementId + -- ^ @held@ records the last announcement number for each held pool. + -- Its next ID is eligible once @ready@ reaches that number. + -> [(idx, (sigId, SizeInBytes))] + -- ^ Candidates still to examine. Deferred entries in ascending index + -- order come before fresh entries from the snapshot. + -> [(sigId, Cursor idx sigId pool, SizeInBytes)] + offers _ _ _ _ [] = [] + offers annId !high !deferred held ((idx, entry@(!sigid, !size)) : rest) = + case poolOf <$> mempoolLookupTx mempoolSnapshot idx of + Nothing -> continue annId (Map.delete idx deferred) held + Just pool + | pool `Map.member` held -> + continue annId (Map.insert idx entry deferred) held + | otherwise -> + -- the `sigId` can be released; advance the announcement ID, + -- updated `deferred` and `held` maps + let annId' = advanceAnnouncementId annId 1 + deferred' = Map.delete idx deferred + -- update `held` with advanced `annId'`, it will be held + -- until the `ready :: AnnouncementId` advances. + held' = Map.insert pool annId' held + in (sigid, Cursor annId' idx high' deferred' held', size) + : continue annId' deferred' held' + where + high' = max high idx + continue nextAnnId nextDeferred nextHeld = + offers nextAnnId high' nextDeferred nextHeld rest diff --git a/dmq-node/src/DMQ/NodeToNode/Version.hs b/dmq-node/src/DMQ/NodeToNode/Version.hs index 78151f09..41f7cbdc 100644 --- a/dmq-node/src/DMQ/NodeToNode/Version.hs +++ b/dmq-node/src/DMQ/NodeToNode/Version.hs @@ -41,6 +41,8 @@ import Ouroboros.Network.OrphanInstances () data NodeToNodeVersion = NodeToNodeV_1 | NodeToNodeV_2 + | NodeToNodeV_3 + -- ^ SigSubmissionV2 with support for bursts of signatures from a pool. deriving (Eq, Ord, Enum, Bounded, Show, Generic, NFData) instance PrettyShow NodeToNodeVersion where @@ -48,6 +50,7 @@ instance PrettyShow NodeToNodeVersion where instance Aeson.ToJSON NodeToNodeVersion where toJSON NodeToNodeV_1 = Aeson.toJSON (1 :: Int) toJSON NodeToNodeV_2 = Aeson.toJSON (2 :: Int) + toJSON NodeToNodeV_3 = Aeson.toJSON (3 :: Int) instance Aeson.ToJSONKey NodeToNodeVersion where nodeToNodeVersionCodec :: CodecCBORTerm (Text, Maybe Int) NodeToNodeVersion @@ -55,9 +58,11 @@ nodeToNodeVersionCodec = CodecCBORTerm { encodeTerm, decodeTerm } where encodeTerm NodeToNodeV_1 = CBOR.TInt 1 encodeTerm NodeToNodeV_2 = CBOR.TInt 2 + encodeTerm NodeToNodeV_3 = CBOR.TInt 3 decodeTerm (CBOR.TInt 1) = Right NodeToNodeV_1 decodeTerm (CBOR.TInt 2) = Right NodeToNodeV_2 + decodeTerm (CBOR.TInt 3) = Right NodeToNodeV_3 decodeTerm (CBOR.TInt n) = Left ( T.pack "decode NodeToNodeVersion: unknown tag: " <> T.pack (show n) , Just n @@ -128,6 +133,7 @@ nodeToNodeCodecCBORTerm = \case NodeToNodeV_1 -> v1 NodeToNodeV_2 -> v1 + NodeToNodeV_3 -> v1 where v1 = CodecCBORTerm { encodeTerm = encodeTerm1, decodeTerm = decodeTerm1 } diff --git a/dmq-node/src/DMQ/Policy.hs b/dmq-node/src/DMQ/Policy.hs index 0c0b1779..0d2ae93f 100644 --- a/dmq-node/src/DMQ/Policy.hs +++ b/dmq-node/src/DMQ/Policy.hs @@ -54,7 +54,11 @@ maxSigBodySize :: SizeInBytes maxSigBodySize = 2000 --- | Minimum delay between signatures created by the same `PoolId`. +-- | Minimum distance between `sigExpiresAt` of two signatures issued by the +-- same `PoolId`, see `DMQ.Protocol.SigSubmission.SigSpacing`. +-- +-- A pool can have at most @maxSigExpiresAtDelay / minSigDelay@ (@30@) +-- signatures which have not expired. -- minSigDelay :: DiffTime minSigDelay = 60 @@ -130,6 +134,10 @@ sigSubmissionProtocolLimits = \case initiatorLimits = replyLimits, responderLimits = requestLimits } + NodeToNodeV_3 -> DirectionalLimits { + initiatorLimits = replyLimits, + responderLimits = requestLimits + } where -- A singleton body request takes 38 bytes including the 34-byte SigId. -- Separate requests to acknowledge one ID and request another take diff --git a/dmq-node/src/DMQ/Protocol/SigSubmission/SigSpacing.hs b/dmq-node/src/DMQ/Protocol/SigSubmission/SigSpacing.hs new file mode 100644 index 00000000..80bd51aa --- /dev/null +++ b/dmq-node/src/DMQ/Protocol/SigSubmission/SigSpacing.hs @@ -0,0 +1,118 @@ +-- | Limit how often a pool can issue signatures. +-- +-- `sigExpiresAt` of any two signatures issued by the same pool must be at +-- least `DMQ.Policy.minSigDelay` apart. +-- +-- The KES signature covers `sigExpiresAt`, so every node sees the same expiry. +-- A burst from another node's mempool passes the spacing check in any arrival +-- order if its expiries are far enough apart from each other and from those +-- already recorded for the same pool. Other checks, such as the OCert counter +-- check, can depend on arrival order. +-- +-- `sigExpiresAt` is chosen by the signer, but it must lie in +-- @[now, now + maxSigExpiresAtDelay)@ (see `DMQ.Policy.maxSigExpiresAtDelay`). +-- Thus a pool can have at most @maxSigExpiresAtDelay / minSigDelay@ +-- signatures which have not expired yet, and over any period of time @D@ it +-- can issue at most about @(D + maxSigExpiresAtDelay) / minSigDelay@ +-- signatures. For this to hold, the value of an expired signature must still +-- be taken into account for @minSigDelay@ after it expired, otherwise a pool +-- could issue signatures with a short time to live at an arbitrary rate. +-- +-- The module should be imported qualified. +-- +module DMQ.Protocol.SigSubmission.SigSpacing + ( SigSpacing + , empty + , expiryFloor + , insert + , toList + ) where + +import Data.OrdPSQ (OrdPSQ) +import Data.OrdPSQ qualified as OrdPSQ +import Data.Set (Set) +import Data.Set qualified as Set +import Data.Time.Clock (DiffTime) +import Data.Time.Clock.POSIX (POSIXTime) + + +-- | `sigExpiresAt` of recently accepted signatures, grouped by a key, e.g. +-- a `DMQ.Protocol.SigSubmission.Type.PoolId`. +-- +-- Invariants: +-- +-- * every set is non-empty; +-- * the priority of a key is the maximum of its set. +-- +data SigSpacing poolId = SigSpacing + !(Maybe POSIXTime) -- latest validation time used to prune the history + !(OrdPSQ poolId POSIXTime (Set POSIXTime)) + deriving Show + + +empty :: SigSpacing poolId +empty = SigSpacing Nothing OrdPSQ.empty + + +-- | Earliest expiry a writer may accept. Its clock sample can predate the +-- transaction that last pruned the shared history. +expiryFloor :: POSIXTime -> SigSpacing poolId -> POSIXTime +expiryFloor sampledNow (SigSpacing lastPrunedAt _) = + maybe sampledNow (max sampledNow) lastPrunedAt + + +-- | Record `sigExpiresAt` of a signature issued by @poolId@, unless it is +-- closer than @minSigDelay@ to `sigExpiresAt` of another signature issued by +-- the same @poolId@. +-- +-- The caller checks the expiry against 'expiryFloor' before insertion. +-- Values at least @minSigDelay@ below that floor can then be forgotten. +-- +insert :: Ord poolId + => DiffTime + -- ^ @minSigDelay@ + -> POSIXTime + -- ^ time sampled by the writer + -> poolId + -> POSIXTime + -- ^ `sigExpiresAt` + -> SigSpacing poolId + -> Either POSIXTime (SigSpacing poolId) + -- ^ either `sigExpiresAt` of a conflicting signature or the updated + -- `SigSpacing` +insert minSigDelay sampledNow poolId expiresAt spacing@(SigSpacing _ psq) = + case Set.lookupGT (max horizon (expiresAt - delay)) values of + Just conflict | conflict < expiresAt + delay -> Left conflict + _ -> + -- A rejection keeps the original queue, so prune other pools only + -- on success. + let values' = Set.insert expiresAt + . Set.dropWhileAntitone (<= horizon) + $ values + psq' = OrdPSQ.insert poolId (Set.findMax values') values' + . snd + . OrdPSQ.atMostView horizon + $ psq + in Right (SigSpacing (Just now) psq') + where + !now = expiryFloor sampledNow spacing + + delay :: POSIXTime + delay = realToFrac minSigDelay + + -- values which are not larger than `horizon` are forgotten + horizon :: POSIXTime + horizon = now - delay + + values :: Set POSIXTime + values = maybe Set.empty snd (OrdPSQ.lookup poolId psq) + + +-- | All recorded values, in ascending order of keys and values. Some values +-- at or below the last pruning cutoff might still be present. +-- +toList :: SigSpacing key -> [(key, [POSIXTime])] +toList (SigSpacing _ psq) = + [ (key, Set.toAscList values) + | (key, _, values) <- OrdPSQ.toAscList psq + ] diff --git a/dmq-node/src/DMQ/Protocol/SigSubmission/Type.hs b/dmq-node/src/DMQ/Protocol/SigSubmission/Type.hs index d6e1dc9d..26d4b343 100644 --- a/dmq-node/src/DMQ/Protocol/SigSubmission/Type.hs +++ b/dmq-node/src/DMQ/Protocol/SigSubmission/Type.hs @@ -347,6 +347,9 @@ data SigValidationError = | SigExpiresAtTooFarInTheFuture | SigResultOther Text | SigTooFrequent PoolId DiffTime + -- ^ The pool issued another signature whose `sigExpiresAt` is closer than + -- `DMQ.Policy.minSigDelay`; `DiffTime` is the distance between the two + -- `sigExpiresAt` values. See `DMQ.Protocol.SigSubmission.SigSpacing`. deriving (Eq, Show) instance ShowProxy SigValidationError where diff --git a/dmq-node/src/DMQ/Protocol/SigSubmission/Validate.hs b/dmq-node/src/DMQ/Protocol/SigSubmission/Validate.hs index 9155d64e..cb5b0419 100644 --- a/dmq-node/src/DMQ/Protocol/SigSubmission/Validate.hs +++ b/dmq-node/src/DMQ/Protocol/SigSubmission/Validate.hs @@ -27,7 +27,6 @@ import Control.Monad.State.Strict qualified as State import Data.ByteString (ByteString) import Data.ByteString.Lazy qualified as LBS import Data.Map.Strict qualified as Map -import Data.OrdPSQ qualified as OrdPSQ import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Cardano.Crypto.DSIGN.Class qualified as DSIGN @@ -45,6 +44,7 @@ import Cardano.Ledger.Keys qualified as Ledger import DMQ.Diffusion.NodeKernel (PoolValidationCtx (..), Readiness (..), ValidationCfg (..)) import DMQ.Policy qualified as Policy +import DMQ.Protocol.SigSubmission.SigSpacing qualified as SigSpacing import DMQ.Protocol.SigSubmission.Type @@ -113,36 +113,13 @@ validateSig ValidationCfg { vcMinSigDelay } sigs = State.runState (traverse (com sigExpiresAt } = do -- check if sig expired - vctxUTCNow <$> State.get >>= \utcNow -> do - let posixNow = utcTimeToPOSIXSeconds utcNow - posixNow <= sigExpiresAt ?! SigExpired - - -- check if sigExpiresAt is not too far in the future - let posixBound = utcTimeToPOSIXSeconds (Policy.maxSigExpiresAtDelay `addUTCTime` utcNow) - sigExpiresAt < posixBound ?! SigExpiresAtTooFarInTheFuture - - -- check if the PoolId doesn't forge signatures too frequently - (\st -> ( vctxNow st - , vctxLastSigByPoolId st - )) - <$> State.get >>= \(now, lastSigByPoolId) -> do - let fn :: Maybe (Time, ()) - -> (Either DiffTime (), Maybe (Time, ())) - fn Nothing - = (Right (), Just (now, ())) - - fn a@(Just (lastSeen, _)) - | sinceLast >= vcMinSigDelay - = (Right (), Just (now, ())) - - | otherwise - = (Left sinceLast, a) - where - sinceLast = now `diffTime` lastSeen - - (r, lastSigByPoolId') = OrdPSQ.alter fn poolId lastSigByPoolId - r ?!: SigTooFrequent poolId - State.modify (\a -> a { vctxLastSigByPoolId = lastSigByPoolId' }) + PoolValidationCtx { vctxUTCNow = utcNow, vctxSigSpacing = sigSpacing } <- State.get + let posixNow = utcTimeToPOSIXSeconds utcNow + SigSpacing.expiryFloor posixNow sigSpacing <= sigExpiresAt ?! SigExpired + + -- check if sigExpiresAt is not too far in the future + let posixBound = utcTimeToPOSIXSeconds (Policy.maxSigExpiresAtDelay `addUTCTime` utcNow) + sigExpiresAt < posixBound ?! SigExpiresAtTooFarInTheFuture -- TODO: if new cborg version is released, validation of SigId should be -- moved to the decoder, right now the decoder only verifies that we @@ -176,9 +153,30 @@ validateSig ValidationCfg { vcMinSigDelay } sigs = State.runState (traverse (com -- pool unregistered and is ineligible to mint signatures Just ZeroSetSnapshot -> left PoolNotEligible + -- + -- Cryptographic checks + -- + + -- validate OCert, which includes verifying its signature + validateOCert coldKey ocertVkHot ocert + ?!: InvalidSignatureOCERT ocertN sigKESPeriod + + -- validate KES signature of the payload + verifyKES () ocertVkHot + (unKESPeriod sigKESPeriod - unKESPeriod startKESPeriod) + (LBS.toStrict signedBytes) + kesSig + ?!: InvalidKESSignature ocertKESPeriod sigKESPeriod + -- -- verify that our observations of ocertN are strictly monotonic -- + -- NOTE: the result depends on the order in which signatures signed with + -- different operational certificates were received, so + -- `InvalidOCertCounter` does not disconnect a node-to-node peer. It's + -- checked after the cryptographic checks, so that a forged signature is + -- not rejected with `InvalidOCertCounter`. + -- vctxOcertMap <$> State.get >>= \ocertMap -> case Map.alterF (\a -> (a, Just ocertN)) @@ -197,19 +195,14 @@ validateSig ValidationCfg { vcMinSigDelay } sigs = State.runState (traverse (com -> left (InvalidOCertCounter prevOcertN ocertN) -- - -- Cryptographic checks - -- - - -- validate OCert, which includes verifying its signature - validateOCert coldKey ocertVkHot ocert - ?!: InvalidSignatureOCERT ocertN sigKESPeriod - - -- validate KES signature of the payload - verifyKES () ocertVkHot - (unKESPeriod sigKESPeriod - unKESPeriod startKESPeriod) - (LBS.toStrict signedBytes) - kesSig - ?!: InvalidKESSignature ocertKESPeriod sigKESPeriod + -- verify that the pool does not issue signatures too frequently, see + -- `DMQ.Protocol.SigSubmission.SigSpacing`. + + case SigSpacing.insert vcMinSigDelay posixNow poolId sigExpiresAt sigSpacing of + Left conflict -> + left (SigTooFrequent poolId (realToFrac (abs (sigExpiresAt - conflict)))) + Right sigSpacing' -> + State.modify (\a -> a { vctxSigSpacing = sigSpacing' }) return sig where diff --git a/dmq-node/test/DMQ/Protocol/SigSubmission/Test.hs b/dmq-node/test/DMQ/Protocol/SigSubmission/Test.hs index fd84107e..761c0924 100644 --- a/dmq-node/test/DMQ/Protocol/SigSubmission/Test.hs +++ b/dmq-node/test/DMQ/Protocol/SigSubmission/Test.hs @@ -33,10 +33,9 @@ import Data.Bifunctor (second) import Data.ByteString (ByteString) import Data.ByteString qualified as BS import Data.ByteString.Lazy qualified as BL +import Data.Either (lefts) import Data.List.NonEmpty qualified as NonEmpty import Data.Map qualified as Map -import Data.OrdPSQ (OrdPSQ) -import Data.OrdPSQ qualified as OrdPSQ import Data.Time.Clock.POSIX (posixSecondsToUTCTime) import Data.Typeable import Data.Word (Word32, Word64) @@ -47,8 +46,7 @@ import Network.TypedProtocol.Codec import Network.TypedProtocol.Codec.Properties hiding (prop_codec) import Cardano.Binary.FixedSizeCodec (encodeFixedSized) -import Cardano.Crypto.DSIGN.Class (DSIGNAlgorithm, SignKeyDSIGN, - deriveVerKeyDSIGN) +import Cardano.Crypto.DSIGN.Class (SignKeyDSIGN, deriveVerKeyDSIGN) import Cardano.Crypto.DSIGN.Class qualified as DSIGN import Cardano.Crypto.Hash.Blake2b (Blake2b_256) import Cardano.Crypto.Hash.Class (Hash, castHash, hashFromBytes, hashSize, @@ -71,6 +69,8 @@ import Test.Crypto.Instances import DMQ.Diffusion.NodeKernel (PoolValidationCtx (..), Readiness (..)) import DMQ.Policy qualified as Policy import DMQ.Protocol.SigSubmission.Codec +import DMQ.Protocol.SigSubmission.SigSpacing (SigSpacing) +import DMQ.Protocol.SigSubmission.SigSpacing qualified as SigSpacing import DMQ.Protocol.SigSubmission.Type import DMQ.Protocol.SigSubmission.Validate @@ -134,11 +134,18 @@ tests = [ testGroup "MockCrypto" [ testProperty "KES sign verify" prop_sign_verify_mockcrypto , testProperty "validateSig" prop_validateSig_mockcrypto + , testProperty "validateSig forged ocert counter" + prop_validateSig_forgedOCertCounter_mockcrypto + , testProperty "validateSig burst" prop_validateSig_burst_mockcrypto + , testProperty "validateSig with an older clock sample" prop_validateSig_staleTime ] #ifdef STANDARDCRYPTO_TESTS , testGroup "StandardCrypto" [ testProperty "KES sign verify" prop_sign_verify_standardcrypto , testProperty "validateSig" prop_validateSig_standardcrypto + , testProperty "validateSig forged ocert counter" + prop_validateSig_forgedOCertCounter_standardcrypto + , testProperty "validateSig burst" prop_validateSig_burst_standardcrypto ] #endif ] @@ -364,8 +371,6 @@ instance ( Crypto crypto , ContextKES kesCrypto ~ () , size ~ SeedSizeKES kesCrypto , Signable kesCrypto ByteString - , dsignCrypto ~ DSIGN crypto - , DSIGNAlgorithm dsignCrypto , Arbitrary (WithConstrKES size kesCrypto (CryptoCtx crypto)) ) => Arbitrary (WithConstrKES size kesCrypto (SigRawWithSignedBytes crypto)) where @@ -378,49 +383,69 @@ instance ( Crypto crypto kesOffset <- arbitrary `suchThat` (< fromIntegral maxKESEvo) sigRawBody <- arbitrary crypto <- arbitrary - return $ withConstrBind crypto \CryptoCtx {ocert, coldKey, snKESKey} -> do - let sigRawOpCertificate :: SigOpCertificate crypto - sigRawOpCertificate = SigOpCertificate ocert - - sigRawColdKey :: SigColdKey crypto - sigRawColdKey = SigColdKey $ deriveVerKeyDSIGN coldKey - - sigRawKESPeriod :: KESPeriod - sigRawKESPeriod = KESPeriod $ unKESPeriod (ocertKESPeriod ocert) - + kesOffset - - sigRaw = SigRaw { - sigRawId = undefined, -- to be filled below - sigRawBody, - sigRawKESPeriod, - sigRawOpCertificate, - sigRawColdKey, - sigRawExpiresAt, - sigRawKESSignature = undefined -- to be filled below - } - signedBytes = CBOR.toStrictByteString (encodeSigPayload sigRaw) - - -- evolve the key to the target period - mbSnKESKey <- KES.updateKESTo () sigRawKESPeriod ocert (KES.SignKeyWithPeriodKES snKESKey 0) - case mbSnKESKey of - Just (KES.SignKeyWithPeriodKES snKESKey' _) -> do - let sigRawId = SigId (castHash $ hashWith id signedBytes) - -- signed bytes with the snKESKey' - sigRawKESSignature - <- SigKESSignature - <$> KES.signKES () kesOffset signedBytes snKESKey' - return SigRawWithSignedBytes { - sigRawSignedBytes = BL.fromStrict signedBytes, - sigRaw = sigRaw { sigRawId, - sigRawKESSignature } - } - Nothing -> - error $ "arbitrary SigRawWithSignedBytes: could not evolve KES key to the target period by KES offset: " - ++ show kesOffset + return $ withConstrBind crypto \cryptoCtx -> + signSigRaw cryptoCtx sigRawBody kesOffset sigRawExpiresAt shrink = shrinkWithConstrSigRawWithSignedBytes +-- | Create a signature of a payload with the keys of a `CryptoCtx`. +-- +signSigRaw + :: forall crypto. + ( Crypto crypto + , ContextKES (KES crypto) ~ () + , Signable (KES crypto) ByteString + ) + => CryptoCtx crypto + -> SigBody + -> Word + -- ^ KES period offset since `ocertKESPeriod` + -> POSIXTime + -- ^ `sigExpiresAt` + -> IO (SigRawWithSignedBytes crypto) +signSigRaw CryptoCtx { ocert, coldKey, snKESKey } + sigRawBody kesOffset sigRawExpiresAt = do + -- evolve the key to the target period + mbSnKESKey <- KES.updateKESTo () sigRawKESPeriod ocert (KES.SignKeyWithPeriodKES snKESKey 0) + case mbSnKESKey of + Just (KES.SignKeyWithPeriodKES snKESKey' _) -> do + let sigRawId = SigId (castHash $ hashWith id signedBytes) + -- signed bytes with the snKESKey' + sigRawKESSignature + <- SigKESSignature + <$> KES.signKES () kesOffset signedBytes snKESKey' + return SigRawWithSignedBytes { + sigRawSignedBytes = BL.fromStrict signedBytes, + sigRaw = sigRaw { sigRawId, + sigRawKESSignature } + } + Nothing -> + error $ "signSigRaw: could not evolve KES key to the target period by KES offset: " + ++ show kesOffset + where + sigRawOpCertificate :: SigOpCertificate crypto + sigRawOpCertificate = SigOpCertificate ocert + + sigRawColdKey :: SigColdKey crypto + sigRawColdKey = SigColdKey $ deriveVerKeyDSIGN coldKey + + sigRawKESPeriod :: KESPeriod + sigRawKESPeriod = KESPeriod $ unKESPeriod (ocertKESPeriod ocert) + + kesOffset + + sigRaw = SigRaw { + sigRawId = undefined, -- to be filled above + sigRawBody, + sigRawKESPeriod, + sigRawOpCertificate, + sigRawColdKey, + sigRawExpiresAt, + sigRawKESSignature = undefined -- to be filled above + } + signedBytes = CBOR.toStrictByteString (encodeSigPayload sigRaw) + + -- Shrinking function for the above instance. It's easier to get its type -- signature right here. -- @@ -888,37 +913,44 @@ prop_codec_valid_cbor_standardcrypto = prop_codec_valid_cbor . getBlind -- | Context which decides if a signature is valid or not. -- --- `currentDiffTime`: diff between current time and `expiresAt` (if negative then --- a signature is valid) +-- `currentTimeDiff`: diff between current time and `expiresAt` (if negative +-- then a signature is valid) +-- +-- `otherExpiresAtDiff`: the same pool issued another signature, which was +-- already accepted, whose `sigExpiresAt` is `sigExpiresAt` of the validated +-- signature plus `otherExpiresAtDiff`. The two signatures conflict if its +-- absolute value is smaller than `Policy.minSigDelay`. Signatures which are +-- invalid for other reasons might conflict too: the spacing rule is checked +-- last, so the other validation error is expected. -- data Validity = Valid { - currentTimeDiff :: NominalDiffTime, - lastSigTimeDiff :: DiffTime + currentTimeDiff :: NominalDiffTime, + otherExpiresAtDiff :: NominalDiffTime } | InvalidViaNotInitialized { - currentTimeDiff :: NominalDiffTime, - lastSigTimeDiff :: DiffTime + currentTimeDiff :: NominalDiffTime, + otherExpiresAtDiff :: NominalDiffTime } | InvalidViaUnrecognizedPool { - currentTimeDiff :: NominalDiffTime, - lastSigTimeDiff :: DiffTime + currentTimeDiff :: NominalDiffTime, + otherExpiresAtDiff :: NominalDiffTime } | InvalidViaSigExpired { - currentTimeDiff :: NominalDiffTime, - lastSigTimeDiff :: DiffTime + currentTimeDiff :: NominalDiffTime, + otherExpiresAtDiff :: NominalDiffTime } | InvalidViaPoolNotEligible { - currentTimeDiff :: NominalDiffTime, - lastSigTimeDiff :: DiffTime + currentTimeDiff :: NominalDiffTime, + otherExpiresAtDiff :: NominalDiffTime } | InvalidViaOCertCounter { - currentTimeDiff :: NominalDiffTime, - lastSigTimeDiff :: DiffTime + currentTimeDiff :: NominalDiffTime, + otherExpiresAtDiff :: NominalDiffTime } | InvalidViaTooRecentSig { - currentTimeDiff :: NominalDiffTime, - lastSigTimeDiff :: DiffTime + currentTimeDiff :: NominalDiffTime, + otherExpiresAtDiff :: NominalDiffTime } deriving (Eq, Show) @@ -933,47 +965,87 @@ labelValidity = \case InvalidViaTooRecentSig {} -> label "InvalidViaTooRecentSig" +-- | `Policy.minSigDelay` as `NominalDiffTime`. +-- +nominalMinSigDelay :: NominalDiffTime +nominalMinSigDelay = realToFrac Policy.minSigDelay + +-- | `otherExpiresAtDiff` which does not conflict with the validated signature. +-- +genFarExpiresAtDiff :: Gen NominalDiffTime +genFarExpiresAtDiff = do + sign <- elements [1, -1] + extra <- realToFrac <$> choose (0, 3600 :: Double) + return (sign * (nominalMinSigDelay + extra)) + +-- | `otherExpiresAtDiff` which conflicts with the validated signature. +-- +genNearExpiresAtDiff :: Gen NominalDiffTime +genNearExpiresAtDiff = + (realToFrac <$> choose (-d, d)) `suchThat` (\a -> abs a < nominalMinSigDelay) + where + d :: Double + d = realToFrac Policy.minSigDelay + +genAnyExpiresAtDiff :: Gen NominalDiffTime +genAnyExpiresAtDiff = oneof [genFarExpiresAtDiff, genNearExpiresAtDiff] + +-- | Make `otherExpiresAtDiff` non-conflicting, preserving its sign. +-- +toFarExpiresAtDiff :: NominalDiffTime -> NominalDiffTime +toFarExpiresAtDiff a + | abs a >= nominalMinSigDelay = a + | a < 0 = -nominalMinSigDelay + | otherwise = nominalMinSigDelay + instance Arbitrary Validity where arbitrary = oneof [ Valid <$> arbitrary `suchThat` (<= 0) - <*> arbitrary `suchThat` (<= -Policy.minSigDelay) + <*> genFarExpiresAtDiff , InvalidViaNotInitialized <$> arbitrary `suchThat` (<= 0) - <*> arbitrary `suchThat` (<= -Policy.minSigDelay) + <*> genAnyExpiresAtDiff , InvalidViaUnrecognizedPool <$> arbitrary `suchThat` (<= 0) - <*> arbitrary `suchThat` (<= -Policy.minSigDelay) + <*> genAnyExpiresAtDiff , InvalidViaSigExpired <$> arbitrary `suchThat` (> 0) - <*> arbitrary `suchThat` (<= -Policy.minSigDelay) + <*> genAnyExpiresAtDiff , InvalidViaPoolNotEligible <$> arbitrary `suchThat` (<= 0) - <*> arbitrary `suchThat` (<= -Policy.minSigDelay) + <*> genAnyExpiresAtDiff , InvalidViaOCertCounter <$> arbitrary `suchThat` (<= 0) - <*> arbitrary `suchThat` (<= -Policy.minSigDelay) + <*> genAnyExpiresAtDiff , InvalidViaTooRecentSig <$> arbitrary `suchThat` (<= 0) - <*> arbitrary `suchThat` (\a -> a > -Policy.minSigDelay && a <= 0) + <*> genNearExpiresAtDiff ] shrink a@Valid { currentTimeDiff } = [ a { currentTimeDiff = t } | t <- shrink currentTimeDiff, t <= 0 ] - shrink (InvalidViaNotInitialized { currentTimeDiff, lastSigTimeDiff }) - = [ Valid { currentTimeDiff, lastSigTimeDiff } ] - shrink (InvalidViaUnrecognizedPool { currentTimeDiff, lastSigTimeDiff }) - = [ Valid { currentTimeDiff, lastSigTimeDiff } ] - shrink a@InvalidViaSigExpired { currentTimeDiff, lastSigTimeDiff } + shrink (InvalidViaNotInitialized { currentTimeDiff, otherExpiresAtDiff }) + = [ Valid { currentTimeDiff, + otherExpiresAtDiff = toFarExpiresAtDiff otherExpiresAtDiff } ] + shrink (InvalidViaUnrecognizedPool { currentTimeDiff, otherExpiresAtDiff }) + = [ Valid { currentTimeDiff, + otherExpiresAtDiff = toFarExpiresAtDiff otherExpiresAtDiff } ] + shrink a@InvalidViaSigExpired { currentTimeDiff, otherExpiresAtDiff } = [ a { currentTimeDiff = t } | t <- shrink currentTimeDiff, t > 0 ] - ++ [ Valid { currentTimeDiff = 0, lastSigTimeDiff } ] - shrink a@InvalidViaPoolNotEligible { currentTimeDiff, lastSigTimeDiff } + ++ [ Valid { currentTimeDiff = 0, + otherExpiresAtDiff = toFarExpiresAtDiff otherExpiresAtDiff } ] + shrink a@InvalidViaPoolNotEligible { currentTimeDiff, otherExpiresAtDiff } = [ a { currentTimeDiff = t } | t <- shrink currentTimeDiff, t <= 0 ] - ++ [ Valid { currentTimeDiff, lastSigTimeDiff } ] - shrink InvalidViaOCertCounter { currentTimeDiff, lastSigTimeDiff } - = [ Valid { currentTimeDiff, lastSigTimeDiff } ] - shrink InvalidViaTooRecentSig { currentTimeDiff, lastSigTimeDiff } - = [ Valid { currentTimeDiff, lastSigTimeDiff = lastSigTimeDiff - 30 } ] + ++ [ Valid { currentTimeDiff, + otherExpiresAtDiff = toFarExpiresAtDiff otherExpiresAtDiff } ] + shrink InvalidViaOCertCounter { currentTimeDiff, otherExpiresAtDiff } + = [ Valid { currentTimeDiff, + otherExpiresAtDiff = toFarExpiresAtDiff otherExpiresAtDiff } ] + shrink a@InvalidViaTooRecentSig { currentTimeDiff, otherExpiresAtDiff } + = [ a { otherExpiresAtDiff = 0 } | otherExpiresAtDiff /= 0 ] + ++ [ Valid { currentTimeDiff, + otherExpiresAtDiff = toFarExpiresAtDiff otherExpiresAtDiff } ] -- | Check that the KES signature is valid. @@ -1020,15 +1092,17 @@ prop_validateSig constr validity = labelValidity validity $ ioProperty do vctxUTCNow :: UTCTime vctxUTCNow = posixSecondsToUTCTime posixNow - vctxNow :: Time - vctxNow = Time 0 - - vctxLastSigByPoolId :: OrdPSQ PoolId Time () - vctxLastSigByPoolId = - case validity of - InvalidViaTooRecentSig { lastSigTimeDiff } -> - OrdPSQ.fromList [(poolId, lastSigTimeDiff `addTime` vctxNow, ())] - _ -> OrdPSQ.fromList [(poolId, lastSigTimeDiff validity `addTime` vctxNow, ())] + -- another signature issued by the same pool, which was accepted + -- before + vctxSigSpacing :: SigSpacing PoolId + vctxSigSpacing = + case SigSpacing.insert Policy.minSigDelay + posixNow + poolId + (sigExpiresAt + otherExpiresAtDiff validity) + SigSpacing.empty of + Right a -> a + Left _ -> error "prop_validateSig: invariant violation" vctxReadiness :: Readiness vctxReadiness = case validity of @@ -1049,13 +1123,12 @@ prop_validateSig constr validity = labelValidity validity $ ioProperty do _ -> Map.fromList [(poolId, ocertN)] validationCtx = PoolValidationCtx { - vctxNow, vctxUTCNow, vctxReadiness, vctxStakeMap, vctxOcertMap, vctxPraosMaxKESEvo = maxKESEvo, -- hard coded Shelley value for testing - vctxLastSigByPoolId + vctxSigSpacing } validationCfg :: ValidationCfg @@ -1111,6 +1184,256 @@ prop_validateSig_standardcrypto prop_validateSig_standardcrypto = prop_validateSig . getBlind +-- | A signature whose operational certificate counter was forged, and is +-- smaller than the last observed counter of the pool, is rejected with +-- `InvalidSignatureOCERT`, which disconnects a node-to-node peer, rather than +-- with `InvalidOCertCounter`, which does not: the counter is checked after the +-- cryptographic checks. +-- +prop_validateSig_forgedOCertCounter + :: ( Crypto crypto + , DSIGN crypto ~ Ledger.Keys.DSIGN + , DSIGN.Signable (DSIGN crypto) (KES.OCertSignable crypto) + , KES.ContextKES (KES crypto) ~ () + , KES.Signable (KES crypto) ByteString + ) + => WithConstrKES size kesCrypt (Sig crypto) + -> Property +prop_validateSig_forgedOCertCounter constr = ioProperty do + sig@Sig { sigColdKey = SigColdKey coldKey, + sigOpCertificate = SigOpCertificate ocert@OCert { ocertN }, + sigExpiresAt + } <- runWithConstr constr + let poolId = hashKey (VKey coldKey) + + -- a counter which was not signed by the cold key, and which is + -- smaller than the last observed counter (`maxBound`) + forgedN | ocertN == 0 = 1 + | otherwise = ocertN - 1 + + forgedSig = sig { sigOpCertificate = SigOpCertificate ocert { ocertN = forgedN } } + + validationCtx = PoolValidationCtx { + vctxUTCNow = posixSecondsToUTCTime sigExpiresAt, + vctxReadiness = Ready, + vctxStakeMap = Map.fromList + [( poolId + , StakeSnapshot { ssMarkPool = mempty, + ssSetPool = succ mempty, + ssGoPool = mempty + } + )], + vctxOcertMap = Map.fromList [(poolId, maxBound)], + vctxPraosMaxKESEvo = maxKESEvo, + vctxSigSpacing = SigSpacing.empty + } + + validationCfg :: ValidationCfg + validationCfg = ValidationCfg { vcMinSigDelay = Policy.minSigDelay } + + return . counterexample (show forgedSig) + $ case fst (validateSig validationCfg [forgedSig] validationCtx) of + [Left (_, InvalidSignatureOCERT {})] -> property True + r -> counterexample (show r) False + +prop_validateSig_forgedOCertCounter_mockcrypto + :: Blind (WithConstrKES (SeedSizeKES (KES MockCrypto)) (KES MockCrypto) (Sig MockCrypto)) + -> Property +prop_validateSig_forgedOCertCounter_mockcrypto = prop_validateSig_forgedOCertCounter . getBlind + +prop_validateSig_forgedOCertCounter_standardcrypto + :: Blind (WithConstrKES (SeedSizeKES (KES StandardCrypto)) (KES StandardCrypto) (Sig StandardCrypto)) + -> Property +prop_validateSig_forgedOCertCounter_standardcrypto = prop_validateSig_forgedOCertCounter . getBlind + + +-- | Signatures issued by a single pool: the current time and `sigExpiresAt` +-- offsets (in seconds) since the current time. The offsets are at least +-- `Policy.minSigDelay` apart, smaller than `Policy.maxSigExpiresAtDelay` and +-- in an arbitrary order. +-- +data SigsBurst = SigsBurst { + burstNow :: Word32, + burstOffsets :: [Word32] + } + deriving Show + +instance Arbitrary SigsBurst where + arbitrary = do + burstNow <- choose (0, maxBound - maxDelay) + start <- choose (0, minDelay - 1) + gaps <- listOf (choose (minDelay, 3 * minDelay)) + burstOffsets <- shuffle (takeWhile (< maxDelay) (scanl (+) start gaps)) + return SigsBurst { burstNow, burstOffsets } + where + minDelay, maxDelay :: Word32 + minDelay = floor Policy.minSigDelay + maxDelay = floor Policy.maxSigExpiresAtDelay + + -- removing offsets preserves the invariants + shrink burst@SigsBurst { burstOffsets } = + [ burst { burstOffsets = burstOffsets' } + | burstOffsets' <- shrinkList (const []) burstOffsets + ] + + +-- | Validate a burst from one pool at a fixed time with an empty spacing +-- history. The signatures use the same OCert and have expiries in the validity +-- window at least `Policy.minSigDelay` apart, so the burst passes in any order. +-- Such a burst can accumulate in another node's mempool. See +-- https://github.com/IntersectMBO/dmq-node/issues/82. +-- +prop_validateSig_burst + :: forall crypto. + ( Crypto crypto + , DSIGN crypto ~ Ledger.Keys.DSIGN + , DSIGN.Signable (DSIGN crypto) (KES.OCertSignable crypto) + , KES.ContextKES (KES crypto) ~ () + , KES.Signable (KES crypto) ByteString + ) + => WithConstrKES (SeedSizeKES (KES crypto)) (KES crypto) (CryptoCtx crypto) + -> SigBody + -> SigsBurst + -> Property +prop_validateSig_burst constr sigBody SigsBurst { burstNow, burstOffsets } = + ioProperty do + cryptoCtx@CryptoCtx { coldKey, ocert = OCert { ocertN } } + <- runWithConstr constr + sigs <- traverse (\offset -> mkSig <$> signSigRaw cryptoCtx sigBody 0 + (posixNow + fromIntegral offset)) + burstOffsets + let poolId = hashKey (VKey (deriveVerKeyDSIGN coldKey)) + + validationCtx = PoolValidationCtx { + vctxUTCNow = posixSecondsToUTCTime posixNow, + vctxReadiness = Ready, + vctxStakeMap = Map.fromList + [( poolId + , StakeSnapshot { ssMarkPool = mempty, + ssSetPool = succ mempty, + ssGoPool = mempty + } + )], + vctxOcertMap = Map.fromList [(poolId, ocertN)], + vctxPraosMaxKESEvo = maxKESEvo, + vctxSigSpacing = SigSpacing.empty + } + + validationCfg :: ValidationCfg + validationCfg = ValidationCfg { vcMinSigDelay = Policy.minSigDelay } + + rejected :: [Sig crypto] -> [(SigId, SigValidationError)] + rejected sigs' = + lefts (fst (validateSig validationCfg sigs' validationCtx)) + + return . counterexample (show sigs) + $ counterexample "rejected" (rejected sigs === []) + .&&. counterexample "rejected in reverse order" (rejected (reverse sigs) === []) + where + posixNow :: POSIXTime + posixNow = fromIntegral burstNow + +prop_validateSig_burst_mockcrypto + :: Blind (WithConstrKES (SeedSizeKES (KES MockCrypto)) (KES MockCrypto) (CryptoCtx MockCrypto)) + -> SigBody + -> SigsBurst + -> Property +prop_validateSig_burst_mockcrypto = prop_validateSig_burst . getBlind + +prop_validateSig_burst_standardcrypto + :: Blind (WithConstrKES (SeedSizeKES (KES StandardCrypto)) (KES StandardCrypto) (CryptoCtx StandardCrypto)) + -> SigBody + -> SigsBurst + -> Property +prop_validateSig_burst_standardcrypto = prop_validateSig_burst . getBlind + + +-- | An older clock sample must respect the expiry floor committed by a writer +-- validating a signature from another pool. +prop_validateSig_staleTime + :: Blind (WithConstrKES (SeedSizeKES (KES MockCrypto)) (KES MockCrypto) (CryptoCtx MockCrypto)) + -> Blind (WithConstrKES (SeedSizeKES (KES MockCrypto)) (KES MockCrypto) (CryptoCtx MockCrypto)) + -> SigBody + -> Property +prop_validateSig_staleTime (Blind genA) (Blind genB) body = once $ ioProperty do + poolA <- runWithConstr genA + poolB <- runWithConstr genB + + let start, pruneTime, olderSample :: NominalDiffTime + start = 1000 + pruneTime = start + nominalMinSigDelay + olderSample = pruneTime - 1 + + sign :: CryptoCtx MockCrypto -> NominalDiffTime -> IO (Sig MockCrypto) + sign issuer expiresAt = mkSig <$> signSigRaw issuer body 0 expiresAt + + poolId :: CryptoCtx MockCrypto -> Ledger.Keys.KeyHash kd + poolId issuer = hashKey (VKey (deriveVerKeyDSIGN (coldKey issuer))) + + stake = StakeSnapshot { + ssMarkPool = mempty, + ssSetPool = succ mempty, + ssGoPool = mempty + } + initialCtx = PoolValidationCtx { + vctxUTCNow = posixSecondsToUTCTime start, + vctxReadiness = Ready, + vctxStakeMap = Map.fromList [(poolId poolA, stake), (poolId poolB, stake)], + vctxOcertMap = Map.empty, + vctxPraosMaxKESEvo = maxKESEvo, + vctxSigSpacing = SigSpacing.empty + } + + validateAt + :: NominalDiffTime + -> [Sig MockCrypto] + -> PoolValidationCtx + -> ( [Either (SigId, SigValidationError) (Sig MockCrypto)] + , PoolValidationCtx + ) + validateAt time sigs ctx' = + validateSig (ValidationCfg Policy.minSigDelay) sigs + ctx' { vctxUTCNow = posixSecondsToUTCTime time } + + firstA <- sign poolA start -- 1000 + firstB <- sign poolB pruneTime -- 1060 + nextB <- sign poolB (pruneTime + nominalMinSigDelay) -- 1120 + expiredA <- sign poolA olderSample -- 1059 + atFloorA <- sign poolA pruneTime -- 1060 + tooFarA <- sign poolA (olderSample + Policy.maxSigExpiresAtDelay) + -- 2859 + + let (initial, withA) = validateAt start [firstA] initialCtx + (newer, pruned) = validateAt pruneTime [firstB] withA + -- Accepting a live signature with an older sample must preserve the floor. + (older, afterOlderWriter) = validateAt olderSample [nextB] pruned + -- A later rejected submission leaves the committed floor at pruneTime. + (rejected, afterRejection) = validateAt (pruneTime + 1) [atFloorA] afterOlderWriter + (results, _) = validateAt olderSample [expiredA, atFloorA, tooFarA] afterRejection + + return + $ poolId poolA /= poolId poolB ==> conjoin + [ fmap sigId `map` (initial ++ newer ++ older) + === + (Right . sigId) `map` [firstA, firstB, nextB] + + , SigSpacing.toList (vctxSigSpacing pruned) + === + [(poolId poolB, [pruneTime])] + + , lefts rejected + === + [(sigId atFloorA, SigExpired)] + + , fmap sigId `map` results + === + [ Left (sigId expiredA, SigExpired) + , Right (sigId atFloorA) + , Left (sigId tooFarA, SigExpiresAtTooFarInTheFuture) + ] + ] + + -- | Sign & verify a payload with KES keys. -- prop_sign_verify diff --git a/dmq-node/test/Main.hs b/dmq-node/test/Main.hs index b6c26521..964c1125 100644 --- a/dmq-node/test/Main.hs +++ b/dmq-node/test/Main.hs @@ -8,6 +8,7 @@ import Test.DMQ.NodeToClient qualified import Test.DMQ.NodeToNode qualified import Test.DMQ.PeerSelection.PeerMetric qualified import Test.DMQ.SigSubmission.App qualified +import Test.DMQ.SigSubmission.SigSpacing qualified import DMQ.Protocol.LocalMsgNotification.Test qualified import DMQ.Protocol.LocalMsgSubmission.Test qualified @@ -30,6 +31,7 @@ tests = , Test.DMQ.NodeToNode.tests , Test.DMQ.PeerSelection.PeerMetric.tests , Test.DMQ.SigSubmission.App.tests + , Test.DMQ.SigSubmission.SigSpacing.tests -- protocols , DMQ.Protocol.SigSubmission.Test.tests diff --git a/dmq-node/test/Test/DMQ/NodeToNode.hs b/dmq-node/test/Test/DMQ/NodeToNode.hs index 195cca7b..f4f4a06e 100644 --- a/dmq-node/test/Test/DMQ/NodeToNode.hs +++ b/dmq-node/test/Test/DMQ/NodeToNode.hs @@ -1,18 +1,32 @@ {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE NumericUnderscores #-} +{-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -Wno-orphans #-} module Test.DMQ.NodeToNode (tests) where +import Codec.CBOR.Term qualified as CBOR +import Control.Monad.Class.MonadAsync (concurrently) +import Control.Monad.IOSim (IOSim, runSimOrThrow) +import Control.Tracer (nullTracer) +import Data.Aeson qualified as Aeson import Data.Foldable (fold) +import Ouroboros.Network.Channel (createConnectedChannels) import Ouroboros.Network.CodecCBORTerm import Ouroboros.Network.DiffusionMode +import Ouroboros.Network.Driver.Simple (runPeer) import Ouroboros.Network.Magic (NetworkMagic (..)) import Ouroboros.Network.Mux qualified as Mux import Ouroboros.Network.PeerSelection.PeerSharing (PeerSharing (..)) +import Ouroboros.Network.Protocol.Handshake (Acceptable (acceptableVersion), + HandshakeResult (..), codecHandshake, combineVersions, + simpleSingletonVersions) +import Ouroboros.Network.Protocol.Handshake.Client (handshakeClientPeer) +import Ouroboros.Network.Protocol.Handshake.Server (handshakeServerPeer) import DMQ.NodeToNode +import Test.DMQ.NodeToNode.SigSubmission qualified as SigSubmission import Test.QuickCheck import Test.Tasty (TestTree, testGroup) @@ -24,6 +38,8 @@ tests = testGroup "DMQ.Network.NodeToNode" [ testProperty "nodeToNodeVersionCodec" prop_nodeToNodeVersionCodec , testProperty "nodeToNodeCodecCBORTerm" prop_nodeToNodeCodec , testProperty "mini-protocol ingress limits" prop_nodeToNodeIngressLimits + , testProperty "negotiates the highest common version" prop_handshake + , SigSubmission.tests ] instance Arbitrary NodeToNodeVersion where @@ -46,26 +62,43 @@ instance Arbitrary NodeToNodeVersionData where <*> arbitrary -prop_nodeToNodeVersionCodec :: NodeToNodeVersion - -> Bool -prop_nodeToNodeVersionCodec version = - case decodeTerm (encodeTerm version) of - Right version' -> version == version' - Left {} -> False +prop_nodeToNodeVersionCodec :: Property +prop_nodeToNodeVersionCodec = once $ conjoin + [ counterexample (show version) $ conjoin + [ encodeTerm version + === + CBOR.TInt tag + + , decodeTerm (CBOR.TInt tag) + === + Right version + + , Aeson.toJSON version + === + Aeson.toJSON tag + ] + | version <- [minBound..maxBound] + , let tag = versionTag version + ] where - CodecCBORTerm { encodeTerm, decodeTerm } = nodeToNodeVersionCodec + versionTag :: NodeToNodeVersion -> Int + versionTag NodeToNodeV_1 = 1 + versionTag NodeToNodeV_2 = 2 + versionTag NodeToNodeV_3 = 3 + + CodecCBORTerm { encodeTerm, decodeTerm } = nodeToNodeVersionCodec prop_nodeToNodeCodec :: NodeToNodeVersion -> NodeToNodeVersionData -> Bool prop_nodeToNodeCodec ntnVersion ntnData = - case decodeTerm (encodeTerm ntnData) of - Right ntnData' -> networkMagic ntnData' == networkMagic ntnData - && diffusionMode ntnData' == diffusionMode ntnData - Left {} -> False + decodeTerm (encodeTerm ntnData) == Right ntnData where CodecCBORTerm { encodeTerm, decodeTerm } = nodeToNodeCodecCBORTerm ntnVersion +-- | TODO: this test should generate requests that fill allowed pipelining +-- depth, use production codec and then check that mux with the current limits +-- is not overflowing. prop_nodeToNodeIngressLimits :: NodeToNodeVersion -> NodeToNodeVersionData -> Property prop_nodeToNodeIngressLimits version versionData = [ (num, Mux.maximumIngressQueue initiatorLimits, Mux.maximumIngressQueue responderLimits) @@ -79,8 +112,47 @@ prop_nodeToNodeIngressLimits version versionData = sigLimits = case version of NodeToNodeV_1 -> (11, 72_088, 101_640) NodeToNodeV_2 -> (11, 101_640, 72_088) + NodeToNodeV_3 -> (11, 101_640, 72_088) bundle = nodeToNodeProtocols dmqLimitsAndTimeouts (Protocols run run run) version versionData run = Mux.InitiatorAndResponderProtocol peer peer peer = Mux.MiniProtocolCb $ \_ _ -> pure ((), Nothing) :: IO ((), Maybe ()) +prop_handshake :: Property +prop_handshake = once $ conjoin + [ counterexample (show (clientMax, serverMax)) $ + let expected = Just (clientMax `min` serverMax) in + runSimOrThrow (negotiate clientMax serverMax) + === + (expected, expected) + | clientMax <- [minBound .. maxBound] + , serverMax <- [minBound .. maxBound] + ] + where + negotiate :: NodeToNodeVersion -> NodeToNodeVersion + -> IOSim s (Maybe NodeToNodeVersion, Maybe NodeToNodeVersion) + negotiate clientMax serverMax = do + (client, server) <- createConnectedChannels + let dataCodec = mkVersionedCodecCBORTerm nodeToNodeCodecCBORTerm + (clientResult, serverResult) <- concurrently + (runPeer nullTracer (codec clientMax) client $ + handshakeClientPeer dataCodec acceptableVersion (versions clientMax)) + (runPeer nullTracer (codec serverMax) server $ + handshakeServerPeer dataCodec acceptableVersion query (versions serverMax)) + pure (agreedVersion clientResult, agreedVersion serverResult) + + agreedVersion (Right (HandshakeNegotiationResult _ v _), _) = Just v + agreedVersion _ = Nothing + + versions highest = combineVersions + [ simpleSingletonVersions v versionData (const ()) + | v <- [minBound .. highest] ] + versionData = stdVersionDataNTN (NetworkMagic 42) InitiatorAndResponderDiffusionMode + PeerSharingDisabled + + -- A legacy decoder also sees the unknown tags in a newer peer's offer. + codec highest = codecHandshake nodeToNodeVersionCodec { + decodeTerm = \term -> do + v <- decodeTerm nodeToNodeVersionCodec term + if v <= highest then Right v else Left ("unknown version", Nothing) + } diff --git a/dmq-node/test/Test/DMQ/NodeToNode/SigSubmission.hs b/dmq-node/test/Test/DMQ/NodeToNode/SigSubmission.hs new file mode 100644 index 00000000..5877bf72 --- /dev/null +++ b/dmq-node/test/Test/DMQ/NodeToNode/SigSubmission.hs @@ -0,0 +1,122 @@ +{-# LANGUAGE RankNTypes #-} + +module Test.DMQ.NodeToNode.SigSubmission (tests) where + +import Control.Monad (unless, void) +import Control.Monad.Class.MonadAsync (link, withAsync) +import Control.Monad.Class.MonadTime.SI (diffTime, getMonotonicTime) +import Control.Monad.Class.MonadTimer.SI (threadDelay, timeout) +import Control.Monad.IOSim (IOSim, runSimOrThrow) +import Control.Tracer (nullTracer) +import Data.Foldable (toList) +import Data.Singletons (SingI) +import Data.Word (Word16) +import Network.TypedProtocol.Codec (AnyMessage (..)) +import Ouroboros.Network.Channel (Channel (..), createConnectedChannels) +import Ouroboros.Network.ControlMessage (ControlMessage (Continue)) +import Ouroboros.Network.Driver.Simple (runPeer) +import Ouroboros.Network.Protocol.TxSubmission2.Codec (codecTxSubmission2Id) +import Ouroboros.Network.Protocol.TxSubmission2.Type qualified as V1 + +import DMQ.Mempool qualified as Mempool +import DMQ.NodeToNode.SigSubmission (outboundV1, outboundV2) +import DMQ.NodeToNode.Version (NodeToNodeVersion (..)) +import DMQ.Protocol.SigSubmissionV2.Codec (codecSigSubmissionV2Id) +import DMQ.Protocol.SigSubmissionV2.Type qualified as V2 + +import Test.QuickCheck (Property, once, property) +import Test.Tasty (TestTree, testGroup) +import Test.Tasty.QuickCheck (testProperty) + +tests :: TestTree +tests = testGroup "outbound signature bursts" + [ testProperty (show v) (prop_burst v) | v <- [minBound .. maxBound] ] + +data Requests m = Requests { + requestIds :: forall b. SingI b => V1.SingBlockingStyle b -> Word16 -> m [Int], + requestBodies :: [Int] -> m [Int] + } + +-- The peer has caught up with signature 10 when the rest of the burst arrives. +-- The tens digit identifies the pool. +prop_burst :: NodeToNodeVersion -> Property +prop_burst version = once $ property $ runSimOrThrow $ do + mp <- Mempool.new id [10] + let reader = Mempool.getIndexedReader id (const 1) mp + writer = Mempool.getWriter () id (\_ -> pure . map Right) (const $ pure ()) mp + withPeer version reader $ \Requests {requestIds, requestBodies} -> do + requestIds V1.SingBlocking 0 >>= expect [10] + requestBodies [10] >>= expect [10] + void $ Mempool.mempoolAddTxs writer [11, 20, 21] + + if version == NodeToNodeV_3 then do + start <- getMonotonicTime + requestIds V1.SingNonBlocking 0 >>= expect [11, 20, 21] + requestBodies [11, 20, 21] >>= expect [11, 20, 21] + getMonotonicTime >>= expect start + else do + requestIds V1.SingNonBlocking 0 >>= expect [20] + requestBodies [20] >>= expect [20] + threadDelay 65 + requestIds V1.SingNonBlocking 0 >>= expect [] + + -- A partial acknowledgement releases only the first pool, after 60s. + requestIds V1.SingNonBlocking 1 >>= expect [] + threadDelay 59 + requestIds V1.SingNonBlocking 0 >>= expect [] + threadDelay 1 + requestIds V1.SingNonBlocking 0 >>= expect [11] + requestBodies [11] >>= expect [11] + + -- V1 can block until the timer fires. V2 must answer empty blocking + -- requests on its usual timeout while this pool is cooling down. + start <- getMonotonicTime + let awaitIds ack = requestIds V1.SingBlocking ack >>= \case + [] -> awaitIds 0 + ids -> pure ids + timeout 61 (awaitIds 2) >>= expect (Just [21]) + end <- getMonotonicTime + expect 60 (diffTime end start) + requestBodies [21] >>= expect [21] + pure True + where + expect expected actual = unless (actual == expected) $ + fail ("expected " ++ show expected ++ ", received " ++ show actual) + +withPeer :: NodeToNodeVersion + -> Mempool.TxSubmissionMempoolReader Int Int Integer (IOSim s) + -> (Requests (IOSim s) -> IOSim s a) + -> IOSim s a +withPeer NodeToNodeV_1 reader k = do + (local, remote) <- createConnectedChannels + let peer = outboundV1 60 (`div` 10) nullTracer 16 reader (pure Continue) + withAsync (runPeer nullTracer codecTxSubmission2Id local peer) $ \worker -> do + link worker + Just (AnyMessage V1.MsgInit) <- recv remote + k Requests { + requestIds = \blocking ack -> do + send remote (AnyMessage (V1.MsgRequestTxIds blocking (fromIntegral ack) 4)) + Just (AnyMessage (V1.MsgReplyTxIds ids)) <- recv remote + pure (map fst $ toList ids) + , requestBodies = \ids -> do + send remote (AnyMessage (V1.MsgRequestTxs ids)) + Just (AnyMessage (V1.MsgReplyTxs bodies)) <- recv remote + pure bodies + } +withPeer version reader k = do + (local, remote) <- createConnectedChannels + let peer = outboundV2 version 60 (`div` 10) nullTracer 16 reader + withAsync (runPeer nullTracer codecSigSubmissionV2Id local peer) $ \worker -> do + link worker + k Requests { + requestIds = \blocking ack -> do + send remote (AnyMessage (V2.MsgRequestSigIds blocking (fromIntegral ack) 4)) + recv remote >>= \case + Just (AnyMessage (V2.MsgReplySigIds ids)) -> pure (map fst $ toList ids) + Just (AnyMessage V2.MsgReplyNoSigIds) -> pure [] + _ -> fail "expected a signature ID reply" + , requestBodies = \ids -> do + send remote (AnyMessage (V2.MsgRequestSigs ids)) + Just (AnyMessage (V2.MsgReplySigs bodies)) <- recv remote + pure bodies + } diff --git a/dmq-node/test/Test/DMQ/SigSubmission/SigSpacing.hs b/dmq-node/test/Test/DMQ/SigSubmission/SigSpacing.hs new file mode 100644 index 00000000..8feae64b --- /dev/null +++ b/dmq-node/test/Test/DMQ/SigSubmission/SigSpacing.hs @@ -0,0 +1,215 @@ +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE NumericUnderscores #-} + +module Test.DMQ.SigSubmission.SigSpacing (tests) where + +import Control.Monad (foldM) + +import Data.Either (isRight) +import Data.List (sort) +import Data.Time.Clock.POSIX (POSIXTime) + +import DMQ.Protocol.SigSubmission.SigSpacing (SigSpacing) +import DMQ.Protocol.SigSubmission.SigSpacing qualified as SigSpacing + +import Test.QuickCheck +import Test.Tasty (TestTree, testGroup) +import Test.Tasty.QuickCheck (testProperty) + + +tests :: TestTree +tests = testGroup "DMQ.Protocol.SigSubmission.SigSpacing" + [ testProperty "model" prop_sigSpacing_model + , testProperty "any order" prop_sigSpacing_anyOrder + ] + + +-- | `sigExpiresAt` of signatures must be smaller than @now + maxDelay@. +-- +maxDelay :: Int +maxDelay = 1800 + +-- | An arbitrary starting time. +-- +startTime :: POSIXTime +startTime = 1_000_000 + + +-- | Number of values (per key) which are at least `minSigDelay` apart and +-- lie in an interval of length `maxDelay`. +-- +maxValues :: Int -> Int +maxValues minSigDelay = ceiling (fromIntegral maxDelay / fromIntegral minSigDelay :: Double) + + +-- | Conflicts of a value with values accepted by a model. +-- +modelConflicts :: POSIXTime + -- ^ `minSigDelay` + -> POSIXTime + -- ^ current time + -> [(Int, POSIXTime)] + -- ^ accepted keys and values + -> Int + -- ^ key + -> POSIXTime + -- ^ value + -> [POSIXTime] +modelConflicts delay now accepted key value = + [ value' + | (key', value') <- accepted + , key' == key + , value' > now - delay + , abs (value - value') < delay + ] + + +-- | An `SigSpacing.insert` operation: time elapsed since the previous operation +-- (in milliseconds), a key and `sigExpiresAt` offset since the current time +-- (in seconds). +-- +data InsertOp = InsertOp { + opElapsedMs :: Int, + opKey :: Int, + opOffset :: Int + } + deriving Show + +instance Arbitrary InsertOp where + arbitrary = + InsertOp <$> frequency [ (3, chooseInt (0, 1_000)) + , (2, chooseInt (0, 60_000)) + , (1, chooseInt (0, 300_000)) + ] + <*> chooseInt (0, 3) + <*> chooseInt (-120, maxDelay - 1) + + shrink op@InsertOp { opElapsedMs, opKey, opOffset } = + [ op { opElapsedMs = a } | a <- shrink opElapsedMs, a >= 0 ] + ++ [ op { opKey = a } | a <- shrink opKey, a >= 0 ] + ++ [ op { opOffset = a } | a <- shrink opOffset, a >= -120 ] + +-- | `minSigDelay` (in seconds) and a sequence of operations. +-- +data InsertOps = InsertOps Int [InsertOp] + deriving Show + +instance Arbitrary InsertOps where + arbitrary = InsertOps <$> chooseInt (1, 120) <*> arbitrary + shrink (InsertOps minSigDelay ops) = + [ InsertOps minSigDelay' ops | minSigDelay' <- shrink minSigDelay, minSigDelay' >= 1 ] + ++ [ InsertOps minSigDelay ops' | ops' <- shrink ops ] + + +-- | `SigSpacing.insert` agrees with a simple model: a value is rejected iff the +-- same key has an accepted value, larger than @now - minSigDelay@, closer +-- than @minSigDelay@. After each insert: +-- +-- * values of a key are at least @minSigDelay@ apart; +-- * values larger than @now - minSigDelay@ are the same as in the model, i.e. +-- no value which can still conflict is forgotten; +-- * the number of values of a key which have not expired is bounded by +-- @maxDelay / minSigDelay@. +-- +prop_sigSpacing_model :: InsertOps -> Property +prop_sigSpacing_model (InsertOps minSigDelay ops) = + let (props, conflicts) = go startTime SigSpacing.empty [] ops + in tabulate "conflicts" [bucket conflicts] + $ conjoin props + where + delay :: POSIXTime + delay = fromIntegral minSigDelay + + bucket :: Int -> String + bucket 0 = "0" + bucket n | n < 5 = "1-4" + | otherwise = ">=5" + + go :: POSIXTime + -> SigSpacing Int + -> [(Int, POSIXTime)] + -> [InsertOp] + -> ([Property], Int) + go _ _ _ [] = ([], 0) + go now0 spacing accepted (op@InsertOp { opElapsedMs, opKey, opOffset } : ops') = + case SigSpacing.insert (fromIntegral minSigDelay) now opKey value spacing of + Left conflict -> + let prop = counterexample (show op) + . counterexample ("unexpected conflict: " ++ show conflict) + $ conflict `elem` conflicts + (props, n) = go now spacing accepted ops' + in (prop : props, succ n) + Right spacing' -> + let accepted' = (opKey, value) : accepted + prop = counterexample (show op) + $ counterexample ("missed conflicts: " ++ show conflicts) + (null conflicts) + .&&. invariants spacing' accepted' + (props, n) = go now spacing' accepted' ops' + in (prop : props, n) + where + now :: POSIXTime + now = now0 + fromIntegral opElapsedMs / 1000 + + value :: POSIXTime + value = fromIntegral (floor now :: Integer) + fromIntegral opOffset + + conflicts = modelConflicts delay now accepted opKey value + + invariants :: SigSpacing Int -> [(Int, POSIXTime)] -> Property + invariants spacing' accepted' = + counterexample "live values differ from the model" + (filter isLive recorded === sort (filter isLive accepted')) + .&&. conjoin + [ counterexample ("key " ++ show key ++ ": " ++ show values) $ + counterexample "values not spaced" + (and (zipWith (\a b -> b - a >= delay) values (drop 1 values))) + .&&. counterexample "too many values which have not expired" + (length (filter (>= now) values) <= maxValues minSigDelay) + | (key, values) <- valuesByKey + ] + where + valuesByKey = SigSpacing.toList spacing' + recorded = [ (key, v) | (key, values) <- valuesByKey, v <- values ] + isLive (_, v) = v > now - delay + + +-- | Keys with values (`sigExpiresAt` offsets since `startTime`), which are at +-- least `minSigDelay` apart for each key, in an arbitrary order. +-- +data SpacedValues = SpacedValues Int [(Int, Int)] + deriving Show + +instance Arbitrary SpacedValues where + arbitrary = do + minSigDelay <- chooseInt (1, 120) + keys <- chooseInt (1, 4) + values <- concat <$> traverse + (\key -> do + start <- chooseInt (0, minSigDelay - 1) + gaps <- listOf (chooseInt (minSigDelay, 3 * minSigDelay)) + return [ (key, offset) + | offset <- takeWhile (< maxDelay) (scanl (+) start gaps) + ]) + [1 .. keys] + SpacedValues minSigDelay <$> shuffle values + + -- removing values preserves spacing + shrink (SpacedValues minSigDelay values) = + SpacedValues minSigDelay <$> shrinkList (const []) values + + +-- | Starting from `SigSpacing.empty`, values at least @minSigDelay@ apart for +-- each key pass the spacing check in any insertion order. +-- +prop_sigSpacing_anyOrder :: SpacedValues -> Property +prop_sigSpacing_anyOrder (SpacedValues minSigDelay values) = + counterexample "rejected" (isRight (insertAll values)) + .&&. counterexample "rejected in reverse order" (isRight (insertAll (reverse values))) + where + insertAll :: [(Int, Int)] -> Either POSIXTime (SigSpacing Int) + insertAll = + foldM (\spacing (key, offset) -> + SigSpacing.insert (fromIntegral minSigDelay) startTime key + (startTime + fromIntegral offset) spacing) + SigSpacing.empty