Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).

Expand Down
60 changes: 57 additions & 3 deletions clients/TypeScript/packages/client/test/DijkstraDevnet.test.ts
Original file line number Diff line number Diff line change
@@ -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.
Expand Down
27 changes: 18 additions & 9 deletions scripts/dijkstra-devnet-test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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.
#
Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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."

"$@"
24 changes: 24 additions & 0 deletions server/src/Ogmios/App/Protocol.hs
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@
module Ogmios.App.Protocol
( onUnmatchedMessage
, defaultWithInternalError
, yieldEncoded
) where

import Ogmios.Prelude

import Cardano.Network.Protocol.NodeToClient
( SerializedTransaction
)
import Control.Monad.Class.MonadThrow
( MonadEvaluate (..)
)
import Data.List
( isInfixOf
)
Expand All @@ -34,6 +38,7 @@ import Ogmios.Data.Json
( FromJSON
, Json
, MultiEraDecoder
, jsonToByteString
)
import Ogmios.Data.Protocol.ChainSync
( FindIntersection
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
12 changes: 11 additions & 1 deletion server/src/Ogmios/App/Protocol/TxMonitor.hs
Original file line number Diff line number Diff line change
Expand Up @@ -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 (..)
)
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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
Expand Down
20 changes: 6 additions & 14 deletions server/src/Ogmios/App/Protocol/TxSubmission.hs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ import Data.Type.Equality (
testEquality,
(:~:) (..),
)
import Ogmios.App.Protocol (
yieldEncoded,
)
import Ogmios.Control.MonadClock (
MonadClock (..),
)
Expand All @@ -97,7 +100,6 @@ import Ogmios.Data.Json (
Json,
MultiEraDecoder (..),
ToJSON,
jsonToByteString,
)
import Ogmios.Data.Ledger.ScriptFailure (
EvaluateTransactionError (..),
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)))

Expand All @@ -254,15 +246,15 @@ 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
clientStIdle
Right upgradedTx ->
pure $ SendMsgSubmitTx upgradedTx $ \result' -> do
clearMempoolOnSuccess result'
yieldEncoded toResponse $
yieldEncoded defaultWithInternalError yield toResponse $
mkSubmitTransactionResponse transaction result'
& toResponse
& encodeSubmitTransactionResponse
Expand All @@ -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
Expand Down
Loading
Loading