Skip to content

Commit

Permalink
PR review changes
Browse files Browse the repository at this point in the history
Mostly removing dead code, moving functions around and
changes related to tests.
  • Loading branch information
Sasha Bogicevic committed Apr 17, 2024
1 parent 6cfffe2 commit a465dd6
Show file tree
Hide file tree
Showing 16 changed files with 55 additions and 173 deletions.
4 changes: 2 additions & 2 deletions hydra-cluster/hydra-cluster.cabal
Expand Up @@ -85,7 +85,7 @@ library
build-depends:
, aeson
, async
, base >=4.7 && <5
, base >=4.7 && <5
, bytestring
, cardano-slotting
, containers
Expand All @@ -103,7 +103,7 @@ library
, lens
, lens-aeson
, optparse-applicative
, plutus-ledger-api:plutus-ledger-api-testlib >=1.9.1.0
, plutus-ledger-api >=1.9.1.0
, process
, QuickCheck
, req
Expand Down
23 changes: 10 additions & 13 deletions hydra-cluster/src/Hydra/Cluster/Scenarios.hs
Expand Up @@ -25,7 +25,7 @@ import Data.Aeson.Types (parseMaybe)
import Data.ByteString (isInfixOf)
import Data.ByteString qualified as B
import Data.Set qualified as Set
import Hydra.API.HTTPServer (DraftCommitTxRequest (..), DraftCommitTxResponse (..), TransactionSubmitted (..))
import Hydra.API.HTTPServer (DraftCommitTxResponse (..), TransactionSubmitted (..))
import Hydra.Cardano.Api (Coin (..), File (File), Key (SigningKey), PaymentKey, Tx, TxId, UTxO, getVerificationKey, isVkTxOut, lovelaceToValue, makeSignedTransaction, mkVkAddress, selectLovelace, signTx, txOutAddress, txOutValue, writeFileTextEnvelope, pattern ReferenceScriptNone, pattern TxOut, pattern TxOutDatumNone)
import Hydra.Chain.Direct.Tx (verificationKeyToOnChainId)
import Hydra.Cluster.Faucet (FaucetLog, seedFromFaucet, seedFromFaucet_)
Expand Down Expand Up @@ -294,9 +294,7 @@ singlePartyOpenAHead tracer workDir node hydraScriptsTxId callback =
where
RunningNode{networkId, nodeSocket, blockTime} = node

-- | Single hydra-node where the commit is done from an external UTxO owned by a
-- script which requires providing script, datum and redeemer instead of
-- signing the transaction.
-- | Single hydra-node where the commit is done using some wallet UTxO.
singlePartyCommitsFromExternal ::
Tracer IO EndToEndLog ->
FilePath ->
Expand All @@ -318,21 +316,20 @@ singlePartyCommitsFromExternal tracer workDir node hydraScriptsTxId =
send n1 $ input "Init" []
headId <- waitMatch (10 * blockTime) n1 $ headIsInitializingWith (Set.fromList [alice])

(walletVk, _) <- keysFor AliceFunds
(walletVk, walletSk) <- keysFor AliceFunds
utxoToCommit <- seedFromFaucet node walletVk 5_000_000 (contramap FromFaucet tracer)
-- Commit the script output using known witness
let clientPayload :: DraftCommitTxRequest Tx = SimpleCommitRequest{utxoToCommit}
-- Commit the script output
res <-
runReq defaultHttpConfig $
req
POST
(http "127.0.0.1" /: "commit")
(ReqBodyJson clientPayload)
(ReqBodyJson utxoToCommit)
(Proxy :: Proxy (JsonResponse (DraftCommitTxResponse Tx)))
(port $ 4000 + hydraNodeId)

let DraftCommitTxResponse{commitTx} = responseBody res
submitTx node commitTx
submitTx node $ signTx walletSk commitTx

lockedUTxO <- waitMatch (10 * blockTime) n1 $ \v -> do
guard $ v ^? key "headId" == Just (toJSON headId)
Expand Down Expand Up @@ -375,10 +372,10 @@ singlePartyCommitsFromExternalTxBlueprint tracer workDir node hydraScriptsTxId =
Right body -> do
let unsignedTx = makeSignedTransaction [] body
let clientPayload =
FullCommitRequest
{ blueprintTx = unsignedTx
, utxo = utxoToCommit
}
Aeson.object
[ "blueprintTx" Aeson..= toJSON unsignedTx
, "utxo" Aeson..= toJSON utxoToCommit
]
res <-
runReq defaultHttpConfig $
req
Expand Down
4 changes: 2 additions & 2 deletions hydra-cluster/src/HydraNode.hs
Expand Up @@ -167,8 +167,8 @@ waitForAll tracer delay nodes expected = do
_ ->
tryNext c msgs stillExpected

