Skip to content

Commit

Permalink
Finish commit external script e2e spec
Browse files Browse the repository at this point in the history
Removed systemStart and epochInfo as arguments to mkChain factory method as they got redundant.
  • Loading branch information
ffakenz committed Jun 2, 2023
1 parent ee4d69d commit 0c360a5
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 94 deletions.
96 changes: 22 additions & 74 deletions hydra-cluster/src/Hydra/Cluster/Scenarios.hs
Expand Up @@ -11,9 +11,7 @@ import CardanoClient (
QueryPoint (QueryTip),
awaitTransaction,
buildTransaction,
queryEraHistory,
queryProtocolParameters,
querySystemStart,
queryTip,
submitTransaction,
)
Expand All @@ -22,47 +20,32 @@ import Control.Lens ((^?))
import Data.Aeson (Value, object, (.=))
import Data.Aeson.Lens (key, _JSON)
import Data.Aeson.Types (parseMaybe)
import qualified Data.List as List
import qualified Data.Set as Set
import Hydra.API.RestServer (DraftCommitTxRequest (..), DraftCommitTxResponse (..))
import Hydra.API.RestServer (DraftCommitTxRequest (..), DraftCommitTxResponse (..), ScriptInfo (..))
import Hydra.Cardano.Api (
AddressInEra,
BuildTxWith (BuildTxWith),
Key (SigningKey, getVerificationKey),
Lovelace (..),
PaymentKey,
PlutusScriptV2,
ProtocolParameters,
ScriptDatum (ScriptDatumForTxIn),
ScriptWitnessInCtx (ScriptWitnessForSpending),
ShelleyWitnessSigningKey (WitnessPaymentKey),
Tx,
TxId,
UTxO,
addTxIn,
balancedTxBody,
defaultTxBodyContent,
fromPlutusScript,
makeShelleyKeyWitness,
makeSignedTransaction,
makeTransactionBodyAutoBalance,
mkScriptAddress,
mkScriptWitness,
mkTxOutAutoBalance,
mkTxOutDatumHash,
mkVkAddress,
selectLovelace,
setTxInsCollateral,
setTxProtocolParams,
signShelleyTransaction,
throwErrorAsException,
toLedgerEpochInfo,
toScriptData,
txOutAddress,
txOutValue,
pattern ReferenceScriptNone,
pattern ScriptWitness,
pattern TxInsCollateral,
)
import Hydra.Chain (HeadId)
import Hydra.Chain.Direct.Wallet (signWith)
Expand Down Expand Up @@ -275,64 +258,29 @@ singlePartyCommitsFromExternalScript tracer workDir node hydraScriptsTxId =
scriptUtxo <- createScriptOutput pparams scriptAddress someSk normalUTxO
colateralUTxO <- seedFromFaucet node someVk 20_000_000 Normal (contramap FromFaucet tracer)

let redeemer = toScriptData ()
datum = ScriptDatumForTxIn $ toScriptData ()

let scriptTxIn = List.head $ fst <$> UTxO.pairs scriptUtxo
scriptWitness =
BuildTxWith $
ScriptWitness ScriptWitnessForSpending $
mkScriptWitness script datum redeemer
-- Request to build a draft commit tx from hydra-node
let reedemer = toScriptData () -- ScriptDataBytes mempty
datum = toScriptData () -- ScriptDataBytes mempty
collateralTxIns = fst <$> UTxO.pairs colateralUTxO
scriptInfo = ScriptInfo reedemer datum script collateralTxIns
clientPayload = DraftCommitTxRequest @Tx scriptUtxo (Just scriptInfo)

-- TODO: temporary sanity check: Spend the script on L1
let body =
defaultTxBodyContent
& addTxIn (scriptTxIn, scriptWitness)
& setTxInsCollateral (TxInsCollateral collateralTxIns)
& setTxProtocolParams (BuildTxWith $ Just pparams)

systemStart <- querySystemStart networkId nodeSocket QueryTip
epochInfo <- toLedgerEpochInfo <$> queryEraHistory networkId nodeSocket QueryTip

let changeAddress = mkVkAddress networkId someVk
balancedBody =
makeTransactionBodyAutoBalance
systemStart
epochInfo
pparams
mempty
(UTxO.toApi $ scriptUtxo <> normalUTxO)
body
changeAddress
Nothing
& \case
Left e -> error (show e)
Right res -> balancedTxBody res

let spendScriptTx = signShelleyTransaction balancedBody [WitnessPaymentKey someSk]
submitTransaction networkId nodeSocket spendScriptTx

