-
Notifications
You must be signed in to change notification settings - Fork 86
/
TxSpec.hs
296 lines (271 loc) · 12.3 KB
/
TxSpec.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
{-# LANGUAGE DuplicateRecordFields #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-- | Unit tests for our "hand-rolled" transactions as they are used in the
-- "direct" chain component.
module Hydra.Chain.Direct.TxSpec where
import Hydra.Cardano.Api
import Hydra.Chain.Direct.Tx
import Hydra.Prelude hiding (label)
import Test.Hydra.Prelude
import Cardano.Api.UTxO qualified as UTxO
import Cardano.Ledger.Api (auxDataTxL, bodyTxL, inputsTxBodyL, isValidTxL, mintTxBodyL, outputsTxBodyL, referenceInputsTxBodyL, reqSignerHashesTxBodyL, witsTxL)
import Cardano.Ledger.Core (EraTx (getMinFeeTx))
import Control.Lens ((^.))
import Data.Map qualified as Map
import Data.Text qualified as T
import Hydra.Cardano.Api.Pretty (renderTx)
import Hydra.Chain (HeadParameters (..))
import Hydra.Chain.Direct.Fixture (
epochInfo,
pparams,
systemStart,
testNetworkId,
testPolicyId,
testSeedInput,
)
import Hydra.Chain.Direct.ScriptRegistry (genScriptRegistry, registryUTxO)
import Hydra.Chain.Direct.State (HasKnownUTxO (getKnownUTxO), genChainStateWithTx)
import Hydra.Chain.Direct.State qualified as Transition
import Hydra.Chain.Direct.Wallet (ErrCoverFee (..), coverFee_)
import Hydra.Contract.Commit qualified as Commit
import Hydra.Contract.HeadTokens (headPolicyId, mkHeadTokenScript)
import Hydra.Contract.Initial qualified as Initial
import Hydra.Ledger.Cardano (adaOnly, genOneUTxOFor, genVerificationKey)
import Hydra.Ledger.Cardano.Evaluate (EvaluationReport, maxTxExecutionUnits)
import Hydra.Party (Party)
import Test.Hydra.Fixture (genForParty, testHeadId)
import Test.QuickCheck (
Property,
choose,
counterexample,
coverTable,
elements,
forAll,
forAllBlind,
label,
property,
suchThat,
vectorOf,
withMaxSuccess,
(.&&.),
(=/=),
(===),
)
import Test.QuickCheck.Instances.Semigroup ()
import Test.QuickCheck.Monadic (monadicIO)
import Test.QuickCheck.Property (checkCoverage)
spec :: Spec
spec =
parallel $ do
describe "HeadSeed (cardano)" $
prop "headSeedToTxIn . txInToHeadSeed === id" $ \txIn -> do
let headSeed = txInToHeadSeed txIn
headSeedToTxIn headSeed === Just txIn
& counterexample (show headSeed)
describe "HeadId (cardano)" $ do
prop "headIdToPolicyId . mkHeadId === id" $ \pid -> do
let headId = mkHeadId pid
headIdToPolicyId headId === Just pid
& counterexample (show headId)
prop "curencySymbolToHeadId . headIdToCurrencySymbol === id" $ \txIn -> monadicIO $ do
let headId = mkHeadId $ headPolicyId txIn
let cs = headIdToCurrencySymbol headId
headId' <- currencySymbolToHeadId cs
pure $ headId' === headId
describe "observeHeadTx" $ do
prop "All valid transitions for all possible states can be observed." $
checkCoverage $
forAllBlind genChainStateWithTx $ \(_ctx, st, tx, transition) ->
genericCoverTable [transition] $
counterexample (show transition) $
let utxo = getKnownUTxO st
in case observeHeadTx testNetworkId utxo tx of
NoHeadTx -> property False
Init{} -> transition === Transition.Init
Abort{} -> transition === Transition.Abort
Commit{} -> transition === Transition.Commit
CollectCom{} -> transition === Transition.Collect
Close{} -> transition === Transition.Close
Contest{} -> transition === Transition.Contest
Fanout{} -> transition === Transition.Fanout
describe "collectComTx" $ do
prop "cover fee correctly handles redeemers" $
withMaxSuccess 60 $ \txIn cperiod (party :| parties) walletUTxO -> do
let allParties = party : parties
cardanoKeys = genForParty genVerificationKey <$> allParties
forAll (elements cardanoKeys) $ \signer ->
forAll genScriptRegistry $ \scriptRegistry ->
let params = HeadParameters cperiod allParties
participants = verificationKeyToOnChainId <$> cardanoKeys
tx = initTx testNetworkId txIn participants params
in case observeInitTx tx of
Right InitObservation{initials, initialThreadUTxO} -> do
let lookupUTxO =
mconcat
[ Map.fromList (initialThreadUTxO : initials)
, UTxO.toMap (registryUTxO scriptRegistry)
]
& Map.mapKeys toLedgerTxIn
& Map.map toLedgerTxOut
in case abortTx mempty scriptRegistry signer initialThreadUTxO (mkHeadTokenScript testSeedInput) (Map.fromList initials) mempty of
Left err ->
property False & counterexample ("AbortTx construction failed: " <> show err)
Right (toLedgerTx -> txAbort) ->
case coverFee_ pparams systemStart epochInfo lookupUTxO walletUTxO txAbort of
Left err ->
True
& label
( case err of
ErrNoFuelUTxOFound{} -> "No fuel UTxO found"
ErrNotEnoughFunds{} -> "Not enough funds"
ErrUnknownInput{} -> "Unknown input"
ErrScriptExecutionFailed{} -> "Script(s) execution failed"
ErrTranslationError{} -> "Transaction context translation error"
)
Right ledgerTx ->
let actualExecutionCost = getMinFeeTx pparams ledgerTx
fee = txFee' apiTx
apiTx = fromLedgerTx ledgerTx
in actualExecutionCost > Coin 0 && fee > actualExecutionCost
& label "Ok"
& counterexample ("Execution cost: " <> show actualExecutionCost)
& counterexample ("Fee: " <> show fee)
& counterexample ("Tx: " <> show apiTx)
& counterexample ("Input utxo: " <> show (walletUTxO <> lookupUTxO))
Left e ->
property False
& counterexample "Failed to construct and observe init tx."
& counterexample (renderTx tx)
& counterexample (show e)
describe "commitTx" $ do
prop "Appends needed commit changes to blueprintTx" $ \blueprintTx' ->
forAll genScriptRegistry $ \scriptRegistry ->
forAll arbitrary $ \party ->
forAll (genAbortableOutputs [party] `suchThat` (\(a, _) -> not (null a))) $ \(initials, commits) ->
forAll arbitrary $ \vkh -> do
initialInputAndOutput <- elements initials
let utxoToCommit = foldMap third commits
let tx' = commitTx testNetworkId scriptRegistry testHeadId party utxoToCommit blueprintTx' (fst initialInputAndOutput, snd initialInputAndOutput, vkh)
let blueprintTx = toLedgerTx blueprintTx'
let blueprintBody = blueprintTx ^. bodyTxL
let tx = toLedgerTx tx'
let commitTxBody = tx ^. bodyTxL
-- TODO: assert all untouched tx fields are equal
pure $
(blueprintTx ^. witsTxL === tx ^. witsTxL)
.&&. (blueprintTx ^. isValidTxL === tx ^. isValidTxL)
.&&. (blueprintTx ^. auxDataTxL === tx ^. auxDataTxL)
.&&. property (length (blueprintBody ^. inputsTxBodyL) <= length (commitTxBody ^. inputsTxBodyL))
.&&. property (length (blueprintBody ^. outputsTxBodyL) <= length (commitTxBody ^. outputsTxBodyL))
.&&. property (length (blueprintBody ^. referenceInputsTxBodyL) <= length (commitTxBody ^. referenceInputsTxBodyL))
.&&. property (length (blueprintBody ^. reqSignerHashesTxBodyL) <= length (commitTxBody ^. reqSignerHashesTxBodyL))
withinTxExecutionBudget :: EvaluationReport -> Property
withinTxExecutionBudget report =
(totalMem <= maxMem && totalCpu <= maxCpu)
& counterexample
( "Ex. Cost Limits exceeded, mem: "
<> show totalMem
<> "/"
<> show maxMem
<> ", cpu: "
<> show totalCpu
<> "/"
<> show maxCpu
)
where
budgets = rights $ Map.elems report
totalMem = sum $ executionMemory <$> budgets
totalCpu = sum $ executionSteps <$> budgets
ExecutionUnits
{ executionMemory = maxMem
, executionSteps = maxCpu
} = maxTxExecutionUnits
-- | Generate a UTXO representing /commit/ outputs for a given list of `Party`.
-- NOTE: Uses 'testPolicyId' for the datum.
-- NOTE: We don't generate empty commits and it is used only at one place so perhaps move it?
-- FIXME: This function is very complicated and it's hard to understand it after a while
generateCommitUTxOs :: [Party] -> Gen (Map.Map TxIn (TxOut CtxUTxO, UTxO))
generateCommitUTxOs parties = do
txins <- vectorOf (length parties) (arbitrary @TxIn)
let vks = (\p -> (genVerificationKey `genForParty` p, p)) <$> parties
committedUTxO <-
vectorOf (length parties) $
fmap adaOnly <$> (genOneUTxOFor =<< arbitrary)
let commitUTxO =
zip txins $
uncurry mkCommitUTxO <$> zip vks committedUTxO
pure $ Map.fromList commitUTxO
where
mkCommitUTxO :: (VerificationKey PaymentKey, Party) -> UTxO -> (TxOut CtxUTxO, UTxO)
mkCommitUTxO (vk, party) utxo =
( toUTxOContext $
TxOut
(mkScriptAddress @PlutusScriptV2 testNetworkId commitScript)
commitValue
(mkTxOutDatumInline commitDatum)
ReferenceScriptNone
, utxo
)
where
commitValue =
mconcat
[ lovelaceToValue (Coin 2000000)
, foldMap txOutValue utxo
, valueFromList
[ (AssetId testPolicyId (assetNameFromVerificationKey vk), 1)
]
]
commitScript = fromPlutusScript Commit.validatorScript
commitDatum = mkCommitDatum party utxo (toPlutusCurrencySymbol testPolicyId)
prettyEvaluationReport :: EvaluationReport -> String
prettyEvaluationReport (Map.toList -> xs) =
"Script Evaluation(s):\n" <> intercalate "\n" (prettyKeyValue <$> xs)
where
prettyKeyValue (ptr, result) =
toString (" - " <> show ptr <> ": " <> prettyResult result)
prettyResult =
either (T.replace "\n" " " . show) show
-- NOTE: Uses 'testPolicyId' for the datum.
genAbortableOutputs :: [Party] -> Gen ([(TxIn, TxOut CtxUTxO)], [(TxIn, TxOut CtxUTxO, UTxO)])
genAbortableOutputs parties =
go
where
go = do
(initParties, commitParties) <- (`splitAt` parties) <$> choose (0, length parties)
initials <- mapM genInitial initParties
commits <- fmap (\(a, (b, c)) -> (a, b, c)) . Map.toList <$> generateCommitUTxOs commitParties
pure (initials, commits)
genInitial p =
mkInitial (genVerificationKey `genForParty` p) <$> arbitrary
mkInitial ::
VerificationKey PaymentKey ->
TxIn ->
(TxIn, TxOut CtxUTxO)
mkInitial vk txin =
( txin
, initialTxOut vk
)
initialTxOut :: VerificationKey PaymentKey -> TxOut CtxUTxO
initialTxOut vk =
toUTxOContext $
TxOut
(mkScriptAddress @PlutusScriptV2 testNetworkId initialScript)
(valueFromList [(AssetId testPolicyId (assetNameFromVerificationKey vk), 1)])
(mkTxOutDatumInline initialDatum)
ReferenceScriptNone
initialScript = fromPlutusScript Initial.validatorScript
initialDatum = Initial.datum (toPlutusCurrencySymbol testPolicyId)
assetNameFromVerificationKey :: VerificationKey PaymentKey -> AssetName
assetNameFromVerificationKey =
onChainIdToAssetName . verificationKeyToOnChainId
fst3 :: (a, b, c) -> a
fst3 (a, _, _) = a
third :: (a, b, c) -> c
third (_, _, c) = c
drop2nd :: (a, b, c) -> (a, c)
drop2nd (a, _, c) = (a, c)
drop3rd :: (a, b, c) -> (a, b)
drop3rd (a, b, _) = (a, b)
tripleToPair :: (a, b, c) -> (a, (b, c))
tripleToPair (a, b, c) = (a, (b, c))