-- | Helper to make it easy to obtain a commit tx using a wallet utxo
-- | Create a commit tx using the hydra-node for later submission
-- | Helper to make it easy to obtain a commit tx using some wallet utxo.
-- Create a commit tx using the hydra-node for later submission.
requestCommitTx :: HydraClient -> UTxO -> IO Tx
requestCommitTx HydraClient{hydraNodeId} utxos =
runReq defaultHttpConfig request <&> commitTx . responseBody
Expand Down
1 change: 0 additions & 1 deletion hydra-node/hydra-node.cabal
Expand Up @@ -276,7 +276,6 @@ test-suite tests
Hydra.API.ServerSpec
Hydra.BehaviorSpec
Hydra.Chain.Direct.Contract.Abort
Hydra.Chain.Direct.Contract.Check
Hydra.Chain.Direct.Contract.Close
Hydra.Chain.Direct.Contract.CollectCom
Hydra.Chain.Direct.Contract.Commit
Expand Down
89 changes: 0 additions & 89 deletions hydra-node/json-schemas/api.yaml
Expand Up @@ -122,7 +122,6 @@ channels:
description: |
Possible responses of this endpoint are:
* DraftCommitTxResponse - 200 ok
* CannotCommitReferenceScript - 400 bad request
* CommittedTooMuchADAForMainnet - 400 bad request
* UnsupportedLegacyOutput - 400 bad request
* SpendingNodeUtxoForbidden - 400 bad request
Expand Down Expand Up @@ -1447,17 +1446,6 @@ components:
enum: ["UnsupportedLegacyOutput"]
byronAddress:
$ref: "api.yaml#/components/schemas/ByronAddress"
- title: CannotCommitReferenceScript
type: object
additionalProperties: false
required:
- tag
description: >-
The UTxO provided to commit contains a reference script, which is currently not supported.
properties:
tag:
type: string
enum: ["CannotCommitReferenceScript"]
- title: NoSeedInput
type: object
additionalProperties: false
Expand Down Expand Up @@ -1784,66 +1772,6 @@ components:
contentEncoding: base16
- type: "null"

TxOutWithWitness:
type: object
description: |
A single transaction output with optional witness to spend it.
Some notes related to witness field:
- When it is present we are treating the output as a script output.
- When `inlineDatum` is present we ignore the `witness.datum` field.
required:
- address
- value
additionalProperties: false
properties:
address:
$ref: "api.yaml#/components/schemas/Address"
value:
$ref: "api.yaml#/components/schemas/Value"
referenceScript:
oneOf:
- $ref: "api.yaml#/components/schemas/Script"
- type: "null"
datumhash:
oneOf:
- type: string
contentEncoding: base16
- type: "null"
inlineDatum:
oneOf:
- type: object
- type: "null"
inlineDatumhash:
oneOf:
- type: string
contentEncoding: base16
- type: "null"
datum:
oneOf:
- type: string
contentEncoding: base16
- type: "null"
witness:
oneOf:
- $ref: "api.yaml#/components/schemas/Witness"
- type: "null"

Witness:
type: object
description: |
A script witness
required:
- datum
- plutusV2Script
- redeemer
additionalProperties: false
properties:
datum:
type: string
plutusV2Script:
$ref: "api.yaml#/components/schemas/PlutusV2Script"
redeemer:
type: string
HydraNodeVersion:
type: string
description: |
Expand Down Expand Up @@ -1935,23 +1863,6 @@ components:

# END OF SERVER OUTPUT SCHEMAS

ScriptInfo:
description: |
Script data needed to spend user provided utxo.
If datum field is ommitted we expect inline datum to be present.
required:
- redeemer
- plutusV2Script
payload:
type: object
properties:
redeemer:
$ref: "api.yaml#/components/schemas/Cbor"
datum:
$ref: "api.yaml#/components/schemas/Cbor"
plutusV2Script:
type: object
$ref: "api.yaml#/components/schemas/PlutusV2Script"