-- -- Request to build a draft commit tx from hydra-node
-- let reedemer = ScriptDataBytes mempty
-- datum = ScriptDataBytes mempty
-- clientPayload = DraftCommitTxRequest @Tx scriptUtxo -- reedemer datum script
-- response <-
-- runReq defaultHttpConfig $
-- req
-- POST
-- (http "127.0.0.1" /: "commit")
-- (ReqBodyJson clientPayload)
-- (Proxy :: Proxy (JsonResponse (DraftCommitTxResponse Tx)))
-- (port $ 4000 + hydraNodeId)

-- responseStatusCode response `shouldBe` 200

-- let DraftCommitTxResponse commitTx = responseBody response

-- -- sign and submit the tx with our external user key
-- let signedCommitTx = signWith someSk commitTx
-- submitTransaction networkId nodeSocket signedCommitTx
response <-
runReq defaultHttpConfig $
req
POST
(http "127.0.0.1" /: "commit")
(ReqBodyJson clientPayload)
(Proxy :: Proxy (JsonResponse (DraftCommitTxResponse Tx)))
(port $ 4000 + hydraNodeId)

responseStatusCode response `shouldBe` 200

let DraftCommitTxResponse commitTx = responseBody response

-- sign and submit the tx with our external user key
let signedCommitTx = signWith someSk commitTx
submitTransaction networkId nodeSocket signedCommitTx

waitFor tracer 600 [n1] $
output "HeadIsOpen" ["utxo" .= scriptUtxo, "headId" .= headId]
Expand Down
6 changes: 1 addition & 5 deletions hydra-node/src/Hydra/Chain/Direct.hs
Expand Up @@ -48,7 +48,6 @@ import Hydra.Cardano.Api (
getTxBody,
getTxId,
shelleyBasedEra,
toLedgerEpochInfo,
toLedgerPParams,
toLedgerUTxO,
)
Expand Down Expand Up @@ -202,8 +201,7 @@ withDirectChain tracer config ctx wallet chainStateAt callback action = do
let getTimeHandle = queryTimeHandle networkId nodeSocket
localChainState <- newLocalChainState chainStateAt
pparams <- queryProtocolParameters networkId nodeSocket QueryTip
systemStart <- querySystemStart networkId nodeSocket QueryTip
epochInfo <- toLedgerEpochInfo <$> queryEraHistory networkId nodeSocket QueryTip

let chainHandle =
mkChain
tracer
Expand All @@ -213,8 +211,6 @@ withDirectChain tracer config ctx wallet chainStateAt callback action = do
localChainState
(submitTx queue)
pparams
systemStart
epochInfo

