-
Notifications
You must be signed in to change notification settings - Fork 86
/
ContractSpec.hs
658 lines (599 loc) · 21.6 KB
/
ContractSpec.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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -Wno-orphans #-}
module Hydra.Chain.Direct.ContractSpec where
import Hydra.Prelude hiding (label)
import Test.Hydra.Prelude
import Cardano.Api.Shelley (TxBody (ShelleyTxBody))
import Cardano.Binary (serialize')
import Cardano.Crypto.DSIGN (deriveVerKeyDSIGN)
import Cardano.Crypto.Util (SignableRepresentation (getSignableRepresentation))
import qualified Cardano.Ledger.Alonzo.Data as Ledger
import qualified Cardano.Ledger.Alonzo.Scripts as Ledger
import qualified Cardano.Ledger.Alonzo.TxBody as Ledger
import Cardano.Ledger.Alonzo.TxInfo (txInfoOut)
import qualified Cardano.Ledger.Alonzo.TxWitness as Ledger
import qualified Cardano.Ledger.Shelley.API as Ledger
import qualified Data.ByteString as BS
import qualified Data.ByteString.Base16 as Base16
import qualified Data.Map as Map
import Data.Maybe (fromJust)
import Data.Maybe.Strict (StrictMaybe (..))
import qualified Data.Sequence.Strict as StrictSeq
import Hydra.Chain.Direct.Fixture (testNetworkId)
import qualified Hydra.Chain.Direct.Fixture as Fixture
import Hydra.Chain.Direct.Tx (
closeTx,
collectComTx,
fanoutTx,
mkCommitDatum,
policyId,
)
import Hydra.Chain.Direct.TxSpec (mkHeadOutput)
import qualified Hydra.Contract.Commit as Commit
import Hydra.Contract.Encoding (serialiseTxOuts)
import qualified Hydra.Contract.Hash as Hash
import Hydra.Contract.Head (
verifyPartySignature,
verifySnapshotSignature,
)
import qualified Hydra.Contract.Head as Head
import Hydra.Data.Party (partyFromVerKey)
import qualified Hydra.Data.Party as OnChain
import qualified Hydra.Data.Party as Party
import Hydra.Ledger.Cardano (
AlonzoEra,
BuildTxWith (BuildTxWith),
CardanoTx,
CtxTx,
CtxUTxO,
Era,
ExecutionUnits (ExecutionUnits),
LedgerEra,
PlutusScriptV1,
Tx (Tx),
TxBodyScriptData (TxBodyNoScriptData, TxBodyScriptData),
TxIn,
TxOut (..),
TxOutDatum (..),
Utxo,
Utxo' (Utxo),
adaOnly,
addInputs,
describeCardanoTx,
emptyTxBody,
fromAlonzoExUnits,
fromLedgerTx,
fromLedgerTxOut,
fromLedgerUtxo,
fromPlutusScript,
genAdaOnlyUtxo,
genOutput,
genUtxoWithSimplifiedAddresses,
genValue,
getOutputs,
hashTxOuts,
lovelaceToTxOutValue,
lovelaceToValue,
mkDatumForTxIn,
mkRedeemerForTxIn,
mkScriptAddress,
mkScriptWitness,
mkTxOutDatum,
mkTxOutDatumHash,
mkTxOutValue,
modifyTxOutValue,
shrinkUtxo,
toCtxUTxOTxOut,
toLedgerTxIn,
toLedgerTxOut,
toPlutusData,
txOutValue,
unsafeBuildTransaction,
utxoPairs,
)
import qualified Hydra.Ledger.Cardano as Api
import Hydra.Ledger.Cardano.Evaluate (evaluateTx)
import Hydra.Ledger.Simple (SimpleTx)
import Hydra.Party (
MultiSigned (MultiSigned),
Party,
Signed (UnsafeSigned),
SigningKey,
aggregate,
deriveParty,
generateKey,
sign,
toPlutusSignatures,
vkey,
)
import Hydra.Snapshot (Snapshot (..), SnapshotNumber)
import Plutus.Orphans ()
import Plutus.V1.Ledger.Api (fromBuiltin, fromData, toBuiltin, toData)
import Plutus.V1.Ledger.Crypto (Signature (Signature))
import Test.QuickCheck (
Positive (Positive),
Property,
arbitrarySizedNatural,
checkCoverage,
choose,
counterexample,
elements,
forAll,
forAllShrink,
oneof,
property,
suchThat,
vector,
(===),
)
import Test.QuickCheck.Instances ()
import qualified Prelude
spec :: Spec
spec = do
describe "Signature validator" $ do
prop
"verifies single signature produced off-chain"
prop_verifyOffChainSignatures
-- FIXME(AB): This property exists solely because our current multisignature implementation
-- is just the aggregates of individual (mock) signatures and there is no point in doing some
-- complicated shuffle logic to verify signatures given we'll end up verifying a single Ed25519
-- signatures.
prop
"verifies snapshot multi-signature for list of parties and signatures"
prop_verifySnapshotSignatures
describe "TxOut hashing" $ do
modifyMaxSuccess (const 20) $
prop "OffChain.hashTxOuts == OnChain.hashTxOuts" prop_consistentOnAndOffChainHashOfTxOuts
describe "CollectCom" $ do
prop "is healthy" $
propTransactionValidates healthyCollectComTx
prop "does not survive random adversarial mutations" $
propMutation healthyCollectComTx genCollectComMutation
describe "Close" $ do
prop "is healthy" $
propTransactionValidates healthyCloseTx
prop "does not survive random adversarial mutations" $
propMutation healthyCloseTx genCloseMutation
describe "Fanout" $ do
prop "is healthy" $
propTransactionValidates healthyFanoutTx
prop "does not survive random adversarial mutations" $
propMutation healthyFanoutTx genFanoutMutation
describe "Hash" $
it "runs with these ^ execution units over Baseline" $ do
for_ [0 .. 5] $ \(power :: Integer) -> do
let n = 8 ^ power
s = n `quot` 8
putTextLn @IO $ " n = " <> show n <> ", s = " <> show s
for_ [minBound .. maxBound] $ \algorithm -> do
let ExecutionUnits
{ executionSteps = baseCpu
, executionMemory = baseMem
} = calculateHashExUnits n Hash.Base
units@ExecutionUnits
{ executionSteps = cpu
, executionMemory = mem
} = calculateHashExUnits n algorithm
putTextLn $
" " <> show algorithm
<> ": "
<> show units
<> " Δcpu="
<> show (toInteger cpu - toInteger baseCpu)
<> " Δmem="
<> show (toInteger mem - toInteger baseMem)
calculateHashExUnits :: Int -> Hash.HashAlgorithm -> ExecutionUnits
calculateHashExUnits n algorithm =
case evaluateTx tx utxo of
Left basicFailure ->
error ("Basic failure: " <> show basicFailure)
Right report ->
case Map.elems report of
[Right units] ->
fromAlonzoExUnits units
_ ->
error $ "Too many redeemers in report: " <> show report
where
tx = unsafeBuildTransaction $ emptyTxBody & addInputs [(input, witness)]
utxo = Utxo $ Map.singleton input output
input = generateWith arbitrary 42
output = toCtxUTxOTxOut $ TxOut address value (mkTxOutDatum datum)
value = lovelaceToTxOutValue 1_000_000
address = mkScriptAddress @PlutusScriptV1 testNetworkId script
witness = BuildTxWith $ mkScriptWitness script (mkDatumForTxIn datum) redeemer
script = fromPlutusScript Hash.validatorScript
datum = Hash.datum $ toBuiltin bytes
redeemer = mkRedeemerForTxIn $ Hash.redeemer algorithm
bytes = fold $ replicate n ("0" :: ByteString)
--
-- Properties
--
prop_consistentOnAndOffChainHashOfTxOuts :: Property
prop_consistentOnAndOffChainHashOfTxOuts =
-- NOTE: We only generate shelley addressed txouts because they are left out
-- of the plutus script context in 'txInfoOut'.
forAllShrink genUtxoWithSimplifiedAddresses shrinkUtxo $ \(utxo :: Utxo) ->
let plutusTxOuts = mapMaybe (txInfoOut . toLedgerTxOut) ledgerTxOuts
ledgerTxOuts = toList utxo
plutusBytes = serialiseTxOuts plutusTxOuts
ledgerBytes = serialize' (toLedgerTxOut <$> ledgerTxOuts)
in (hashTxOuts ledgerTxOuts === fromBuiltin (Head.hashTxOuts plutusTxOuts))
& counterexample ("Plutus: " <> show plutusTxOuts)
& counterexample ("Ledger: " <> show ledgerTxOuts)
& counterexample ("Ledger CBOR: " <> decodeUtf8 (Base16.encode ledgerBytes))
& counterexample ("Plutus CBOR: " <> decodeUtf8 (Base16.encode $ fromBuiltin plutusBytes))
prop_verifyOffChainSignatures :: Property
prop_verifyOffChainSignatures =
forAll arbitrary $ \(snapshot :: Snapshot SimpleTx) ->
forAll arbitrary $ \(Positive n) ->
let sk = generateKey n
UnsafeSigned signature = sign sk snapshot
party = partyFromVerKey $ deriveVerKeyDSIGN sk
snapshotNumber = toInteger $ number snapshot
in verifyPartySignature snapshotNumber party (Signature $ toBuiltin signature)
& counterexample ("signed: " <> show (BS.unpack signature))
& counterexample ("party: " <> show party)
& counterexample ("message: " <> show (getSignableRepresentation snapshot))
prop_verifySnapshotSignatures :: Property
prop_verifySnapshotSignatures =
forAll arbitrary $ \(snapshot :: Snapshot SimpleTx) ->
forAll genListOfSigningKeys $ \sks ->
let parties = partyFromVerKey . deriveVerKeyDSIGN <$> sks
signatures = toPlutusSignatures $ aggregate [sign sk snapshot | sk <- sks]
snapshotNumber = toInteger $ number snapshot
in verifySnapshotSignature parties snapshotNumber signatures
propMutation :: (CardanoTx, Utxo) -> ((CardanoTx, Utxo) -> Gen SomeMutation) -> Property
propMutation (tx, utxo) genMutation =
forAll @_ @Property (genMutation (tx, utxo)) $ \SomeMutation{label, mutation} ->
(tx, utxo)
& applyMutation mutation
& propTransactionDoesNotValidate
& genericCoverTable [label]
& checkCoverage
propTransactionDoesNotValidate :: (CardanoTx, Utxo) -> Property
propTransactionDoesNotValidate (tx, lookupUtxo) =
let result = evaluateTx tx lookupUtxo
in counterexample "Should have not validated" $
case result of
Left _ ->
property True
Right redeemerReport ->
any isLeft (Map.elems redeemerReport)
& counterexample ("Tx: " <> toString (describeCardanoTx tx))
& counterexample ("Lookup utxo: " <> decodeUtf8 (encodePretty lookupUtxo))
& counterexample ("Redeemer report: " <> show redeemerReport)
propTransactionValidates :: (CardanoTx, Utxo) -> Property
propTransactionValidates (tx, lookupUtxo) =
let result = evaluateTx tx lookupUtxo
in counterexample "Should have validated" $
case result of
Left _ ->
property False
& counterexample ("Tx: " <> toString (describeCardanoTx tx))
& counterexample ("Lookup utxo: " <> decodeUtf8 (encodePretty lookupUtxo))
Right redeemerReport ->
all isRight (Map.elems redeemerReport)
& counterexample ("Tx: " <> toString (describeCardanoTx tx))
& counterexample ("Lookup utxo: " <> decodeUtf8 (encodePretty lookupUtxo))
& counterexample ("Redeemer report: " <> show redeemerReport)
--
-- Mutation
--
data SomeMutation = forall lbl.
(Typeable lbl, Enum lbl, Bounded lbl, Show lbl) =>
SomeMutation
{ label :: lbl
, mutation :: Mutation
}
deriving instance Show SomeMutation
data Mutation
= ChangeHeadRedeemer Head.Input
| ChangeHeadDatum Head.State
| PrependOutput (TxOut CtxTx Era)
| ChangeOutput Word (TxOut CtxTx Era)
deriving (Show, Generic)
applyMutation :: Mutation -> (CardanoTx, Utxo) -> (CardanoTx, Utxo)
applyMutation mutation (tx@(Tx body wits), utxo) = case mutation of
ChangeHeadRedeemer newRedeemer ->
let ShelleyTxBody era ledgerBody scripts scriptData mAuxData scriptValidity = body
redeemers = alterRedeemers (changeHeadRedeemer newRedeemer) scriptData
body' = ShelleyTxBody era ledgerBody scripts redeemers mAuxData scriptValidity
in (Tx body' wits, utxo)
ChangeHeadDatum d' ->
let fn o@(TxOut addr value _)
| isHeadOutput o =
(TxOut addr value $ mkTxOutDatumHash d')
| otherwise =
o
in (tx, fmap fn utxo)
PrependOutput txOut ->
( alterTxOuts (txOut :) tx
, utxo
)
ChangeOutput ix txOut ->
( alterTxOuts replaceAtIndex tx
, utxo
)
where
replaceAtIndex txOuts =
foldr
( \(i, out) list ->
if i == ix then txOut : list else out : list
)
[]
(zip [0 ..] txOuts)
--
-- CollectComTx
--
healthyCollectComTx :: (CardanoTx, Utxo)
healthyCollectComTx =
( fromLedgerTx tx
, fromLedgerUtxo lookupUtxo
)
where
lookupUtxo =
Ledger.UTxO $
Map.singleton headInput headResolvedInput <> (fst <$> commits)
tx =
collectComTx
Fixture.testNetworkId
(Utxo $ Map.fromList committedUtxo)
(headInput, headDatum, healthyCollectComOnChainParties)
commits
committedUtxo =
generateWith
(replicateM (length healthyCollectComParties) genCommittableTxOut)
42
commits =
(uncurry healthyCommitOutput <$> zip healthyCollectComParties committedUtxo)
& Map.fromList
& Map.mapKeys toLedgerTxIn
& Map.map (first toLedgerTxOut)
headInput = generateWith arbitrary 42
headResolvedInput = mkHeadOutput (SJust headDatum)
headDatum = Ledger.Data $ toData healthyCollectComInitialDatum
healthyCollectComInitialDatum :: Head.State
healthyCollectComInitialDatum =
Head.Initial
{ contestationPeriod = generateWith arbitrary 42
, parties = healthyCollectComOnChainParties
}
healthyCollectComOnChainParties :: [OnChain.Party]
healthyCollectComOnChainParties =
Party.partyFromVerKey . vkey <$> healthyCollectComParties
healthyCollectComParties :: [Party]
healthyCollectComParties = flip generateWith 42 $ do
alice <- arbitrary
bob <- arbitrary
carol <- arbitrary
pure [alice, bob, carol]
genCommittableTxOut :: Gen (TxIn, TxOut CtxUTxO AlonzoEra)
genCommittableTxOut =
Prelude.head . utxoPairs <$> (genAdaOnlyUtxo `suchThat` (\u -> length u > 1))
healthyCommitOutput ::
Party ->
(TxIn, TxOut CtxUTxO AlonzoEra) ->
(TxIn, (TxOut CtxUTxO AlonzoEra, Ledger.Data LedgerEra))
healthyCommitOutput party committed =
( generateWith arbitrary seed
,
( toCtxUTxOTxOut (TxOut commitAddress commitValue (mkTxOutDatum commitDatum))
, Ledger.Data (toData commitDatum)
)
)
where
Party.UnsafeParty (fromIntegral -> seed) = Party.partyFromVerKey (vkey party)
commitScript =
fromPlutusScript Commit.validatorScript
commitAddress =
mkScriptAddress @Api.PlutusScriptV1 Fixture.testNetworkId commitScript
commitValue =
mkTxOutValue $
lovelaceToValue 2_000_000 <> (txOutValue . snd) committed
commitDatum =
mkCommitDatum party (Just committed)
data CollectComMutation
= MutateOpenOutputValue
| MutateOpenUtxoHash
deriving (Generic, Show, Enum, Bounded)
genCollectComMutation :: (CardanoTx, Utxo) -> Gen SomeMutation
genCollectComMutation (tx, _utxo) =
oneof
[ SomeMutation MutateOpenOutputValue . ChangeOutput 0 <$> do
mutatedValue <- (mkTxOutValue <$> genValue) `suchThat` (/= collectComOutputValue)
pure $ TxOut collectComOutputAddress mutatedValue collectComOutputDatum
, SomeMutation MutateOpenUtxoHash . ChangeOutput 0 <$> do
mutatedUtxoHash <- BS.pack <$> vector 32
case collectComOutputDatum of
TxOutDatumNone -> error "unexpected empty head datum"
(TxOutDatumHash _sdsie _ha) -> error "unexpected hash-only datum"
(TxOutDatum _sdsie sd) ->
case fromData $ toPlutusData sd of
Nothing -> error "Invalid data"
(Just Head.Open{parties}) ->
pure $
TxOut
collectComOutputAddress
collectComOutputValue
(mkTxOutDatum Head.Open{parties, Head.utxoHash = toBuiltin mutatedUtxoHash})
(Just st) -> error $ "unexpected state " <> show st
]
where
TxOut collectComOutputAddress collectComOutputValue collectComOutputDatum =
fromJust $ getOutputs tx !!? 0
--
-- CloseTx
--
healthyCloseTx :: (CardanoTx, Utxo)
healthyCloseTx =
( fromLedgerTx tx
, fromLedgerUtxo lookupUtxo
)
where
tx = closeTx healthySnapshot (healthySignature healthySnapshotNumber) (headInput, headOutput, headDatum)
headInput = generateWith arbitrary 42
headOutput = mkHeadOutput (SJust headDatum)
headDatum = Ledger.Data $ toData healthyCloseDatum
lookupUtxo = Ledger.UTxO $ Map.singleton headInput headOutput
healthySnapshot :: Snapshot CardanoTx
healthySnapshot =
Snapshot
{ number = healthySnapshotNumber
, utxo = mempty
, confirmed = []
}
healthySnapshotNumber :: SnapshotNumber
healthySnapshotNumber = 1
healthyCloseDatum :: Head.State
healthyCloseDatum =
Head.Open
{ parties = healthyCloseParties
, utxoHash = ""
}
healthyCloseParties :: [OnChain.Party]
healthyCloseParties = partyFromVerKey . vkey . deriveParty <$> healthyPartyCredentials
healthyPartyCredentials :: [SigningKey]
healthyPartyCredentials = [1, 2, 3]
healthySignature :: SnapshotNumber -> MultiSigned (Snapshot CardanoTx)
healthySignature number = MultiSigned [sign sk snapshot | sk <- healthyPartyCredentials]
where
snapshot = healthySnapshot{number}
data CloseMutation
= MutateSignatureButNotSnapshotNumber
| MutateSnapshotNumberButNotSignature
| MutateSnapshotToIllFormedValue
| MutateParties
deriving (Generic, Show, Enum, Bounded)
genCloseMutation :: (CardanoTx, Utxo) -> Gen SomeMutation
genCloseMutation (_tx, _utxo) =
-- FIXME: using 'closeRedeemer' here is actually too high-level and reduces
-- the power of the mutators, we should test at the level of the validator.
-- That is, using the on-chain types. 'closeRedeemer' is also not used
-- anywhere after changing this and can be moved into the closeTx
oneof
[ SomeMutation MutateSignatureButNotSnapshotNumber . ChangeHeadRedeemer <$> do
closeRedeemer (number healthySnapshot) <$> arbitrary
, SomeMutation MutateSnapshotNumberButNotSignature . ChangeHeadRedeemer <$> do
mutatedSnapshotNumber <- arbitrarySizedNatural `suchThat` (\n -> n /= healthySnapshotNumber && n > 0)
pure (closeRedeemer mutatedSnapshotNumber $ healthySignature healthySnapshotNumber)
, SomeMutation MutateSnapshotToIllFormedValue . ChangeHeadRedeemer <$> do
mutatedSnapshotNumber <- arbitrary `suchThat` (< 0)
let mutatedSignature =
MultiSigned [sign sk $ serialize' mutatedSnapshotNumber | sk <- healthyPartyCredentials]
pure
Head.Close
{ snapshotNumber = mutatedSnapshotNumber
, signature = toPlutusSignatures mutatedSignature
, utxoHash = ""
}
, SomeMutation MutateParties . ChangeHeadDatum <$> do
mutatedParties <- arbitrary `suchThat` (/= healthyCloseParties)
pure $
Head.Open
{ parties = mutatedParties
, utxoHash = ""
}
, SomeMutation MutateParties . ChangeHeadDatum <$> arbitrary `suchThat` \case
Head.Open{Head.parties = parties} ->
parties /= Head.parties healthyCloseDatum
_ ->
True
]
where
closeRedeemer snapshotNumber sig =
Head.Close
{ snapshotNumber = toInteger snapshotNumber
, signature = toPlutusSignatures sig
, utxoHash = ""
}
--
-- FanoutTx
--
healthyFanoutTx :: (CardanoTx, Utxo)
healthyFanoutTx =
( fromLedgerTx tx
, fromLedgerUtxo lookupUtxo
)
where
tx = fanoutTx healthyFanoutUtxo (headInput, headDatum)
headInput = generateWith arbitrary 42
headOutput = mkHeadOutput (SJust headDatum)
headDatum = Ledger.Data $ toData healthyFanoutDatum
lookupUtxo = Ledger.UTxO $ Map.singleton headInput headOutput
healthyFanoutUtxo :: Utxo
healthyFanoutUtxo =
-- NOTE: we trim down the generated tx's output to make sure it fits w/in
-- TX size limits
adaOnly <$> generateWith genUtxoWithSimplifiedAddresses 42
healthyFanoutDatum :: Head.State
healthyFanoutDatum =
Head.Closed 1 (toBuiltin $ hashTxOuts $ toList healthyFanoutUtxo)
data FanoutMutation
= MutateAddUnexpectedOutput
| MutateChangeOutputValue
deriving (Generic, Show, Enum, Bounded)
genFanoutMutation :: (CardanoTx, Utxo) -> Gen SomeMutation
genFanoutMutation (tx, _utxo) =
oneof
[ SomeMutation MutateAddUnexpectedOutput . PrependOutput <$> do
arbitrary >>= genOutput
, SomeMutation MutateChangeOutputValue <$> do
let outs = getOutputs tx
(ix, out) <- elements (zip [0 .. length outs - 1] outs)
value' <- genValue `suchThat` (/= txOutValue out)
pure $ ChangeOutput (fromIntegral ix) (modifyTxOutValue (const value') out)
]
--
-- Generators
--
genListOfSigningKeys :: Gen [SigningKey]
genListOfSigningKeys = choose (1, 20) <&> fmap generateKey . enumFromTo 1
genBytes :: Gen ByteString
genBytes = arbitrary
---
--- Orphans
---
deriving instance Eq Head.Input
instance Arbitrary Head.Input where
arbitrary = genericArbitrary
instance Arbitrary Head.State where
arbitrary = genericArbitrary
--
-- Helpers
--
isHeadOutput :: TxOut CtxUTxO Era -> Bool
isHeadOutput (TxOut addr _ _) = addr == headAddress
where
headAddress = Api.mkScriptAddress @Api.PlutusScriptV1 Fixture.testNetworkId headScript
headScript = Api.fromPlutusScript $ Head.validatorScript policyId
changeHeadRedeemer :: Head.Input -> (Ledger.Data era, Ledger.ExUnits) -> (Ledger.Data era, Ledger.ExUnits)
changeHeadRedeemer newRedeemer redeemer@(dat, units) =
case fromData (Ledger.getPlutusData dat) of
Just (_ :: Head.Input) ->
(Ledger.Data (toData newRedeemer), units)
Nothing ->
redeemer
alterRedeemers ::
((Ledger.Data LedgerEra, Ledger.ExUnits) -> (Ledger.Data LedgerEra, Ledger.ExUnits)) ->
TxBodyScriptData AlonzoEra ->
TxBodyScriptData AlonzoEra
alterRedeemers fn = \case
TxBodyNoScriptData -> error "TxBodyNoScriptData unexpected"
TxBodyScriptData supportedInEra dats (Ledger.Redeemers redeemers) ->
let newRedeemers = fmap fn redeemers
in TxBodyScriptData supportedInEra dats (Ledger.Redeemers newRedeemers)
alterTxOuts ::
([TxOut CtxTx Era] -> [TxOut CtxTx Era]) ->
CardanoTx ->
CardanoTx
alterTxOuts fn tx =
Tx body' wits
where
body' = ShelleyTxBody era ledgerBody' scripts scriptData mAuxData scriptValidity
ledgerBody' = ledgerBody{Ledger.outputs = outputs'}
-- WIP
outputs' = StrictSeq.fromList . mapOutputs . toList $ Ledger.outputs ledgerBody
mapOutputs = fmap (toLedgerTxOut . toCtxUTxOTxOut) . fn . fmap fromLedgerTxOut
ShelleyTxBody era ledgerBody scripts scriptData mAuxData scriptValidity = body
Tx body wits = tx