PlutusV2Script:
type: object
Expand Down
1 change: 0 additions & 1 deletion hydra-node/src/Hydra/API/HTTPServer.hs
Expand Up @@ -193,7 +193,6 @@ handleDraftCommitUtxo directChain getInitializingHeadId body = do
-- Distinguish between errors users can actually benefit from and
-- other errors that are turned into 500 responses.
case e of
CannotCommitReferenceScript -> return400 e
CommittedTooMuchADAForMainnet _ _ -> return400 e
UnsupportedLegacyOutput _ -> return400 e
walletUtxoErr@SpendingNodeUtxoForbidden -> return400 walletUtxoErr
Expand Down
2 changes: 0 additions & 2 deletions hydra-node/src/Hydra/Chain.hs
Expand Up @@ -131,8 +131,6 @@ data PostTxError tx
| CannotFindOwnInitial {knownUTxO :: UTxOType tx}
| -- | Comitting byron addresses is not supported.
UnsupportedLegacyOutput {byronAddress :: Address ByronAddr}
| -- | Comitting reference scripts is not supported right now.
CannotCommitReferenceScript
| InvalidStateToPost {txTried :: PostChainTx tx, chainState :: ChainStateType tx}
| NotEnoughFuel
| NoFuelUTXOFound
Expand Down
2 changes: 1 addition & 1 deletion hydra-node/src/Hydra/Chain/Direct/Tx.hs
Expand Up @@ -9,7 +9,7 @@
-- thus we have not yet "reached" 'isomorphism'.
module Hydra.Chain.Direct.Tx where

import Hydra.Cardano.Api hiding (hashScript)
import Hydra.Cardano.Api
import Hydra.Prelude

import Cardano.Api.UTxO qualified as UTxO
Expand Down
14 changes: 0 additions & 14 deletions hydra-node/src/Hydra/Ledger/Cardano.hs
Expand Up @@ -231,20 +231,6 @@ mkRangedTx (txin, TxOut owner valueIn datum refScript) (recipient, valueOut) sk
, txValidityUpperBound = fromMaybe TxValidityNoUpperBound validityUpperBound
}

-- TODO: This should actually be isomorphic to ScriptWitness of cardano-api,
-- i.e. we should support also native scripts, other versions of plutus and
-- witnessing via reference inputs
data ScriptInfo = ScriptInfo
{ redeemer :: HashableScriptData
, datum :: Maybe HashableScriptData
, plutusV2Script :: PlutusScript
}
deriving stock (Show, Eq, Generic)
deriving anyclass (ToJSON, FromJSON)

instance Arbitrary ScriptInfo where
arbitrary = genericArbitrary

