diff --git a/README.md b/README.md index 56ca0f7..572b701 100644 --- a/README.md +++ b/README.md @@ -149,14 +149,71 @@ The `Prometheus` requires a different port number than `cardano-node`'s } ``` -By default all counters are prefixed with `dmq_node_`, this can be changed with -`TraceOptionMetricsPrefix` option in the configuration file, e.g. +DMQ metrics use the prefix `dmq_node_` by default. To change it, set +`TraceOptionMetricsPrefix` in the configuration file, e.g. ```json { "TraceOptionMetricsPrefix": "dmq_aggregator." } ``` +### NixOS + +The flake exports `nixosModules.dmq-node`, which configures +`services.dmq-node`. It reads the Shelley genesis and the cardano network magic +from the attached node's flat configuration. dmq-node connects to the node +socket through the node's group, so that socket must be group-writable; the +example uses socket activation for this, and the `cardanoNodeSocketGroup` +option lists the alternatives. In a flake's `nixosSystem`: + +```nix +nixpkgs.lib.nixosSystem { + modules = [ + inputs.dmq-node.nixosModules.dmq-node + ({ config, ... }: { + services.cardano-node.systemdSocketActivation = true; + services.dmq-node = { + enable = true; + networkMagic = 2912307721; + cardanoNodeConfig = config.services.cardano-node.nodeConfig; + cardanoNodeSocketPath = config.services.cardano-node.socketPath 0; + hostAddr = "0.0.0.0"; + openFirewall = true; + topology = { localRoots = [ ]; publicRoots = [ ]; useLedgerAfterSlot = -1; }; + traceOptions."" = { + backends = [ "Stdout MachineFormat" "PrometheusSimple suffix 127.0.0.1 12800" ]; + severity = "Info"; + }; + }; + }) + ]; +} +``` + +With this configuration, a Prometheus instance on the same host can scrape +`127.0.0.1:12800` at its default path, `/metrics`. To inspect it directly: + +```sh +curl -fsS http://127.0.0.1:12800/metrics +``` + +`dmq_node_peerSelection_ActivePeers_int` reports the current active peer count. +For messages received from peers, look for `dmq_node_txSubmission_txsReceived_int`, +`dmq_node_txSubmission_txsAccepted_int` and `dmq_node_txSubmission_txsRejected_int`. +The V2 submission worker checks for changed totals every seven seconds, so these +series can be absent from an early scrape. The NixOS service enables GHC runtime +statistics with `+RTS -T -RTS`, including `rts_gc_bytes_allocated` and +`rts_gc_num_gcs`. + +`nix/nixos/dmq-node-service.nix` holds the module with no reference to this +flake, so it can be imported by path. There `package` defaults to +`pkgs.dmq-node`, which `overlays.default` adds; set `package` instead to pin +another build. The VM test runs with: + +```bash +> nix build .#checks.x86_64-linux.nixos-dmq-node +``` + ## Developing with Nix To enter a development shell with all dependencies available, use: diff --git a/dmq-node/changelog.d/20261112_210000_michael_dmq_client.md b/dmq-node/changelog.d/20261112_210000_michael_dmq_client.md new file mode 100644 index 0000000..205f070 --- /dev/null +++ b/dmq-node/changelog.d/20261112_210000_michael_dmq_client.md @@ -0,0 +1,20 @@ + + + +### Non-Breaking + +- Added `dmq-client`, a node-to-client client: `submit` signs a message with + a pool's KES key and submits it, `notify` prints received messages. +- `DMQ.NodeToClient` exports `localMsgSubmissionMiniProtocolNum`, + `localMsgNotificationMiniProtocolNum` and `localMiniProtocolLimits`; + `DMQ.Protocol.SigSubmission.Codec` exports `encodeSigPayload`. diff --git a/dmq-node/client/Main.hs b/dmq-node/client/Main.hs new file mode 100644 index 0000000..5747261 --- /dev/null +++ b/dmq-node/client/Main.hs @@ -0,0 +1,303 @@ +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DisambiguateRecordFields #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE PackageImports #-} +{-# LANGUAGE RankNTypes #-} +{-# LANGUAGE TypeApplications #-} + +-- | Client for a dmq-node's node-to-client socket. +-- +-- `submit` signs a message with a pool's KES key and submits it through +-- LocalMsgSubmission; `notify` reads messages through LocalMsgNotification. +-- +-- The message is written from the CDDL (`cddl/specs/sig.cddl`) field by +-- field, and the `Sig` that is submitted is the library's decoding of those +-- bytes, so it never serialises a `SigRaw`. +module Main (main) where + +import Codec.CBOR.Decoding qualified as CBOR +import Codec.CBOR.Encoding qualified as CBOR +import Codec.CBOR.Write qualified as CBOR +import Control.DeepSeq (NFData) +import Control.Exception (throwIO) +import Control.Monad (unless) +import "contra-tracer" Control.Tracer (nullTracer) +import Data.Aeson ((.:), (.=)) +import Data.Aeson qualified as Aeson +import Data.ByteString qualified as BS +import Data.ByteString.Base16 qualified as Base16 +import Data.ByteString.Char8 qualified as BS.Char8 +import Data.ByteString.Lazy qualified as LBS +import Data.ByteString.Lazy.Char8 qualified as LBS.Char8 +import Data.Foldable (for_) +import Data.List.NonEmpty qualified as NonEmpty +import Data.Text (Text) +import Data.Text.Encoding qualified as Text +import Data.Void (Void, absurd) +import Data.Word (Word32) +import Options.Applicative +import System.Exit (die) +import System.IO (hFlush, stdout) +import System.IOManager (withIOManager) + +import Cardano.Binary (decodeFullDecoder) +import Cardano.Binary.FixedSizeCodec (decodeFixedSized, encodeFixedSized) +import Cardano.Crypto.DSIGN.Class (VerKeyDSIGN) +import Cardano.Crypto.Hash.Class (castHash, hashToBytesAsHex, hashWith) +import Cardano.Crypto.KES.Class (SignKeyKES, SignKeyWithPeriodKES (..), + forgetSignKeyKES, rawDeserialiseSignKeyKES, signKES) +import Cardano.Crypto.Libsodium (sodiumInit) +import Cardano.KESAgent.KES.Crypto (Crypto (..)) +import Cardano.KESAgent.KES.Evolution (updateKESTo) +import Cardano.KESAgent.KES.OCert (OCert (..)) +import Cardano.KESAgent.Protocols.StandardCrypto (StandardCrypto) + +import Network.Mux qualified as Mx + +import Ouroboros.Network.ConnectionManager.Types (DataFlow (..)) +import Ouroboros.Network.Driver.Simple (runAnnotatedPeer) +import Ouroboros.Network.Magic (NetworkMagic (..)) +import Ouroboros.Network.Mux qualified as Mx +import Ouroboros.Network.Protocol.Handshake (HandshakeArguments (..)) +import Ouroboros.Network.Protocol.Handshake.Version (simpleSingletonVersions) +import Ouroboros.Network.Protocol.LocalTxSubmission.Client qualified as Submission +import Ouroboros.Network.Protocol.LocalTxSubmission.Type (SubmitResult (..)) +import Ouroboros.Network.Snocket (localAddressFromPath, localSnocket, + makeLocalBearer) +import Ouroboros.Network.Socket (ConnectToArgs (..), HandshakeCallbacks (..), + connectToNode, nullNetworkConnectTracers) + +import DMQ.NodeToClient (localMsgNotificationMiniProtocolNum, + localMsgSubmissionMiniProtocolNum, ntcHandshakeArguments) +import DMQ.NodeToClient.Version (NodeToClientVersion (..), stdVersionDataNTC) +import DMQ.Policy qualified as Policy +import DMQ.Protocol.LocalMsgNotification.Client qualified as Notification +import DMQ.Protocol.LocalMsgNotification.Codec (codecLocalMsgNotification) +import DMQ.Protocol.LocalMsgSubmission.Client +import DMQ.Protocol.LocalMsgSubmission.Codec (codecLocalMsgSubmission) +import DMQ.Protocol.SigSubmission.Codec (decodeSig, decodeSigOpCertificate, + encodeSigId, encodeSigOpCertificate, encodeSigPayload) +import DMQ.Protocol.SigSubmission.Type + +type C = StandardCrypto + +-- | The dmq-node to talk to, and what to do there. +data Command = Command + { socketPath :: FilePath + , networkMagic :: NetworkMagic + , task :: Task + } + +data Task = Submit SubmitArgs | Notify Positive + +data SubmitArgs = SubmitArgs + { kesSigningKey :: FilePath + , opCert :: FilePath + , kesPeriod :: KESPeriod + , expiresAt :: Word32 + , body :: FilePath + } + +-- | Constructed only by the `positive` reader. +newtype Positive = Positive Int + +main :: IO () +main = do + -- KES signing keys live in libsodium's mlocked memory. + sodiumInit + Command { socketPath, networkMagic, task } <- + execParser (info (commandParser <**> helper) fullDesc) + case task of + Submit args -> submit socketPath networkMagic args + Notify n -> notify socketPath networkMagic n + +-- | The node options follow the subcommand: `dmq-client submit --socket …`. +commandParser :: Parser Command +commandParser = hsubparser + ( command "submit" (info (withNode (Submit <$> submitParser)) + (progDesc "Sign a message with a pool's KES key and submit it")) + <> command "notify" (info (withNode (Notify <$> option positive (long "count" <> metavar "N"))) + (progDesc "Print messages as JSON lines: {\"id\", \"bytes\"}")) + ) + where + withNode taskParser = Command + <$> strOption (long "socket" <> metavar "PATH") + <*> (NetworkMagic <$> option auto (long "network-magic" <> metavar "WORD32")) + <*> taskParser + + submitParser = SubmitArgs + <$> strOption (long "kes-signing-key" <> metavar "PATH") + <*> strOption (long "op-cert" <> metavar "PATH") + <*> (KESPeriod <$> option auto (long "kes-period" <> metavar "WORD")) + <*> option auto (long "expires-at" <> metavar "POSIX_SECONDS") + <*> strOption (long "body" <> metavar "PATH") + + positive = auto >>= \n -> + if n >= 1 then pure (Positive n) + else readerError ("--count must be at least 1, got " <> show n) + +failWith :: String -> IO a +failWith = die . ("dmq-client: " <>) + +-- +-- submit +-- + +submit :: FilePath -> NetworkMagic -> SubmitArgs -> IO () +submit socketPath networkMagic args = do + (ocert, coldKey) <- readOpCert (opCert args) + kesKey <- readKESSigningKey (kesSigningKey args) + msgBody <- BS.readFile (body args) + + let KESPeriod start = ocertKESPeriod ocert + KESPeriod current = kesPeriod args + unless (current >= start) $ + failWith ("--kes-period " <> show current <> " is before the op cert's start period " <> show start) + SignKeyWithPeriodKES evolvedKey evolution <- + maybe (failWith ("the KES key cannot evolve to period " <> show current)) pure + =<< updateKESTo () (kesPeriod args) ocert (SignKeyWithPeriodKES kesKey 0) + + let signedBytes = CBOR.toStrictByteString $ + encodeSigPayload (SigBody msgBody) (kesPeriod args) (fromIntegral (expiresAt args)) + msgId = SigId (castHash (hashWith id signedBytes)) + kesSig <- signKES () evolution signedBytes evolvedKey + forgetSignKeyKES evolvedKey + + let wireBytes = CBOR.toLazyByteString $ + CBOR.encodeListLen 5 + <> encodeSigId msgId + <> CBOR.encodePreEncoded signedBytes + <> encodeFixedSized kesSig + <> encodeSigOpCertificate (SigOpCertificate ocert) + <> encodeFixedSized coldKey + sig <- either (\err -> failWith ("decoding the message we built: " <> show err)) pure + (decodeMessage wireBytes) + + result <- connect socketPath networkMagic localMsgSubmissionMiniProtocolNum $ \channel -> + runAnnotatedPeer nullTracer (codecLocalMsgSubmission @C) channel + (localMsgSubmissionClientPeer + (Submission.LocalTxSubmissionClient + (pure (Submission.SendMsgSubmitTx sig (pure . Submission.SendMsgDone . rejection))))) + case result of + Nothing -> BS.Char8.putStrLn (hashToBytesAsHex (getSigId (sigId sig))) + Just err -> failWith ("rejected: " <> err) + where + -- `SigValidationError` has no `NFData`, which the driver needs for the result. + rejection :: SubmitResult SigValidationError -> Maybe String + rejection SubmitSuccess = Nothing + rejection (SubmitFail err) = Just (show err) + + decodeMessage bytes = + (\withBytes -> SigWithBytes bytes (withBytes bytes)) + <$> decodeFullDecoder "Sig" (decodeSig @C) bytes + +-- +-- notify +-- + +notify :: FilePath -> NetworkMagic -> Positive -> IO () +notify socketPath networkMagic (Positive n) = + connect socketPath networkMagic localMsgNotificationMiniProtocolNum $ \channel -> + runAnnotatedPeer nullTracer (codecLocalMsgNotification @C) channel + (Notification.localMsgNotificationClientPeer + (Notification.LocalMsgNotificationClient (pure (request n)))) + where + request remaining = Notification.SendMsgRequestBlocking $ \msgs _hasMore -> do + let printed = take remaining (NonEmpty.toList msgs) + for_ printed $ \sig -> + LBS.Char8.putStrLn . Aeson.encode $ Aeson.object + [ "id" .= sigId sig + , "bytes" .= Text.decodeUtf8 (Base16.encode (LBS.toStrict (sigBytes sig))) + ] + hFlush stdout + let remaining' = remaining - length printed + pure $ if remaining' == 0 then Notification.SendMsgDone (pure ()) else request remaining' + +-- +-- shared +-- + +-- | Run one initiator mini-protocol over a node-to-client connection, with +-- the same handshake as dmq-node's own node-to-client server. +connect :: NFData a + => FilePath + -> NetworkMagic + -> Mx.MiniProtocolNum + -> (Mx.Channel IO LBS.ByteString -> IO (a, Maybe LBS.ByteString)) + -> IO a +connect path magic protocolNum run = withIOManager $ \iocp -> do + result <- connectToNode + (localSnocket iocp) + makeLocalBearer + ConnectToArgs + { ctaHandshakeCodec = haHandshakeCodec + , ctaHandshakeTimeLimits = haTimeLimits + , ctaVersionDataCodec = haVersionDataCodec + , ctaConnectTracers = nullNetworkConnectTracers + , ctaHandshakeCallbacks = HandshakeCallbacks haAcceptVersion haQueryVersion + } + (\_ -> pure ()) + (simpleSingletonVersions NodeToClientV_1 (stdVersionDataNTC magic) $ \_ -> + Mx.OuroborosApplication + [ Mx.MiniProtocol + { Mx.miniProtocolNum = protocolNum + , Mx.miniProtocolStart = Mx.StartEagerly + , Mx.miniProtocolLimits = Policy.localProtocolLimits + , Mx.miniProtocolRun = Mx.InitiatorProtocolOnly (Mx.MiniProtocolCb (\_ctx -> run)) + } + ]) + (const Unidirectional) + Nothing + (localAddressFromPath path) + case result of + Left err -> throwIO err + Right (Left a) -> pure a + Right (Right v) -> absurd (v :: Void) + where + HandshakeArguments { haHandshakeCodec, haTimeLimits, haVersionDataCodec, + haAcceptVersion, haQueryVersion } = + ntcHandshakeArguments nullTracer + +-- +-- cardano-cli text envelopes +-- + +data TextEnvelope = TextEnvelope { envelopeType :: Text, cborHex :: Text } + +instance Aeson.FromJSON TextEnvelope where + parseJSON = Aeson.withObject "TextEnvelope" $ \o -> + TextEnvelope <$> o .: "type" <*> o .: "cborHex" + +readEnvelope :: Text -> FilePath -> IO BS.ByteString +readEnvelope expected path = do + TextEnvelope { envelopeType, cborHex } <- + either (\err -> failWith (path <> ": " <> err)) pure + =<< Aeson.eitherDecodeFileStrict path + unless (envelopeType == expected) $ + failWith (path <> ": expected type " <> show expected <> ", got " <> show envelopeType) + either (\err -> failWith (path <> ": cborHex: " <> err)) pure + (Base16.decode (Text.encodeUtf8 cborHex)) + +decodeEnvelope :: FilePath -> (forall s. CBOR.Decoder s a) -> BS.ByteString -> IO a +decodeEnvelope path decoder bytes = + either (\err -> failWith (path <> ": " <> show err)) pure + (decodeFullDecoder "cborHex" decoder (LBS.fromStrict bytes)) + +readKESSigningKey :: FilePath -> IO (SignKeyKES (KES C)) +readKESSigningKey path = do + raw <- decodeEnvelope path CBOR.decodeBytes + =<< readEnvelope "KesSigningKey_ed25519_kes_2^6" path + maybe (failWith (path <> ": not a Sum6KES signing key")) pure + =<< rawDeserialiseSignKeyKES raw + +-- | A cardano-cli op cert is `[ocert, cold verification key]`. +readOpCert :: FilePath -> IO (OCert C, VerKeyDSIGN (DSIGN C)) +readOpCert path = + decodeEnvelope path decoder =<< readEnvelope "NodeOperationalCertificate" path + where + decoder :: CBOR.Decoder s (OCert C, VerKeyDSIGN (DSIGN C)) + decoder = do + CBOR.decodeListLenOf 2 + SigOpCertificate ocert <- decodeSigOpCertificate + coldKey <- decodeFixedSized + pure (ocert, coldKey) diff --git a/dmq-node/dmq-node.cabal b/dmq-node/dmq-node.cabal index 466748c..7218140 100644 --- a/dmq-node/dmq-node.cabal +++ b/dmq-node/dmq-node.cabal @@ -184,6 +184,37 @@ executable dmq-node hs-source-dirs: app default-language: Haskell2010 +executable dmq-client + import: + warnings, + extensions + + main-is: Main.hs + ghc-options: + -threaded + -rtsopts + + build-depends: + Win32-network, + aeson, + base, + base16-bytestring, + bytestring, + cardano-binary, + cardano-crypto-class, + cborg, + contra-tracer, + deepseq, + dmq-node, + kes-agent:crypto, + network-mux, + optparse-applicative, + ouroboros-network:{api, framework, protocols}, + text, + + hs-source-dirs: client + default-language: Haskell2010 + test-suite dmq-tests import: warnings, diff --git a/dmq-node/src/DMQ/NodeToClient.hs b/dmq-node/src/DMQ/NodeToClient.hs index 4c886d0..2fae5ba 100644 --- a/dmq-node/src/DMQ/NodeToClient.hs +++ b/dmq-node/src/DMQ/NodeToClient.hs @@ -11,6 +11,8 @@ module DMQ.NodeToClient , ntcApps , ntcHandshakeArguments , responders + , localMsgSubmissionMiniProtocolNum + , localMsgNotificationMiniProtocolNum ) where import Data.ByteString.Lazy (ByteString) @@ -224,6 +226,12 @@ responders Apps { -- shared implementation of tools that can analyse both protocols, e.g. -- wireshark plugins. -- +localMsgSubmissionMiniProtocolNum :: MiniProtocolNum +localMsgSubmissionMiniProtocolNum = MiniProtocolNum 14 + +localMsgNotificationMiniProtocolNum :: MiniProtocolNum +localMsgNotificationMiniProtocolNum = MiniProtocolNum 15 + nodeToClientProtocols :: Protocols appType ntcAddr bytes m a b -> NodeToClientVersion @@ -241,13 +249,13 @@ nodeToClientProtocols protocols _version _versionData = ] where localMsgSubmission protocol = MiniProtocol { - miniProtocolNum = MiniProtocolNum 14, + miniProtocolNum = localMsgSubmissionMiniProtocolNum, miniProtocolStart = StartOnDemand, miniProtocolLimits = Policy.localProtocolLimits, miniProtocolRun = protocol } localMsgNotification protocol = MiniProtocol { - miniProtocolNum = MiniProtocolNum 15, + miniProtocolNum = localMsgNotificationMiniProtocolNum, miniProtocolStart = StartOnDemand, miniProtocolLimits = Policy.localProtocolLimits, miniProtocolRun = protocol diff --git a/dmq-node/src/DMQ/Protocol/SigSubmission/Codec.hs b/dmq-node/src/DMQ/Protocol/SigSubmission/Codec.hs index bbe8743..81f8496 100644 --- a/dmq-node/src/DMQ/Protocol/SigSubmission/Codec.hs +++ b/dmq-node/src/DMQ/Protocol/SigSubmission/Codec.hs @@ -18,6 +18,7 @@ module DMQ.Protocol.SigSubmission.Codec , decodeSigId , encodeSigOpCertificate , decodeSigOpCertificate + , encodeSigPayload ) where import Control.Monad (when) @@ -157,6 +158,15 @@ codecSigSubmission = encodeSig :: Sig crypto -> CBOR.Encoding encodeSig = Utils.encodeBytes . sigRawBytes +-- | The part of a message the KES key signs, `[body, kesPeriod, expiresAt]`; +-- `decodeSig` reads it back. +encodeSigPayload :: SigBody -> KESPeriod -> POSIXTime -> CBOR.Encoding +encodeSigPayload (SigBody body) (KESPeriod kesPeriod) expiresAt = + CBOR.encodeListLen 3 + <> CBOR.encodeBytes body + <> CBOR.encodeWord kesPeriod + <> CBOR.encodeWord32 (floor expiresAt) + decodeSig :: forall crypto s. ( Crypto crypto ) diff --git a/dmq-node/test/DMQ/Protocol/SigSubmission/Test.hs b/dmq-node/test/DMQ/Protocol/SigSubmission/Test.hs index fd84107..7f2441e 100644 --- a/dmq-node/test/DMQ/Protocol/SigSubmission/Test.hs +++ b/dmq-node/test/DMQ/Protocol/SigSubmission/Test.hs @@ -398,7 +398,7 @@ instance ( Crypto crypto sigRawExpiresAt, sigRawKESSignature = undefined -- to be filled below } - signedBytes = CBOR.toStrictByteString (encodeSigPayload sigRaw) + signedBytes = CBOR.toStrictByteString (sigRawPayload sigRaw) -- evolve the key to the target period mbSnKESKey <- KES.updateKESTo () sigRawKESPeriod ocert (KES.SignKeyWithPeriodKES snKESKey 0) @@ -475,7 +475,7 @@ shrinkSigRawWithSignedBytesFn SigRawWithSignedBytes { sigRaw } = [ SigRawWithSignedBytes { sigRaw = sigRaw', sigRawSignedBytes = sigRawSignedBytes' } | sigRaw' <- shrinkSigRawFn sigRaw - , let sigRawSignedBytes' = CBOR.toLazyByteString (encodeSigPayload sigRaw') + , let sigRawSignedBytes' = CBOR.toLazyByteString (sigRawPayload sigRaw') ] @@ -522,16 +522,9 @@ mkSig sigRawWithSignedBytes@SigRawWithSignedBytes { sigRaw } = -- encode the payload -encodeSigPayload :: SigRaw crypto -> CBOR.Encoding -encodeSigPayload SigRaw { - sigRawBody, - sigRawKESPeriod, - sigRawExpiresAt - } - = CBOR.encodeListLen 3 - <> CBOR.encodeBytes (getSigBody sigRawBody) - <> CBOR.encodeWord (unKESPeriod sigRawKESPeriod) - <> CBOR.encodeWord32 (floor sigRawExpiresAt) +sigRawPayload :: SigRaw crypto -> CBOR.Encoding +sigRawPayload SigRaw { sigRawBody, sigRawKESPeriod, sigRawExpiresAt } = + encodeSigPayload sigRawBody sigRawKESPeriod sigRawExpiresAt -- encode together with KES signature, OCert and cold key. encodeSigRaw :: Crypto crypto @@ -540,7 +533,7 @@ encodeSigRaw :: Crypto crypto encodeSigRaw sigRaw@SigRaw { sigRawId, sigRawKESSignature, sigRawOpCertificate, sigRawColdKey } = CBOR.encodeListLen 5 <> encodeSigId sigRawId - <> encodeSigPayload sigRaw + <> sigRawPayload sigRaw <> encodeFixedSized (getSigKESSignature sigRawKESSignature) <> encodeSigOpCertificate sigRawOpCertificate <> encodeFixedSized (getSigColdKey sigRawColdKey) diff --git a/flake.nix b/flake.nix index 32ff692..7c51fed 100644 --- a/flake.nix +++ b/flake.nix @@ -41,7 +41,23 @@ flake-utils.url = "github:numtide/flake-utils"; }; - outputs = inputs: inputs.flake-utils.lib.eachDefaultSystem (system: - import ./nix/outputs.nix { inherit inputs system; } - ); + outputs = inputs: inputs.flake-utils.lib.eachDefaultSystem + (system: + import ./nix/outputs.nix { inherit inputs system; } + ) // { + overlays.default = final: _prev: { + inherit (inputs.self.packages.${final.stdenv.hostPlatform.system}) dmq-node; + }; + + # Defaults `package` directly rather than adding the overlay: NixOS rejects + # `nixpkgs.overlays` when `nixpkgs.pkgs` is set from outside. + nixosModules = rec { + dmq-node = { lib, pkgs, ... }: { + imports = [ ./nix/nixos/dmq-node-service.nix ]; + services.dmq-node.package = lib.mkDefault + inputs.self.packages.${pkgs.stdenv.hostPlatform.system}.dmq-node; + }; + default = dmq-node; + }; + }; } diff --git a/nix/nixos/dmq-node-service.nix b/nix/nixos/dmq-node-service.nix new file mode 100644 index 0000000..c6d414d --- /dev/null +++ b/nix/nixos/dmq-node-service.nix @@ -0,0 +1,349 @@ +# NixOS service module for dmq-node. +# +# Self-contained: it references nothing from this flake, so it can be imported +# by path. +{ config, lib, pkgs, ... }: + +let + inherit (lib) mkEnableOption mkIf mkOption mkPackageOption types; + + cfg = config.services.dmq-node; + json = pkgs.formats.json { }; + # json.type also accepts a path, which json.generate writes as a string. + jsonObject = types.attrsOf json.type; + + # The unit's only writable path under ProtectSystem = "strict". + runtimeDirectory = "dmq-node"; + + # User and group the module creates, and only while they are the defaults. + defaultAccount = "dmq-node"; + + requiredNodeConfigKey = key: + cfg.cardanoNodeConfig.${key} or (throw + "services.dmq-node.cardanoNodeConfig has no `${key}`; it must be a flat cardano-node config, such as services.cardano-node.nodeConfig or cardanoLib.environments..nodeConfig"); + + # cardano-node resolves a relative genesis path against its config file, + # whose location an attrset no longer carries. + shelleyGenesisFile = + let file = requiredNodeConfigKey "ShelleyGenesisFile"; + in + if types.path.check file then file + else + throw + "services.dmq-node.cardanoNodeConfig.ShelleyGenesisFile must be an absolute path, got `${file}`; override it, e.g. `// { ShelleyGenesisFile = ./${file}; }`"; + shelleyGenesis = builtins.fromJSON (builtins.readFile shelleyGenesisFile); + + generatedSettings = { + NetworkMagic = cfg.networkMagic; + CardanoNetworkMagic = shelleyGenesis.networkMagic; + ShelleyGenesisFile = "${shelleyGenesisFile}"; + # Optional for cardano-node and dmq-node alike: without it, neither + # verifies the genesis file. + ShelleyGenesisHash = cfg.cardanoNodeConfig.ShelleyGenesisHash or null; + IPv4 = cfg.hostAddr; + IPv6 = cfg.ipv6HostAddr; + PortNumber = cfg.port; + LocalAddress = cfg.socketPath; + CardanoNodeSocket = cfg.cardanoNodeSocketPath; + TraceOptions = cfg.traceOptions; + }; + + # Sandbox settings the unit enables, with the directories each one hides. + sandboxHides = { + PrivateTmp = [ "/tmp/" "/var/tmp/" ]; + ProtectHome = [ "/home/" "/root/" "/run/user/" ]; + }; + hiddenSocketDirs = lib.filter + (dir: lib.hasPrefix dir cfg.cardanoNodeSocketPath) + (lib.concatLists (lib.attrValues sandboxHides)); + + # Ports below 1024 need the capability under the kernel's default + # ip_unprivileged_port_start. A string, not a list: NixOS writes no line for + # an empty list, while an empty assignment is systemd's empty set. + capabilities = lib.optionalString (cfg.port < 1024) "CAP_NET_BIND_SERVICE"; + + duplicatedKeys = lib.intersectLists + (lib.attrNames generatedSettings) + (lib.attrNames cfg.extraSettings); + + configFile = json.generate "dmq-node-config.json" + (lib.filterAttrs (_: v: v != null) generatedSettings // cfg.extraSettings); + + topologyFile = json.generate "dmq-node-topology.json" cfg.topology; + + # dmq-node exits when it cannot reach cardano-node, which only listens once + # its ledger replay is done (hours on mainnet). Waiting here, as the main + # process, keeps the unit active and out of systemd's start limits. + # Connecting, not just testing for the file: a stopped node leaves its socket + # file behind. Connecting needs write permission, which no wait grants, so a + # socket we cannot write fails the start instead. + dmqNode = pkgs.writeShellApplication { + name = "dmq-node-when-cardano-node-listens"; + runtimeInputs = [ pkgs.socat ]; + text = '' + socket=${lib.escapeShellArg cfg.cardanoNodeSocketPath} + connect() { + if [ -S "$socket" ] && [ ! -w "$socket" ]; then + echo "$socket is not writable by group ${cfg.cardanoNodeSocketGroup}; see services.dmq-node.cardanoNodeSocketGroup" >&2 + exit 1 + fi + socat -u /dev/null "UNIX-CONNECT:$socket" 2>/dev/null + } + if ! connect; then + echo "Waiting for cardano-node to listen on $socket ..." + until connect; do + sleep 5 + done + fi + exec ${lib.escapeShellArgs [ + (lib.getExe' cfg.package "dmq-node") + "--configuration-file" + configFile + "--topology-file" + topologyFile + "+RTS" + "-T" + "-RTS" + ]} + ''; + }; +in +{ + options.services.dmq-node = { + enable = mkEnableOption "the DMQ node"; + + package = mkPackageOption pkgs "dmq-node" { }; + + networkMagic = mkOption { + type = types.ints.u32; + description = "Network magic of the DMQ network (CIP-137); mainnet is 2912307721."; + }; + + cardanoNodeConfig = mkOption { + type = types.attrs; + example = lib.literalExpression "config.services.cardano-node.nodeConfig"; + description = '' + The flat cardano-node configuration of the node this DMQ node attaches + to. `ShelleyGenesisFile` and, if present, `ShelleyGenesisHash` are read + from it, and the cardano network magic is read from that genesis file. + + cardano-node keeps this attrset flat under both `configFormat` dialects + and envelopes it only when writing its config file. + + `services.cardano-node.nodeConfig` is the base configuration only. If + the node overrides its genesis through `extraNodeConfig` or + `extraNodeInstanceConfig`, pass the merged attrset instead: + `lib.recursiveUpdate (lib.recursiveUpdate nodeConfig extraNodeConfig) (extraNodeInstanceConfig 0)`. + A `nodeConfigFile` replaces all three. + ''; + }; + + cardanoNodeSocketPath = mkOption { + type = types.str; + example = lib.literalExpression "config.services.cardano-node.socketPath 0"; + description = '' + Node-to-client socket of the cardano-node. The service waits until + cardano-node accepts connections on it before starting dmq-node, + which exits when that connection fails. + ''; + }; + + cardanoNodeSocketGroup = mkOption { + type = types.str; + default = "cardano-node"; + description = '' + Group owning the cardano-node socket; the service joins it as a + supplementary group to connect. The default is the group that + cardano-node's NixOS module runs as, so its socket has that group. + + Connecting needs the socket to be group-writable, which it is not by + default (mode 0755). Make it so on the cardano-node side with one of: + - `services.cardano-node.systemdSocketActivation = true` + (socket mode 0660 with `services.cardano-node.socketGroup`); + - `services.cardano-node.shareNodeSocket = true` under cardano-parts; + - `systemd.services.cardano-node.serviceConfig.UMask = "0007"`. + + The service fails to start while the socket is not writable. + ''; + }; + + hostAddr = mkOption { + type = types.nullOr types.str; + default = null; + example = "0.0.0.0"; + description = "IPv4 address to bind node-to-node connections to."; + }; + + ipv6HostAddr = mkOption { + type = types.nullOr types.str; + default = null; + example = "::"; + description = "IPv6 address to bind node-to-node connections to."; + }; + + port = mkOption { + type = types.port; + default = 3141; + description = "Node-to-node TCP port."; + }; + + socketPath = mkOption { + type = types.str; + readOnly = true; + default = "/run/${runtimeDirectory}/dmq-node.socket"; + description = '' + Node-to-client socket that DMQ clients connect to. Fixed inside the + service's runtime directory, the only path the unit may write. + ''; + }; + + topology = mkOption { + type = jsonObject; + example = { + localRoots = [{ + accessPoints = [{ address = "dmq.example.org"; port = 3141; }]; + advertise = false; + trustable = true; + valency = 1; + }]; + publicRoots = [ ]; + useLedgerAfterSlot = -1; + }; + description = '' + Peers to connect to, in cardano-node's topology syntax: + . + To use a topology file, pass `lib.importJSON ./topology.json`. + + The access points are other dmq-nodes (port 3141 by default), not + cardano-nodes. `bootstrapPeers` and `peerSnapshotFile` are not + supported. Ledger peers additionally need `LedgerPeers = true` in + `extraSettings` and SRV relay records (CIP-155); see the dmq-node + README. + ''; + }; + + traceOptions = mkOption { + type = jsonObject; + example = { + "" = { + backends = [ "Stdout MachineFormat" "PrometheusSimple suffix 127.0.0.1 12800" ]; + severity = "Info"; + }; + "Net.PeerSelection" = { severity = "Debug"; }; + }; + description = '' + trace-dispatcher `TraceOptions`: per trace namespace, its `severity`, + `detail`, `maxFrequency` and `backends`. The `""` namespace sets the + defaults the others refine. See the Configuration section of + . + + dmq-node requires this option. The example serves DMQ metrics + (`dmq_node_*`) and GHC runtime statistics (`rts_gc_*`) at + `http://127.0.0.1:12800/metrics`. + ''; + }; + + user = mkOption { + type = types.str; + default = defaultAccount; + description = '' + User the service runs as. The module creates it only under the + default name; another name must be an existing account. + ''; + }; + + group = mkOption { + type = types.str; + default = defaultAccount; + description = '' + Group the service runs as. Its members get access to the + node-to-client socket. The module creates it only under the default + name. + ''; + }; + + openFirewall = mkOption { + type = types.bool; + default = false; + description = "Open `port` in the firewall."; + }; + + extraSettings = mkOption { + type = jsonObject; + default = { }; + example = { LedgerPeers = true; PeerSharing = false; }; + description = '' + Further keys of the dmq-node configuration file. Keys that the options + above already set are rejected. + ''; + }; + }; + + config = mkIf cfg.enable { + assertions = [ + { + assertion = cfg.hostAddr != null || cfg.ipv6HostAddr != null; + message = "services.dmq-node: set hostAddr, ipv6HostAddr or both."; + } + { + assertion = hiddenSocketDirs == [ ]; + message = "services.dmq-node.cardanoNodeSocketPath is under ${toString hiddenSocketDirs}, which the service's sandbox hides; move the cardano-node socket, e.g. to /run/cardano-node/node.socket."; + } + { + assertion = duplicatedKeys == [ ]; + message = "services.dmq-node.extraSettings sets keys owned by other options: ${toString duplicatedKeys}"; + } + ]; + + users = { + users = mkIf (cfg.user == defaultAccount) { + ${defaultAccount} = { + isSystemUser = true; + inherit (cfg) group; + }; + }; + groups = mkIf (cfg.group == defaultAccount) { + ${defaultAccount} = { }; + }; + }; + + networking.firewall.allowedTCPPorts = mkIf cfg.openFirewall [ cfg.port ]; + + systemd.services.dmq-node = { + description = "DMQ node"; + wantedBy = [ "multi-user.target" ]; + wants = [ "network-online.target" ]; + after = [ "network-online.target" ]; + + # dmq-node also exits when a running cardano-node restarts. Every such + # restart is a start here, so no start limit: a bounded one would leave + # dmq-node failed after a few node restarts. + startLimitIntervalSec = 0; + + serviceConfig = lib.mapAttrs (_: _: true) sandboxHides // { + ExecStart = lib.getExe dmqNode; + Restart = "always"; + RestartSec = "10s"; + + User = cfg.user; + Group = cfg.group; + SupplementaryGroups = [ cfg.cardanoNodeSocketGroup ]; + NoNewPrivileges = true; + AmbientCapabilities = capabilities; + CapabilityBoundingSet = capabilities; + RuntimeDirectory = runtimeDirectory; + RuntimeDirectoryMode = "0750"; + # The node-to-client socket must be group-writable for clients. + UMask = "0007"; + + ProtectSystem = "strict"; + PrivateDevices = true; + ProtectKernelTunables = true; + ProtectKernelModules = true; + ProtectControlGroups = true; + RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ]; + LockPersonality = true; + }; + }; + }; +} diff --git a/nix/nixos/tests/dmq-node.nix b/nix/nixos/tests/dmq-node.nix new file mode 100644 index 0000000..f5a1e0a --- /dev/null +++ b/nix/nixos/tests/dmq-node.nix @@ -0,0 +1,255 @@ +# Two stake pools, each a VM running cardano-node 11.2.1 (its own NixOS +# module) and dmq-node (ours). +{ pkgs, dmqModule, cardanoNodeModule, cardanoNodePackages, dmq-client }: + +let + inherit (pkgs) lib; + + # create-env stamps the build time; this fixed instant replaces it and the + # test sets both VM clocks to it. + systemStartPosix = 1893456000; + testnetMagic = 42; + dmqMagic = 4242; + cardanoPort = 3001; + dmqPort = 3141; + + env = pkgs.callPackage ./testnet-env.nix { + inherit (cardanoNodePackages) cardano-testnet cardano-cli; + inherit systemStartPosix testnetMagic; + }; + + # create-env writes the cardano-config envelope. services.cardano-node takes + # a flat config and envelopes it again (configFormat = "enveloped"). + envelope = (lib.importJSON "${env}/configuration.json").Configuration; + withStorePaths = lib.mapAttrs (key: value: + if lib.hasSuffix "GenesisFile" key then "${env}/${value}" else value); + nodeConfig = + withStorePaths (envelope.Protocol // envelope.Testing) + // envelope.Network + // envelope.HermodTracing + // { Protocol = "Cardano"; }; + + shelleyGenesis = lib.importJSON "${env}/shelley-genesis.json"; + + body = name: pkgs.writeText "body-${name}" (lib.concatStrings (lib.replicate 64 "${name}-msg/")); + + pool = name: peer: { config, nodes, ... }: + let + topologyFor = port: { + localRoots = [{ + accessPoints = [{ address = nodes.${peer}.networking.primaryIPAddress; inherit port; }]; + advertise = false; + trustable = true; + valency = 1; + }]; + publicRoots = [ ]; + useLedgerAfterSlot = -1; + }; + in + { + imports = [ cardanoNodeModule dmqModule ]; + + virtualisation = { + memorySize = 3072; + cores = 2; + }; + + networking.firewall.allowedTCPPorts = [ cardanoPort ]; + environment.systemPackages = [ cardanoNodePackages.cardano-cli dmq-client pkgs.jq ]; + + services = { + # The test owns the clock. + timesyncd.enable = false; + + cardano-node = { + enable = true; + inherit cardanoNodePackages nodeConfig; + configFormat = "enveloped"; + # The module writes its config with builtins.toFile, which cannot refer to + # the generated env; production genesis paths are sources, not derivations. + nodeConfigFile = "${pkgs.writeText "cardano-node-config.json" + (builtins.toJSON (cardanoNodePackages.cardanoLib.mkEnvelope nodeConfig))}"; + hostAddr = "0.0.0.0"; + port = cardanoPort; + kesKey = "/var/lib/pool-keys/kes.skey"; + vrfKey = "/var/lib/pool-keys/vrf.skey"; + operationalCertificate = "/var/lib/pool-keys/opcert.cert"; + topology = builtins.toFile "topology.json" (builtins.toJSON (topologyFor cardanoPort)); + }; + + dmq-node = { + enable = true; + networkMagic = dmqMagic; + cardanoNodeConfig = config.services.cardano-node.nodeConfig; + cardanoNodeSocketPath = config.services.cardano-node.socketPath 0; + hostAddr = config.networking.primaryIPAddress; + port = dmqPort; + openFirewall = true; + topology = topologyFor dmqPort; + traceOptions."" = { + backends = [ "Stdout MachineFormat" ]; + severity = "Info"; + }; + }; + }; + + systemd.services = { + # cardano-node refuses signing keys readable by others, and store paths are. + pool-keys = { + wantedBy = [ "multi-user.target" ]; + serviceConfig = { + Type = "oneshot"; + RemainAfterExit = true; + }; + script = '' + install -d -m 0700 -o cardano-node -g cardano-node /var/lib/pool-keys + for key in kes.skey vrf.skey opcert.cert; do + install -m 0400 -o cardano-node -g cardano-node \ + ${env}/pools-keys/${name}/$key /var/lib/pool-keys/$key + done + ''; + }; + + cardano-node = { + # Started by the test script once the clock is on the genesis instant. + wantedBy = lib.mkForce [ ]; + requires = [ "pool-keys.service" ]; + after = [ "pool-keys.service" ]; + # The node socket must be writable by group cardano-node, which dmq-node + # joins. + serviceConfig.UMask = "0007"; + }; + + dmq-node.wantedBy = lib.mkForce [ ]; + }; + }; +in +pkgs.testers.runNixOSTest { + name = "dmq-node"; + globalTimeout = 1500; + + nodes = { + pool1 = pool "pool1" "pool2"; + pool2 = pool "pool2" "pool1"; + }; + + testScript = { nodes, ... }: '' + import json + import time + + pools = [pool1, pool2] + cardano_socket = "${nodes.pool1.services.cardano-node.socketPath 0}" + dmq_socket = "${nodes.pool1.services.dmq-node.socketPath}" + keys = { + "pool1": "${env}/pools-keys/pool1", + "pool2": "${env}/pools-keys/pool2", + "unregistered": "${env}/unregistered", + } + bodies = { + "pool1": "${body "pool1"}", + "pool2": "${body "pool2"}", + "pool1-again": "${body "pool1-again"}", + "pool2-again": "${body "pool2-again"}", + } + slots_per_kes_period = ${toString shelleyGenesis.slotsPerKESPeriod} + + # dmq-node answers these until its cardano-node has a stake snapshot with + # the pool in it. + not_ready_yet = ("NotInitialized", "PoolNotEligible", "UnrecognizedPool") + + def tip(machine): + return json.loads(machine.succeed( + f"cardano-cli latest query tip --testnet-magic ${toString testnetMagic} --socket-path {cardano_socket}" + )) + + def submit(machine, key, body): + kes_period = tip(machine)["slot"] // slots_per_kes_period + return machine.execute( + f"dmq-client submit --socket {dmq_socket} --network-magic ${toString dmqMagic}" + f" --kes-signing-key {keys[key]}/kes.skey --op-cert {keys[key]}/opcert.cert" + f" --kes-period {kes_period} --expires-at $(( $(date +%s) + 900 ))" + f" --body {bodies[body]} 2>&1" + ) + + def submit_until_accepted(machine, key, body, retry_on): + deadline = time.monotonic() + 300 + while True: + status, out = submit(machine, key, body) + if status == 0: + return out.strip() + assert any(reason in out for reason in retry_on), f"{key} rejected: {out}" + assert time.monotonic() < deadline, f"{key} still rejected after 300s: {out}" + time.sleep(2) + + def notified_ids(path): + return [json.loads(line)["id"] for line in path.splitlines()] + + start_all() + for machine in pools: + machine.wait_for_unit("pool-keys.service") + + with subtest("both VM clocks on the genesis start"): + t0 = time.time() + for machine in pools: + machine.succeed(f"date -u -s @{${toString systemStartPosix} - 5 + (time.time() - t0):.3f}") + for machine in pools: + machine.succeed("systemctl start cardano-node.service dmq-node.service") + + with subtest("both pools forge on one chain"): + for machine in pools: + machine.wait_until_succeeds( + f"cardano-cli latest query tip --testnet-magic ${toString testnetMagic} --socket-path {cardano_socket}" + " | jq -e '.block >= 10'", + timeout=300, + ) + machine.wait_until_succeeds( + "journalctl -u cardano-node.service -o cat | grep -q Forge.Loop.AdoptedBlock", + timeout=120, + ) + assert tip(pool1)["era"] == "Conway", tip(pool1) + + with subtest("each dmq-node reads its cardano-node and peers with the other"): + for machine in pools: + machine.wait_until_succeeds( + "journalctl -u dmq-node.service -o cat | grep -q Net.Local.LocalStateQuery.CurrentEpoch", + timeout=120, + ) + machine.wait_until_succeeds( + "journalctl -u dmq-node.service -o cat | grep -q PromoteWarmDone", + timeout=120, + ) + machine.succeed(f"test \"$(stat -c %G {dmq_socket})\" = dmq-node") + machine.succeed( + "ps -o supgrp= -p \"$(systemctl show -p MainPID --value dmq-node.service)\"" + " | tr , '\\n' | grep -qx cardano-node" + ) + + with subtest("each pool's first message is accepted and reaches both dmq-nodes"): + id1 = submit_until_accepted(pool1, "pool1", "pool1", not_ready_yet) + id2 = submit_until_accepted(pool2, "pool2", "pool2", not_ready_yet) + for machine in pools: + out = machine.succeed( + f"timeout 120 dmq-client notify --socket {dmq_socket} --network-magic ${toString dmqMagic} --count 2" + ) + assert sorted(notified_ids(out)) == sorted([id1, id2]), out + + with subtest("later messages arrive once each, in order"): + pool2.succeed( + f"(timeout 300 dmq-client notify --socket {dmq_socket} --network-magic ${toString dmqMagic}" + " --count 4 > /tmp/notify 2>&1 &)" + ) + # dmq-node accepts one message per pool per minute. A resend of id3 + # would show up before id4, so the fourth message proves id3 came once. + id3 = submit_until_accepted(pool1, "pool1", "pool1-again", ("SigTooFrequent",)) + # id3 travels from pool1; let it land before pool2 adds id4 locally. + pool2.wait_until_succeeds(f"grep -q {id3} /tmp/notify", timeout=120) + id4 = submit_until_accepted(pool2, "pool2", "pool2-again", ("SigTooFrequent",)) + pool2.wait_until_succeeds("test $(wc -l < /tmp/notify) -ge 4", timeout=120) + ids = notified_ids(pool2.succeed("cat /tmp/notify")) + assert len(ids) == 4 and sorted(ids[:2]) == sorted([id1, id2]) and ids[2:] == [id3, id4], ids + + with subtest("a pool outside the stake distribution is rejected"): + status, out = submit(pool1, "unregistered", "pool1") + assert status != 0 and "UnrecognizedPool" in out, out + ''; +} diff --git a/nix/nixos/tests/testnet-env.nix b/nix/nixos/tests/testnet-env.nix new file mode 100644 index 0000000..6ffb7fb --- /dev/null +++ b/nix/nixos/tests/testnet-env.nix @@ -0,0 +1,48 @@ +# A two-pool cardano testnet from `cardano-testnet create-env`: Conway from +# epoch 0, with its genesis files, config and pool keys. +# +# create-env stamps systemStart with the build time. A cached build would start +# the chain days in the past, so both genesis start times are rewritten to +# `systemStartPosix` and the VM test sets its clocks to that instant. +{ runCommand, jq, cardano-testnet, cardano-cli, systemStartPosix, testnetMagic }: + +runCommand "dmq-testnet-env" +{ + nativeBuildInputs = [ cardano-testnet cardano-cli jq ]; + inherit systemStartPosix testnetMagic; +} '' + export HOME=$TMPDIR + export CARDANO_CLI=${cardano-cli}/bin/cardano-cli + cardano-testnet create-env --num-pool-nodes 2 --testnet-magic "$testnetMagic" --output env + cd env + + jq --arg t "$(date -u -d "@$systemStartPosix" +%Y-%m-%dT%H:%M:%SZ)" '.systemStart = $t' shelley-genesis.json > s.json + mv s.json shelley-genesis.json + jq --argjson t "$systemStartPosix" '.startTime = $t' byron-genesis.json > b.json + mv b.json byron-genesis.json + + shelley=$(cardano-cli hash genesis-file --genesis shelley-genesis.json) + byron=$(cardano-cli byron genesis print-genesis-hash --genesis-json byron-genesis.json) + jq --arg s "$shelley" --arg b "$byron" \ + '.Configuration.Protocol.ShelleyGenesisHash = $s | .Configuration.Protocol.ByronGenesisHash = $b' \ + configuration.yaml > configuration.json + + # A pool that is in no stake distribution, for the rejection case. + mkdir unregistered + cardano-cli latest node key-gen \ + --cold-verification-key-file unregistered/cold.vkey \ + --cold-signing-key-file unregistered/cold.skey \ + --operational-certificate-issue-counter-file unregistered/opcert.counter + cardano-cli latest node key-gen-KES \ + --verification-key-file unregistered/kes.vkey \ + --signing-key-file unregistered/kes.skey + cardano-cli latest node issue-op-cert \ + --kes-verification-key-file unregistered/kes.vkey \ + --cold-signing-key-file unregistered/cold.skey \ + --operational-certificate-issue-counter-file unregistered/opcert.counter \ + --kes-period 0 \ + --out-file unregistered/opcert.cert + + mkdir -p $out + cp -r configuration.json *-genesis.json pools-keys unregistered $out/ +'' diff --git a/nix/outputs.nix b/nix/outputs.nix index d99bad7..a08a5a0 100644 --- a/nix/outputs.nix +++ b/nix/outputs.nix @@ -28,6 +28,7 @@ let # pkgs.setGitRev # (inputs.self.rev or inputs.self.dirtyShortRev) pkgs.dmq-node.hsPkgs.dmq-node.components.exes.dmq-node; + dmq-client = pkgs.dmq-node.hsPkgs.dmq-node.components.exes.dmq-client; default = dmq-node; } // lib.optionalAttrs (builtins.hasAttr buildSystem staticCrossTarget) { dmq-node-static = @@ -64,6 +65,21 @@ let flake = pkgs.dmq-node.flake { }; format = pkgs.callPackage ./formatting.nix pkgs; + # cardano-node 11.2.1, fetched only when the NixOS test is evaluated; as a + # flake input it would put its whole lock into ours. + cardano-node = builtins.getFlake + "github:IntersectMBO/cardano-node/90bc1cd9380a78a63091ff673f8c5693152c8f60?narHash=sha256-gCKN9f0VXLLvJL/yMb3hztsa%2B91PJ93N6EHOoKhV4AI%3D"; + + checks = lib.optionalAttrs pkgs.stdenv.hostPlatform.isLinux { + nixos-dmq-node = import ./nixos/tests/dmq-node.nix { + inherit pkgs; + dmqModule = inputs.self.nixosModules.dmq-node; + cardanoNodeModule = cardano-node.nixosModules.cardano-node; + inherit (cardano-node.legacyPackages.${system}) cardanoNodePackages; + inherit (packages) dmq-client; + }; + }; + ciJobs = flake.hydraJobs // @@ -116,6 +132,8 @@ let constituents = utils.collectDerivationsWithoutChecks nativeJobs; }; required = utils.makeHydraRequiredJob ciJobs; + # Built by Hydra, outside `required`. + nixos-tests = checks; }; hydraJobs = @@ -131,6 +149,7 @@ in { inherit packages; inherit devShells; + inherit checks; inherit hydraJobs; legacyPackages = { format =