let handler = chainSyncHandler tracer callback getTimeHandle ctx localChainState
res <-
Expand Down
30 changes: 24 additions & 6 deletions hydra-node/src/Hydra/Chain/Direct/Handlers.hs
@@ -1,4 +1,5 @@
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UndecidableInstances #-}
Expand All @@ -15,18 +16,25 @@ import qualified Cardano.Api.UTxO as UTxO
import Cardano.Slotting.Slot (SlotNo (..))
import Control.Concurrent.Class.MonadSTM (modifyTVar, newTVarIO, writeTVar)
import Control.Monad.Class.MonadSTM (throwSTM)
import qualified Data.List as List
import Hydra.Cardano.Api (
BlockHeader,
BuildTxWith (BuildTxWith),
ChainPoint (..),
LedgerEpochInfo,
ProtocolParameters,
SystemStart,
ScriptWitnessInCtx (ScriptWitnessForSpending),
Tx,
TxId,
addTxIn,
chainPointToSlotNo,
getChainPoint,
getTxBody,
getTxId,
mkScriptWitness,
setTxInsCollateral,
setTxProtocolParams,
pattern ScriptWitness,
pattern TxInsCollateral,
)
import Hydra.Chain (Chain (..), ChainCallback, ChainEvent (..), ChainStateType, PostChainTx (..), PostTxError (..))
import Hydra.Chain.Direct.State (
Expand All @@ -52,6 +60,7 @@ import Hydra.Chain.Direct.Wallet (
)
import Hydra.ContestationPeriod (toNominalDiffTime)
import Hydra.Ledger (ChainSlot (ChainSlot))
import Hydra.Ledger.Cardano (unsafeBuildTransaction)
import Hydra.Logging (Tracer, traceWith)
import Plutus.Orphans ()
import System.IO.Error (userError)
Expand Down Expand Up @@ -127,10 +136,8 @@ mkChain ::
LocalChainState m ->
SubmitTx m ->
ProtocolParameters ->
SystemStart ->
LedgerEpochInfo ->
Chain Tx m
mkChain tracer queryTimeHandle wallet ctx LocalChainState{getLatest} submitTx pparams systemStart epochInfo =
mkChain tracer queryTimeHandle wallet ctx LocalChainState{getLatest} submitTx pparams =
Chain
{ postTx = \tx -> do
chainState <- atomically getLatest
Expand Down Expand Up @@ -173,7 +180,18 @@ mkChain tracer queryTimeHandle wallet ctx LocalChainState{getLatest} submitTx pp
Left CannotCommitReferenceScript -> pure $ Left CannotCommitReferenceScript
Left (CommittedTooMuchADAForMainnet l ml) -> pure $ Left $ CommittedTooMuchADAForMainnet l ml
Left e -> throwIO e
Right commitScriptTx ->
Right commitScriptTxBody -> do
let scriptTxIn = List.head $ fst <$> UTxO.pairs scriptUtxo
scriptWitness =
BuildTxWith $
ScriptWitness ScriptWitnessForSpending $
mkScriptWitness script datum redeemer
let commitScriptTx =
unsafeBuildTransaction $
commitScriptTxBody
& addTxIn (scriptTxIn, scriptWitness)
& setTxInsCollateral (TxInsCollateral collateralTxIns)
& setTxProtocolParams (BuildTxWith $ Just pparams)
Right <$> finalizeTx wallet ctx chainState scriptUtxo commitScriptTx
_ -> pure $ Left FailedToDraftTxNotInitializing
}
Expand Down
10 changes: 7 additions & 3 deletions hydra-node/src/Hydra/Chain/Direct/State.hs
Expand Up @@ -18,6 +18,7 @@ import qualified Data.Map as Map
import Data.Maybe (fromJust)
import Hydra.Cardano.Api (
AssetName (AssetName),
BuildTx,
ChainPoint (..),
CtxUTxO,
Hash,
Expand All @@ -30,6 +31,7 @@ import Hydra.Cardano.Api (
SerialiseAsRawBytes (serialiseToRawBytes),
SlotNo (SlotNo),
Tx,
TxBodyContent,
TxIn,
TxOut,
UTxO,
Expand Down Expand Up @@ -96,6 +98,7 @@ import Hydra.Chain.Direct.Tx (
observeContestTx,
observeFanoutTx,
observeInitTx,
rawCommitTxBody,
)
import Hydra.ContestationPeriod (ContestationPeriod)
import Hydra.Crypto (HydraKey)
Expand Down Expand Up @@ -323,7 +326,9 @@ commitScript ::
ChainContext ->
InitialState ->
UTxO ->
Either (PostTxError Tx) Tx
Either
(PostTxError Tx)
(TxBodyContent BuildTx)
commitScript ctx st utxo = do
case ownInitial ctx st of
Nothing ->
Expand All @@ -332,8 +337,7 @@ commitScript ctx st utxo = do
rejectByronAddress utxo
rejectReferenceScripts utxo
rejectMoreThanMainnetLimit networkId utxo
-- FIXME: should build a script tx using rawCommitTxBody and taking more args
Right $ commitTx networkId scriptRegistry headId ownParty utxo initial
Right $ rawCommitTxBody networkId scriptRegistry headId ownParty utxo initial
where
ChainContext{networkId, ownParty, scriptRegistry} = ctx
InitialState{headId} = st
Expand Down
9 changes: 3 additions & 6 deletions hydra-node/test/Hydra/Model/MockChain.hs
Expand Up @@ -43,7 +43,7 @@ import Hydra.Chain.Direct.Handlers (
)
import Hydra.Chain.Direct.ScriptRegistry (genScriptRegistry)
import Hydra.Chain.Direct.State (ChainContext (..))
import Hydra.Chain.Direct.TimeHandle (TimeHandle, TimeHandleParams (..), genTimeParams)
import Hydra.Chain.Direct.TimeHandle (TimeHandle)
import Hydra.Chain.Direct.Wallet (TinyWallet (..))
import Hydra.ContestationPeriod (ContestationPeriod)
import Hydra.Crypto (HydraKey)
Expand Down Expand Up @@ -222,9 +222,8 @@ createMockChain ::
LocalChainState m ->
Chain Tx m
createMockChain tracer ctx submitTx timeHandle seedInput chainState =
let TimeHandleParams{systemStart, eraHistory} = genTimeParams `generateWith` 42
-- NOTE: The wallet basically does nothing
wallet =
-- NOTE: The wallet basically does nothing
let wallet =
TinyWallet
{ getUTxO = pure mempty
, getSeedInput = pure (Just seedInput)
Expand All @@ -241,8 +240,6 @@ createMockChain tracer ctx submitTx timeHandle seedInput chainState =
chainState
submitTx
defaultProtocolParameters
systemStart
(toLedgerEpochInfo eraHistory)
where
defaultProtocolParameters = fromLedgerPParams ShelleyBasedEraShelley def

Expand Down

0 comments on commit 0c360a5

Please sign in to comment.