-- | Create _blueprint_ transaction used as a starting point for a proper commit tx.
--
-- This is to ensure the backwards compatibility with `UTxO'` which
Expand Down
32 changes: 31 additions & 1 deletion hydra-node/src/Hydra/Ledger/Cardano/Evaluate.hs
Expand Up @@ -59,6 +59,7 @@ import Hydra.Cardano.Api (
toLedgerTx,
toLedgerUTxO,
)
import Hydra.Cardano.Api.Pretty (renderTxWithUTxO)
import Hydra.ContestationPeriod (ContestationPeriod (UnsafeContestationPeriod))
import Hydra.Ledger.Cardano.Time (slotNoFromUTCTime, slotNoToUTCTime)
import Ouroboros.Consensus.Cardano.Block (CardanoEras)
Expand All @@ -75,7 +76,7 @@ import Ouroboros.Consensus.HardFork.History (
import PlutusCore qualified as PLC
import PlutusLedgerApi.Common (mkTermToEvaluate)
import PlutusLedgerApi.Common qualified as Plutus
import Test.QuickCheck (choose)
import Test.QuickCheck (Property, choose, counterexample, property)
import Test.QuickCheck.Gen (chooseWord64)
import UntypedPlutusCore (UnrestrictedProgram (..))
import UntypedPlutusCore qualified as UPLC
Expand Down Expand Up @@ -351,6 +352,35 @@ slotLength = mkSlotLength 1
systemStart :: SystemStart
systemStart = SystemStart $ posixSecondsToUTCTime 0

-- * Properties

-- | Expect a given 'Tx' and 'UTxO' to pass evaluation.
propTransactionEvaluates :: (Tx, UTxO) -> Property
propTransactionEvaluates (tx, lookupUTxO) =
case evaluateTx tx lookupUTxO of
Left err ->
property False
& counterexample ("Transaction: " <> renderTxWithUTxO lookupUTxO tx)
& counterexample ("Phase-1 validation failed: " <> show err)
Right redeemerReport ->
all isRight (Map.elems redeemerReport)
& counterexample ("Transaction: " <> renderTxWithUTxO lookupUTxO tx)
& counterexample ("Redeemer report: " <> show redeemerReport)
& counterexample "Phase-2 validation failed"

-- | Expect a given 'Tx' and 'UTxO' to fail phase 1 or phase 2 evaluation.
propTransactionFailsEvaluation :: (Tx, UTxO) -> Property
propTransactionFailsEvaluation (tx, lookupUTxO) =
case evaluateTx tx lookupUTxO of
Left _ -> property True
Right redeemerReport ->
any isLeft redeemerReport
& counterexample ("Transaction: " <> renderTxWithUTxO lookupUTxO tx)
& counterexample ("Redeemer report: " <> show redeemerReport)
& counterexample "Phase-2 validation should have failed"

-- * Generators

genPointInTime :: Gen (SlotNo, UTCTime)
genPointInTime = do
slot <- SlotNo <$> arbitrary
Expand Down
3 changes: 0 additions & 3 deletions hydra-node/test/Hydra/API/HTTPServerSpec.hs
Expand Up @@ -116,14 +116,11 @@ apiServerSpec = do
prop "handles PostTxErrors accordingly" $ \request postTxError -> do
let expectedResponse =
case postTxError of
CannotCommitReferenceScript -> 400
SpendingNodeUtxoForbidden -> 400
CommittedTooMuchADAForMainnet{} -> 400
UnsupportedLegacyOutput{} -> 400
_ -> 500
let coverage = case postTxError of
-- TODO: This is not actually returned by draftCommitTx anymore, should remove the type
CannotCommitReferenceScript -> cover 1 True "CannotCommitReferenceScript"
SpendingNodeUtxoForbidden -> cover 1 True "SpendingNodeUtxoForbidden"
CommittedTooMuchADAForMainnet{} -> cover 1 True "CommittedTooMuchADAForMainnet"
UnsupportedLegacyOutput{} -> cover 1 True "UnsupportedLegacyOutput"
Expand Down
23 changes: 0 additions & 23 deletions hydra-node/test/Hydra/Chain/Direct/Contract/Check.hs

This file was deleted.

10 changes: 0 additions & 10 deletions hydra-node/test/Hydra/Chain/Direct/Contract/Mutation.hs
Expand Up @@ -213,16 +213,6 @@ propTransactionFailsPhase2 mExpectedError (tx, lookupUTxO) =
ScriptErrorEvaluationFailed _ errList -> errMsg `elem` errList
_otherScriptExecutionError -> False

-- | Expect a given 'Tx' and 'UTxO' to fail phase 1 or phase 2 evaluation.
propTransactionFailsEvaluation :: (Tx, UTxO) -> Property
propTransactionFailsEvaluation (tx, lookupUTxO) =
case evaluateTx tx lookupUTxO of
Left _ -> property True
Right redeemerReport ->
any isLeft redeemerReport
& counterexample ("Transaction: " <> renderTxWithUTxO lookupUTxO tx)
& counterexample ("Redeemer report: " <> show redeemerReport)
& counterexample "Phase-2 validation should have failed"

-- * Mutations

Expand Down
2 changes: 1 addition & 1 deletion hydra-node/test/Hydra/Chain/Direct/ContractSpec.hs
Expand Up @@ -20,7 +20,6 @@ import Hydra.Cardano.Api (
)
import Hydra.Cardano.Api.Network (networkIdToNetwork)
import Hydra.Chain.Direct.Contract.Abort (genAbortMutation, healthyAbortTx, propHasCommit, propHasInitial)
import Hydra.Chain.Direct.Contract.Check (propTransactionEvaluates)
import Hydra.Chain.Direct.Contract.Close (genCloseInitialMutation, genCloseMutation, healthyCloseInitialTx, healthyCloseTx)
import Hydra.Chain.Direct.Contract.CollectCom (genCollectComMutation, healthyCollectComTx)
import Hydra.Chain.Direct.Contract.Commit (genCommitMutation, healthyCommitTx)
Expand Down Expand Up @@ -64,6 +63,7 @@ import Test.QuickCheck (
(==>),
)
import Test.QuickCheck.Instances ()
import Hydra.Ledger.Cardano.Evaluate (propTransactionEvaluates)

spec :: Spec
spec = parallel $ do
Expand Down

0 comments on commit a465dd6

Please sign in to comment.