diff --git a/CHANGELOG.md b/CHANGELOG.md index 32405b4c9..0af0c2fbf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,7 +38,7 @@ math: true #### Fixed -- A failure while encoding the response of `submitTransaction` now returns a JSON-RPC internal error to the client. Before, the websocket connection was closed with no reply. +- A failure while encoding the response of `submitTransaction` or `nextTransaction` now returns a JSON-RPC internal error to the client. Before, the websocket connection was closed with no reply. - In the Dijkstra era, `submitTransaction` now reports why the ledger rejected a transaction, with the same errors as in earlier eras. Before, a Dijkstra rejection closed the websocket connection with no reply. A failure inside a sub-transaction gets the same error as the same failure in a top-level transaction, and the error does not say which sub-transaction failed. A withdrawal from an account that is not registered gets [`UnknownCredential`](https://ogmios.dev/mini-protocols/local-tx-submission#schema-3146/UnknownCredential) (`code=3146`) with the credential of one such account, where earlier eras report [`IncompleteWithdrawals`](https://ogmios.dev/mini-protocols/local-tx-submission#schema-3141/IncompleteWithdrawals) (`code=3141`). diff --git a/clients/TypeScript/packages/client/test/DijkstraDevnet.test.ts b/clients/TypeScript/packages/client/test/DijkstraDevnet.test.ts index 420287431..0cbfbe30c 100644 --- a/clients/TypeScript/packages/client/test/DijkstraDevnet.test.ts +++ b/clients/TypeScript/packages/client/test/DijkstraDevnet.test.ts @@ -1,39 +1,93 @@ import { dummyInteractionContext } from './helpers' import { createChainSynchronizationClient } from '../src/ChainSynchronization' +import { networkTip } from '../src/LedgerStateQuery' +import { createMempoolMonitoringClient, MempoolMonitoringClient } from '../src/MempoolMonitoring' import { submitTransaction } from '../src/TransactionSubmission' import { Transaction } from '@cardano-ogmios/schema' +import { execFileSync } from 'child_process' import { inspect } from 'util' // Set by scripts/dijkstra-devnet-test.sh. Without DIJKSTRA_TX_ID, these tests are skipped. const transactionCbor = process.env.DIJKSTRA_TX_CBOR const transactionId = process.env.DIJKSTRA_TX_ID const subTransactionId = process.env.DIJKSTRA_SUB_TX_ID +const producerPid = process.env.DIJKSTRA_PRODUCER_PID + +// Pause a process with SIGSTOP, and wait until it is stopped. +const pause = async (pid: number) => { + process.kill(pid, 'SIGSTOP') + while (!execFileSync('ps', ['-o', 'stat=', '-p', String(pid)]).toString().trim().startsWith('T')) { + await new Promise(resolve => setTimeout(resolve, 10)) + } +} const describeOnDevnet = transactionId === undefined ? describe.skip : describe describeOnDevnet('Dijkstra devnet', () => { // Each test needs the transaction submitted, so it is submitted once, first. let submittedId: string | undefined + // The next block takes the transaction out of the mempool. So the mempool + // snapshot is taken by acquireMempool() in beforeAll, right after the submission. + let mempool: MempoolMonitoringClient beforeAll(async () => { - if (transactionCbor === undefined) { - throw new Error('DIJKSTRA_TX_CBOR is not set: run this test through scripts/dijkstra-devnet-test.sh') + if (transactionCbor === undefined || producerPid === undefined) { + throw new Error('DIJKSTRA_TX_CBOR or DIJKSTRA_PRODUCER_PID is not set: run this test through scripts/dijkstra-devnet-test.sh') } + mempool = await createMempoolMonitoringClient(await dummyInteractionContext()) const context = await dummyInteractionContext() try { + // Ogmios is connected to a relay. While the block producer is paused, no + // block can take the transaction out of the mempool before the snapshot. + await pause(Number(producerPid)) submittedId = await submitTransaction(context, transactionCbor) + await mempool.acquireMempool() } catch (error) { // The errors of the client have an empty stack, which Jest shows as an empty message. - throw new Error(`submitTransaction failed: ${inspect(error, { depth: null })}`) + throw new Error(`Submitting the transaction or taking the mempool snapshot failed: ${inspect(error, { depth: null })}`) } finally { context.socket.close() + process.kill(Number(producerPid), 'SIGCONT') } }) + afterAll(async () => { + await mempool?.shutdown() + }) + it('submits a transaction with a sub-transaction', () => { expect(submittedId).toBe(transactionId) }) + it('reads a transaction with a sub-transaction from the mempool', async () => { + expect(submittedId).toBeDefined() + let tx: Transaction | null + try { + tx = await mempool.nextTransaction({ fields: 'all' }) + while (tx !== null && tx.id !== transactionId) { + tx = await mempool.nextTransaction({ fields: 'all' }) + } + } catch (error) { + // The errors of the client have an empty stack, which Jest shows as an empty message. + throw new Error(`Reading the mempool failed: ${inspect(error, { depth: null })}`) + } + + expect(tx?.id).toBe(transactionId) + expect(tx?.subTransactions?.map(subTx => subTx.id)).toEqual([subTransactionId]) + }) + + it('rejects a transaction submitted twice, and keeps the connection open', async () => { + expect(submittedId).toBeDefined() + const context = await dummyInteractionContext() + try { + // 3173: all inputs of the transaction are already spent. + await expect(submitTransaction(context, transactionCbor as string)).rejects.toMatchObject({ code: 3173 }) + await expect(networkTip(context)).resolves.toBeDefined() + } finally { + context.socket.close() + } + }) + it('reads a transaction with a sub-transaction from a block', async () => { // Jest 26 runs the tests even when beforeAll fails. Without a submitted // transaction, the blocks would be read until the test times out. diff --git a/scripts/dijkstra-devnet-test.sh b/scripts/dijkstra-devnet-test.sh index 8a8dcb250..c93aa1816 100755 --- a/scripts/dijkstra-devnet-test.sh +++ b/scripts/dijkstra-devnet-test.sh @@ -9,7 +9,9 @@ # Start a local devnet in the Dijkstra era, with Ogmios on it. Build a # transaction with a sub-transaction, but do not submit it. Then run # COMMAND, with DIJKSTRA_TX_CBOR set to the transaction (in base16), and -# DIJKSTRA_TX_ID and DIJKSTRA_SUB_TX_ID set to the ids of both. +# DIJKSTRA_TX_ID and DIJKSTRA_SUB_TX_ID set to the ids of both, and +# DIJKSTRA_PRODUCER_PID set to the process id of the node that makes the +# blocks. Ogmios is connected to the other node, a relay. # Everything started here stops when the script ends. The files of the # devnet are removed, unless the script fails. # @@ -31,13 +33,14 @@ MAGIC=42 FEE=1000000 # A short path: the node socket path must stay short. WORK=$(mktemp -d /tmp/devnet.XXXXXX) -SOCKET="$WORK/env/socket/node1/sock" +# node1 makes the blocks, node2 is a relay. +SOCKET="$WORK/env/socket/node2/sock" PIDS=() # Whether the processes started here have all exited. none_running() { local pid - for pid in "${PIDS[@]}" "$(cat "$WORK/env/logs/node1/node.pid" 2>/dev/null)"; do + for pid in "${PIDS[@]}" "$(cat "$WORK/env/logs/node1/node.pid" 2>/dev/null)" "$(cat "$WORK/env/logs/node2/node.pid" 2>/dev/null)"; do if [ -n "$pid" ] && kill -0 "$pid" 2>/dev/null; then return 1 fi @@ -49,9 +52,13 @@ stop() { for pid in "${PIDS[@]}"; do kill "$pid" 2>/dev/null || true done - if [ -f "$WORK/env/logs/node1/node.pid" ]; then - kill "$(cat "$WORK/env/logs/node1/node.pid")" 2>/dev/null || true - fi + for node in node1 node2; do + if [ -f "$WORK/env/logs/$node/node.pid" ]; then + # A paused node only stops once it is resumed. + kill -CONT "$(cat "$WORK/env/logs/$node/node.pid")" 2>/dev/null || true + kill "$(cat "$WORK/env/logs/$node/node.pid")" 2>/dev/null || true + fi + done if [ "$status" -eq 0 ]; then # Wait for them to exit, or files they still write could stay behind. wait_for 30 none_running || true @@ -100,12 +107,13 @@ lovelace_of() { } echo "Starting the devnet in $WORK." -cardano-testnet create-env --num-pool-nodes 1 --testnet-magic "$MAGIC" --output "$WORK/env" \ +cardano-testnet create-env --nodes spo,relay --testnet-magic "$MAGIC" --output "$WORK/env" \ > "$WORK/create-env.log" 2>&1 || fail "cardano-testnet create-env failed" # Conway from the start, Dijkstra from epoch 1. Dijkstra at epoch 0 stops the node. jq '.Configuration.Testing.TestDijkstraHardForkAtEpoch = 1' "$WORK/env/configuration.yaml" > "$WORK/config.json" mv "$WORK/config.json" "$WORK/env/configuration.yaml" -(cd "$WORK" && exec cardano-testnet cardano --node-env "$WORK/env" > "$WORK/testnet.log" 2>&1) & +# The test pauses the block producer, so the chain-stall watchdog is turned off. +(cd "$WORK" && exec cardano-testnet cardano --node-env "$WORK/env" --disable-chain-stall-watchdog > "$WORK/testnet.log" 2>&1) & PIDS+=($!) wait_for 300 cli query tip || fail "the node does not answer" @@ -157,7 +165,8 @@ cardano-cli dijkstra transaction sign \ DIJKSTRA_SUB_TX_ID=$(cardano-cli dijkstra sub-transaction txid --signed-sub-tx-file "$WORK/sub.signed.json" --output-text) DIJKSTRA_TX_ID=$(cardano-cli dijkstra transaction txid --tx-file "$WORK/signed.json" --output-text) DIJKSTRA_TX_CBOR=$(jq -r .cborHex "$WORK/signed.json") -export DIJKSTRA_SUB_TX_ID DIJKSTRA_TX_ID DIJKSTRA_TX_CBOR +DIJKSTRA_PRODUCER_PID=$(cat "$WORK/env/logs/node1/node.pid") +export DIJKSTRA_SUB_TX_ID DIJKSTRA_TX_ID DIJKSTRA_TX_CBOR DIJKSTRA_PRODUCER_PID echo "Built transaction $DIJKSTRA_TX_ID with sub-transaction $DIJKSTRA_SUB_TX_ID." "$@" diff --git a/server/src/Ogmios/App/Protocol.hs b/server/src/Ogmios/App/Protocol.hs index 00dd8e6b1..7f9b9e5c5 100644 --- a/server/src/Ogmios/App/Protocol.hs +++ b/server/src/Ogmios/App/Protocol.hs @@ -7,6 +7,7 @@ module Ogmios.App.Protocol ( onUnmatchedMessage , defaultWithInternalError + , yieldEncoded ) where import Ogmios.Prelude @@ -14,6 +15,9 @@ import Ogmios.Prelude import Cardano.Network.Protocol.NodeToClient ( SerializedTransaction ) +import Control.Monad.Class.MonadThrow + ( MonadEvaluate (..) + ) import Data.List ( isInfixOf ) @@ -34,6 +38,7 @@ import Ogmios.Data.Json ( FromJSON , Json , MultiEraDecoder + , jsonToByteString ) import Ogmios.Data.Protocol.ChainSync ( FindIntersection @@ -74,8 +79,10 @@ import Ouroboros.Network.Block import qualified Codec.Json.Rpc as Rpc import qualified Codec.Json.Rpc.Handler as Rpc import qualified Data.Aeson as Json +import qualified Data.Aeson.Encoding as JsonEncoding import qualified Data.Aeson.KeyMap as Json import qualified Data.Aeson.Types as Json +import qualified Data.ByteString.Builder as Builder import qualified Data.Text as T -- | A default handler for unmatched requests. This is an attempt to provide @@ -203,3 +210,20 @@ defaultWithInternalError reportException opts continue yield toResponse = do yield $ Rpc.ko opts $ Rpc.internalError mirror (displayException e) reportException e continue + +-- | Encode a response before sending it. If encoding fails, reply with an +-- internal error instead of closing the connection. Errors while sending are +-- not caught. +yieldEncoded + :: (Monad m, MonadEvaluate m) + => (m (Maybe Json) -> (Json -> m ()) -> Rpc.ToResponse r -> m (Maybe Json) -> m (Maybe Json)) + -- ^ A handler that turns exceptions into internal errors, like 'defaultWithInternalError' + -> (Json -> m ()) + -- ^ An emitter for yielding JSON objects + -> Rpc.ToResponse r + -> Json + -> m () +yieldEncoded withInternalError yield toResponse json = + withInternalError (pure Nothing) yield toResponse + (Just . JsonEncoding.unsafeToEncoding . Builder.byteString <$> evaluate (jsonToByteString json)) + >>= traverse_ yield diff --git a/server/src/Ogmios/App/Protocol/TxMonitor.hs b/server/src/Ogmios/App/Protocol/TxMonitor.hs index b8971cbae..828d1ff43 100644 --- a/server/src/Ogmios/App/Protocol/TxMonitor.hs +++ b/server/src/Ogmios/App/Protocol/TxMonitor.hs @@ -45,6 +45,12 @@ import Ogmios.Prelude hiding ( id ) +import Control.Monad.Class.MonadThrow + ( MonadEvaluate + ) +import Ogmios.App.Protocol + ( yieldEncoded + ) import Ogmios.Control.MonadSTM ( MonadSTM (..) ) @@ -96,6 +102,7 @@ import qualified Codec.Json.Rpc as Rpc mkTxMonitorClient :: forall m block crypto. ( MonadSTM m + , MonadEvaluate m , HasTxId (GenTx block) , block ~ CardanoBlock crypto ) @@ -153,7 +160,10 @@ mkTxMonitorClient defaultWithInternalError TxMonitorCodecs{..} queue yield _node NextTransactionResponseId (txId <$> mTx) Just NextTransactionAllFields -> NextTransactionResponseTx mTx - yield $ encodeNextTransactionResponse $ toResponse response + -- On an encoding failure the client gets an internal error, and the + -- next call returns the transaction after this one. + yieldEncoded defaultWithInternalError yield toResponse $ + encodeNextTransactionResponse $ toResponse response clientStAcquired MsgHasTransaction HasTransaction{id} toResponse -> defaultWithInternalError clientStAcquired yield toResponse $ do diff --git a/server/src/Ogmios/App/Protocol/TxSubmission.hs b/server/src/Ogmios/App/Protocol/TxSubmission.hs index cb415959e..067593a54 100644 --- a/server/src/Ogmios/App/Protocol/TxSubmission.hs +++ b/server/src/Ogmios/App/Protocol/TxSubmission.hs @@ -71,6 +71,9 @@ import Data.Type.Equality ( testEquality, (:~:) (..), ) +import Ogmios.App.Protocol ( + yieldEncoded, + ) import Ogmios.Control.MonadClock ( MonadClock (..), ) @@ -97,7 +100,6 @@ import Ogmios.Data.Json ( Json, MultiEraDecoder (..), ToJSON, - jsonToByteString, ) import Ogmios.Data.Ledger.ScriptFailure ( EvaluateTransactionError (..), @@ -188,8 +190,6 @@ import Type.Reflection ( import qualified Codec.Json.Rpc as Rpc import qualified Data.Aeson as Json -import qualified Data.Aeson.Encoding as JsonEncoding -import qualified Data.ByteString.Builder as Builder import qualified Data.Map.Strict as Map import qualified Data.Text as T import qualified Ouroboros.Consensus.HardFork.Combinator as HF @@ -224,14 +224,6 @@ mkTxSubmissionClient tr defaultWithInternalError TxSubmissionCodecs{..} Executio await :: m (TxSubmissionMessage block) await = atomically (readTQueue queue) - -- | Encode eagerly, so that an encoder exception becomes an internal error reply instead of - -- surfacing in the websocket send. 'yield' stays outside the handler on purpose. - yieldEncoded :: Rpc.ToResponse r -> Json -> m () - yieldEncoded toResponse json = - defaultWithInternalError (pure Nothing) yield toResponse - (Just . JsonEncoding.unsafeToEncoding . Builder.byteString <$> evaluate (jsonToByteString json)) - >>= traverse_ yield - isMostRecentEra era = T.toLower (toText era) == T.toLower (toText (eraName @(MostRecentEra block))) @@ -254,7 +246,7 @@ mkTxSubmissionClient tr defaultWithInternalError TxSubmissionCodecs{..} Executio SubmitFail (ApplyTxErrWrongEra eraMismatch) | isMostRecentEra (ledgerEraName eraMismatch) -> do case upgradeGenTx transaction of Left hint -> do - yieldEncoded toResponse $ + yieldEncoded defaultWithInternalError yield toResponse $ SubmitTransactionFailedToUpgrade hint & toResponse & encodeSubmitTransactionResponse @@ -262,7 +254,7 @@ mkTxSubmissionClient tr defaultWithInternalError TxSubmissionCodecs{..} Executio Right upgradedTx -> pure $ SendMsgSubmitTx upgradedTx $ \result' -> do clearMempoolOnSuccess result' - yieldEncoded toResponse $ + yieldEncoded defaultWithInternalError yield toResponse $ mkSubmitTransactionResponse transaction result' & toResponse & encodeSubmitTransactionResponse @@ -272,7 +264,7 @@ mkTxSubmissionClient tr defaultWithInternalError TxSubmissionCodecs{..} Executio -- mempool to ensure we always use the latest available -- mempool snapshot during evaluation. clearMempoolOnSuccess result - yieldEncoded toResponse $ + yieldEncoded defaultWithInternalError yield toResponse $ mkSubmitTransactionResponse transaction result & toResponse & encodeSubmitTransactionResponse diff --git a/server/test/unit/Ogmios/App/Protocol/TxMonitorSpec.hs b/server/test/unit/Ogmios/App/Protocol/TxMonitorSpec.hs index 00e22ed15..551f91805 100644 --- a/server/test/unit/Ogmios/App/Protocol/TxMonitorSpec.hs +++ b/server/test/unit/Ogmios/App/Protocol/TxMonitorSpec.hs @@ -74,6 +74,7 @@ import Ogmios.Data.Json.Orphans import Ogmios.Data.Json.Prelude ( MetadataFormat (..) , at + , inefficientEncodingToValue ) import Ogmios.Data.Protocol.TxMonitor ( AcquireMempool (..) @@ -81,6 +82,7 @@ import Ogmios.Data.Protocol.TxMonitor , GenTxId , HasTransaction (..) , NextTransaction (..) + , NextTransactionFields (..) , ReleaseMempool (..) , SizeOfMempool (..) , SlotNo (..) @@ -160,6 +162,7 @@ spec = parallel $ do context "TxMonitor" $ do parallel $ prop "Any sequence acquire/has/next/size is valid" prop_anySequenceValid parallel $ prop "Can and must query after acquiring" prop_queryAfterAcquiring + parallel $ prop "Replies with an internal error when a transaction fails to encode" prop_encoderFailure where prop_anySequenceValid :: Property prop_anySequenceValid = @@ -173,7 +176,7 @@ spec = parallel $ do & cover 1 (nextThenHas False msgs) "NextTransaction then HasTransaction" ) where - p msgs = prop_inIOSim $ withTxMonitorClient $ \send receive -> do + p msgs = prop_inIOSim $ withTxMonitorClient (encodeTx (MetadataNoSchema, omitOptionalCbor)) $ \send receive -> do send $ acquireMempool Nothing expectRpcResponse isAcquireMempoolResponse receive Json.Null forM_ msgs $ \(msg, mirror, predicate) -> do @@ -211,21 +214,42 @@ spec = parallel $ do & cover 1 ("SizeOfMempool" == showTxMonitorMessage arg) "SizeOfMempool" ) where - p (msg, mirror, _) = prop_inIOSim $ withTxMonitorClient $ \send receive -> do + p (msg, mirror, _) = prop_inIOSim $ withTxMonitorClient (encodeTx (MetadataNoSchema, omitOptionalCbor)) $ \send receive -> do send msg expectRpcResponse isMustAcquireFirst receive (toJSON mirror) + prop_encoderFailure :: Property + prop_encoderFailure = + prop_inIOSim $ withTxMonitorClient (const $ error "cannot encode") $ \send receive -> do + -- The mempool can be empty. Acquire it again until it holds a transaction. + let nextUntilFailure = do + send $ acquireMempool Nothing + expectRpcResponse isAcquireMempoolResponse receive Json.Null + send $ nextTxWithAllFields Nothing + response <- receive + if isNoTransaction response then do + send $ releaseMempool Nothing + expectRpcResponse isReleaseMempoolResponse receive Json.Null + nextUntilFailure + else + expectRpcResponse isInternalError (pure response) Json.Null + nextUntilFailure + -- The client still answers. + send $ sizeOfMempool Nothing + expectRpcResponse isSizeOfMempoolResponse receive Json.Null + type Protocol = LocalTxMonitor (GenTxId Block) (GenTx Block) SlotNo withTxMonitorClient :: (MonadCatch m, MonadEvaluate m, MonadOuroboros m) - => ((TxMonitorMessage Block -> m ()) -> m Json -> m a) + => (GenTx Block -> Json) + -> ((TxMonitorMessage Block -> m ()) -> m Json -> m a) -> StdGen -> m a -withTxMonitorClient action seed = do +withTxMonitorClient encodeTx' action seed = do (recvQ, sendQ) <- atomically $ (,) <$> newTQueue <*> newTQueue let opts = Rpc.defaultOptions - let innerCodecs = mkTxMonitorCodecs opts encodeGenTxId (encodeTx (MetadataNoSchema, omitOptionalCbor)) + let innerCodecs = mkTxMonitorCodecs opts encodeGenTxId encodeTx' let client = mkTxMonitorClient (defaultWithInternalError (const $ return ()) opts) innerCodecs recvQ (atomically . writeTQueue sendQ) NodeToClientV_23 let codec = codecs defaultSlotsPerEpoch nodeToClientV_Latest & cTxMonitorCodec withMockChannel (txMonitorMockPeer seed codec) $ \channel -> do @@ -458,6 +482,16 @@ isNextTxResponse :: ResponsePredicate isNextTxResponse = ResponsePredicate $ \v -> ("method" `at` v) == Just (toJSON @Text "nextTransaction") +nextTxWithAllFields :: Rpc.Mirror -> TxMonitorMessage Block +nextTxWithAllFields mirror = + MsgNextTransaction (NextTransaction (Just NextTransactionAllFields)) (Rpc.Response method mirror) + where + method = Just "nextTransaction" + +isNoTransaction :: Json -> Bool +isNoTransaction json = + (("result" `at` inefficientEncodingToValue json) >>= at "transaction") == Just Json.Null + hasTx :: Rpc.Mirror -> Ledger.TxId -> TxMonitorMessage Block hasTx mirror tx = MsgHasTransaction (HasTransaction tx) (Rpc.Response method mirror) @@ -505,6 +539,13 @@ isMustAcquireFirst = ResponsePredicate $ code <- "code" `at` e guard (code == toJSON @Int 4000) +isInternalError :: ResponsePredicate +isInternalError = ResponsePredicate $ + \v -> isJust $ do + e <- "error" `at` v + code <- "code" `at` e + guard (code == toJSON @Int (-32603)) + -- -- Helpers --