-
Notifications
You must be signed in to change notification settings - Fork 155
/
ImpTest.hs
1351 lines (1239 loc) · 44.3 KB
/
ImpTest.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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilyDependencies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE UndecidableSuperClasses #-}
module Test.Cardano.Ledger.Shelley.ImpTest (
ImpTestM,
SomeSTSEvent (..),
runImpTestM,
runImpTestM_,
evalImpTestM,
execImpTestM,
runImpTestGenM,
runImpTestGenM_,
evalImpTestGenM,
execImpTestGenM,
ImpTestState,
ImpTestEnv (..),
ImpException (..),
ShelleyEraImp (..),
PlutusArgs,
ScriptTestContext,
initShelleyImpNES,
impWitsVKeyNeeded,
modifyPrevPParams,
passEpoch,
passNEpochs,
passTick,
freshKeyHash,
freshKeyPair,
freshKeyAddr,
lookupKeyPair,
freshByronKeyHash,
freshBootstapAddress,
lookupByronKeyPair,
freshSafeHash,
freshKeyHashVRF,
submitTx,
submitTx_,
submitTxAnn,
submitTxAnn_,
submitFailingTx,
trySubmitTx,
modifyNES,
getsNES,
getUTxO,
impAddNativeScript,
impAnn,
runImpRule,
tryRunImpRule,
registerRewardAccount,
lookupReward,
registerPool,
getRewardAccountAmount,
withImpState,
shelleyFixupTx,
lookupImpRootTxOut,
sendValueTo,
sendCoinTo,
expectRegisteredRewardAddress,
expectNotRegisteredRewardAddress,
expectTreasury,
updateAddrTxWits,
addNativeScriptTxWits,
addRootTxIn,
fixupFees,
impGetNativeScript,
impLookupUTxO,
-- * Logging
logEntry,
logToExpr,
logStakeDistr,
logFeeMismatch,
-- * Combinators
withNoFixup,
-- We only export getters, because internal state should not be accessed during testing
impNESG,
impLastTickG,
impKeyPairsG,
impNativeScriptsG,
) where
import qualified Cardano.Chain.Common as Byron
import Cardano.Crypto.DSIGN (DSIGNAlgorithm (..), Ed25519DSIGN, seedSizeDSIGN)
import Cardano.Crypto.Hash (Hash, HashAlgorithm)
import Cardano.Crypto.Seed (mkSeedFromBytes)
import qualified Cardano.Crypto.VRF as VRF
import Cardano.Ledger.Address (
Addr (..),
BootstrapAddress (..),
RewardAccount (..),
bootstrapKeyHash,
)
import Cardano.Ledger.BaseTypes (
BlocksMade (..),
EpochSize (..),
Globals (..),
Network (..),
ShelleyBase,
SlotNo,
StrictMaybe (..),
TxIx (..),
inject,
mkTxIxPartial,
)
import Cardano.Ledger.CertState (certDStateL, dsUnifiedL)
import Cardano.Ledger.Coin (Coin (..))
import Cardano.Ledger.Core
import Cardano.Ledger.Credential (Credential (..), StakeReference (..), credToText)
import Cardano.Ledger.Crypto (Crypto (..))
import Cardano.Ledger.EpochBoundary (emptySnapShots)
import Cardano.Ledger.Keys (
HasKeyRole (..),
KeyHash,
KeyRole (..),
VerKeyVRF,
bootstrapWitKeyHash,
hashKey,
makeBootstrapWitness,
witVKeyHash,
)
import Cardano.Ledger.PoolDistr (IndividualPoolStake (..), PoolDistr (..))
import Cardano.Ledger.PoolParams (PoolParams (..))
import Cardano.Ledger.SafeHash (HashAnnotated (..), SafeHash, extractHash)
import Cardano.Ledger.Shelley (ShelleyEra)
import Cardano.Ledger.Shelley.AdaPots (sumAdaPots, totalAdaPotsES)
import Cardano.Ledger.Shelley.Core
import Cardano.Ledger.Shelley.LedgerState (
AccountState (..),
EpochState (..),
LedgerState (..),
NewEpochState (..),
StashedAVVMAddresses,
asTreasuryL,
consumed,
curPParamsEpochStateL,
epochStateIncrStakeDistrL,
epochStateUMapL,
esAccountStateL,
esLStateL,
lsCertStateL,
lsUTxOStateL,
nesELL,
nesEsL,
prevPParamsEpochStateL,
produced,
smartUTxOState,
startStep,
utxosDonationL,
utxosUtxoL,
)
import Cardano.Ledger.Shelley.Rules (LedgerEnv (..))
import Cardano.Ledger.Shelley.Scripts (MultiSig (..))
import Cardano.Ledger.Tools (calcMinFeeTxNativeScriptWits, integralToByteStringN)
import Cardano.Ledger.TxIn (TxId (..), TxIn (..))
import Cardano.Ledger.UMap as UMap
import Cardano.Ledger.UTxO (
EraUTxO (..),
ScriptsProvided (..),
UTxO (..),
txinLookup,
)
import Cardano.Ledger.Val (Val (..))
import Control.Monad (forM)
import Control.Monad.IO.Class
import Control.Monad.Reader (MonadReader (..), asks)
import Control.Monad.State.Strict (MonadState (..), execStateT, gets, modify)
import Control.Monad.Trans (lift)
import Control.Monad.Trans.Reader (ReaderT (..))
import Control.Monad.Writer.Class (MonadWriter (..))
import Control.State.Transition (STS (..), TRC (..), applySTSOptsEither)
import Control.State.Transition.Extended (
ApplySTSOpts (..),
AssertionPolicy (..),
SingEP (..),
ValidationPolicy (..),
)
import Data.Coerce (coerce)
import Data.Data (Proxy (..), type (:~:) (..))
import Data.Default.Class (Default (..))
import Data.Foldable (toList)
import Data.Functor (($>))
import Data.Functor.Identity (Identity (..))
import Data.IORef
import Data.List.NonEmpty (NonEmpty)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (catMaybes, fromMaybe, mapMaybe)
import Data.Sequence.Strict (StrictSeq (..))
import qualified Data.Sequence.Strict as SSeq
import qualified Data.Set as Set
import qualified Data.Text as T
import Data.Type.Equality (TestEquality (..))
import GHC.Stack (SrcLoc (..), getCallStack)
import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)
import Lens.Micro (Lens', SimpleGetter, lens, to, (%~), (&), (.~), (<>~), (^.))
import Lens.Micro.Mtl (use, view, (%=), (+=), (.=))
import Numeric.Natural (Natural)
import Prettyprinter (Doc, Pretty (..), defaultLayoutOptions, layoutPretty, line)
import Prettyprinter.Render.String (renderString)
import System.Random
import qualified System.Random as Random
import Test.Cardano.Ledger.Core.Arbitrary ()
import Test.Cardano.Ledger.Core.KeyPair (
ByronKeyPair (..),
KeyPair (..),
mkAddr,
mkKeyHash,
mkWitnessesVKey,
)
import Test.Cardano.Ledger.Core.Utils (mkDummySafeHash, testGlobals, txInAt)
import Test.Cardano.Ledger.Imp.Common
import Test.Cardano.Ledger.Plutus (PlutusArgs, ScriptTestContext)
import Test.Cardano.Ledger.Shelley.TreeDiff (Expr (..))
import Test.Cardano.Slotting.Numeric ()
import Test.HUnit.Lang (FailureReason (..), HUnitFailure (..))
import Test.Hspec.Core.Spec (Example (..), Params, paramsQuickCheckArgs)
import Test.QuickCheck.Gen (Gen (..))
import Test.QuickCheck.Random (QCGen (..), mkQCGen)
import Type.Reflection (Typeable, typeOf)
import UnliftIO (MonadUnliftIO (..))
import UnliftIO.Exception (
Exception (..),
SomeException (..),
catchAny,
catchAnyDeep,
evaluateDeep,
throwIO,
)
data SomeSTSEvent era
= forall (rule :: Symbol).
( Typeable (Event (EraRule rule era))
, Eq (Event (EraRule rule era))
, ToExpr (Event (EraRule rule era))
) =>
SomeSTSEvent (Event (EraRule rule era))
instance Eq (SomeSTSEvent era) where
SomeSTSEvent x == SomeSTSEvent y
| Just Refl <- testEquality (typeOf x) (typeOf y) = x == y
| otherwise = False
instance ToExpr (SomeSTSEvent era) where
toExpr (SomeSTSEvent ev) = App "SomeSTSEvent" [toExpr ev]
data ImpTestState era = ImpTestState
{ impNES :: !(NewEpochState era)
, impRootTxIn :: !(TxIn (EraCrypto era))
, impKeyPairs :: !(forall k. Map (KeyHash k (EraCrypto era)) (KeyPair k (EraCrypto era)))
, impByronKeyPairs :: !(Map (BootstrapAddress (EraCrypto era)) ByronKeyPair)
, impNativeScripts :: !(Map (ScriptHash (EraCrypto era)) (NativeScript era))
, impLastTick :: !SlotNo
, impGlobals :: !Globals
, impLog :: !(Doc ())
, impGen :: !QCGen
, impEvents :: [SomeSTSEvent era]
}
impLogL :: Lens' (ImpTestState era) (Doc ())
impLogL = lens impLog (\x y -> x {impLog = y})
impNESL :: Lens' (ImpTestState era) (NewEpochState era)
impNESL = lens impNES (\x y -> x {impNES = y})
impNESG :: SimpleGetter (ImpTestState era) (NewEpochState era)
impNESG = impNESL
impLastTickL :: Lens' (ImpTestState era) SlotNo
impLastTickL = lens impLastTick (\x y -> x {impLastTick = y})
impLastTickG :: SimpleGetter (ImpTestState era) SlotNo
impLastTickG = impLastTickL
impRootTxInL :: Lens' (ImpTestState era) (TxIn (EraCrypto era))
impRootTxInL = lens impRootTxIn (\x y -> x {impRootTxIn = y})
impKeyPairsG ::
SimpleGetter
(ImpTestState era)
(Map (KeyHash k (EraCrypto era)) (KeyPair k (EraCrypto era)))
impKeyPairsG = to impKeyPairs
impNativeScriptsL :: Lens' (ImpTestState era) (Map (ScriptHash (EraCrypto era)) (NativeScript era))
impNativeScriptsL = lens impNativeScripts (\x y -> x {impNativeScripts = y})
impNativeScriptsG ::
SimpleGetter (ImpTestState era) (Map (ScriptHash (EraCrypto era)) (NativeScript era))
impNativeScriptsG = impNativeScriptsL
impEventsL :: Lens' (ImpTestState era) [SomeSTSEvent era]
impEventsL = lens impEvents (\x y -> x {impEvents = y})
class
( Show (NewEpochState era)
, ToExpr (NewEpochState era)
, ToExpr (Tx era)
, ToExpr (TxOut era)
, ToExpr (PParams era)
, ToExpr (StashedAVVMAddresses era)
, ToExpr (GovState era)
, ToExpr (PParamsHKD StrictMaybe era)
, ToExpr (PParamsHKD Identity era)
, Show (TxOut era)
, Show (PParams era)
, Show (StashedAVVMAddresses era)
, Show (GovState era)
, Eq (TxOut era)
, Eq (PParams era)
, Eq (StashedAVVMAddresses era)
, Eq (GovState era)
, Eq (Event (EraRule "LEDGER" era))
, Eq (Event (EraRule "TICK" era))
, Signal (EraRule "LEDGER" era) ~ Tx era
, BaseM (EraRule "LEDGER" era) ~ ShelleyBase
, STS (EraRule "LEDGER" era)
, Signable
(DSIGN (EraCrypto era))
(Hash (HASH (EraCrypto era)) EraIndependentTxBody)
, DSIGN (EraCrypto era) ~ Ed25519DSIGN
, ToExpr (PredicateFailure (EraRule "LEDGER" era))
, ToExpr (PredicateFailure (EraRule "UTXOW" era))
, ToExpr (Event (EraRule "LEDGER" era))
, ToExpr (Event (EraRule "TICK" era))
, EraUTxO era
, ShelleyEraTxCert era
, State (EraRule "LEDGER" era) ~ LedgerState era
, Environment (EraRule "LEDGER" era) ~ LedgerEnv era
, EraGov era
, BaseM (EraRule "TICK" era) ~ ShelleyBase
, Signal (EraRule "TICK" era) ~ SlotNo
, Environment (EraRule "TICK" era) ~ ()
, State (EraRule "TICK" era) ~ NewEpochState era
, STS (EraRule "TICK" era)
, NFData (PredicateFailure (EraRule "TICK" era))
, NFData (StashedAVVMAddresses era)
, NFData (Tx era)
, NFData (VerKeyDSIGN (DSIGN (EraCrypto era)))
, NFData (PredicateFailure (EraRule "LEDGER" era))
, NFData (Event (EraRule "LEDGER" era))
, NFData (Event (EraRule "TICK" era))
, VRF.VRFAlgorithm (VRF (EraCrypto era))
, HashAlgorithm (HASH (EraCrypto era))
, DSIGNAlgorithm (DSIGN (EraCrypto era))
, EraRuleEvent "LEDGER" era ~ Event (EraRule "LEDGER" era)
, EraRuleEvent "TICK" era ~ Event (EraRule "TICK" era)
, Typeable (EraRuleEvent "LEDGER" era)
, Typeable (EraRuleEvent "TICK" era)
, ToExpr (EraRuleEvent "LEDGER" era)
, ToExpr (EraRuleEvent "TICK" era)
) =>
ShelleyEraImp era
where
initImpNES :: NewEpochState era
-- | Try to find a sufficient number of KeyPairs that would satisfy a native script.
-- Whenever script can't be satisfied, Nothing is returned
impSatisfyNativeScript ::
-- | Set of Witnesses that have already been satisfied
Set.Set (KeyHash 'Witness (EraCrypto era)) ->
NativeScript era ->
ImpTestM era (Maybe (Map (KeyHash 'Witness (EraCrypto era)) (KeyPair 'Witness (EraCrypto era))))
-- | This modifer should change not only the current PParams, but also the future
-- PParams. If the future PParams are not updated, then they will overwrite the
-- mofication of the current PParams at the next epoch.
modifyPParams ::
(PParams era -> PParams era) ->
ImpTestM era ()
modifyPParams f = modifyNES $ nesEsL . curPParamsEpochStateL %~ f
fixupTx :: HasCallStack => Tx era -> ImpTestM era (Tx era)
impLedgerEnv :: EraGov era => NewEpochState era -> ImpTestM era (LedgerEnv era)
impLedgerEnv nes = do
slotNo <- gets impLastTick
pure
LedgerEnv
{ ledgerSlotNo = slotNo
, ledgerPp = nes ^. nesEsL . curPParamsEpochStateL
, ledgerIx = TxIx 0
, ledgerAccount = nes ^. nesEsL . esAccountStateL
}
-- | Modify the previous PParams in the current state with the given function. For current
-- and future PParams, use `modifyPParams`
modifyPrevPParams ::
EraGov era =>
(PParams era -> PParams era) ->
ImpTestM era ()
modifyPrevPParams f = modifyNES $ nesEsL . prevPParamsEpochStateL %~ f
-- | Logs the current stake distribution
logStakeDistr :: ImpTestM era ()
logStakeDistr = do
stakeDistr <- getsNES $ nesEsL . epochStateIncrStakeDistrL
logEntry $ "Stake distr: " <> showExpr stakeDistr
mkHashVerKeyVRF ::
forall era.
ShelleyEraImp era =>
Integer ->
Hash (HASH (EraCrypto era)) (VerKeyVRF (EraCrypto era))
mkHashVerKeyVRF =
VRF.hashVerKeyVRF
. VRF.deriveVerKeyVRF
. VRF.genKeyVRF
. mkSeedFromBytes
. integralToByteStringN seedSize
where
seedSize = fromIntegral . seedSizeDSIGN $ Proxy @(DSIGN (EraCrypto era))
testKeyHash :: Crypto c => KeyHash kd c
testKeyHash = mkKeyHash (-1)
initShelleyImpNES ::
forall era.
( Default (StashedAVVMAddresses era)
, ShelleyEraImp era
) =>
NewEpochState era
initShelleyImpNES =
NewEpochState
{ stashedAVVMAddresses = def
, nesRu =
SJust $
startStep
(EpochSize 432_000)
(BlocksMade (Map.singleton testKeyHash 10))
epochState
(Coin 45)
(activeSlotCoeff testGlobals)
10
, nesPd =
PoolDistr $
Map.fromList
[
( testKeyHash
, IndividualPoolStake
1
(mkHashVerKeyVRF @era 0)
)
]
, nesEs = epochState
, nesEL = 0
, nesBprev = BlocksMade (Map.singleton testKeyHash 10)
, nesBcur = BlocksMade mempty
}
where
pp =
emptyPParams
& ppMinFeeAL .~ Coin 44
& ppMinFeeBL .~ Coin 155_381
epochState =
EpochState
{ esAccountState =
AccountState
{ asTreasury = Coin 10_000
, asReserves = Coin 1_000
}
, esSnapshots = emptySnapShots
, esLState =
LedgerState
{ lsUTxOState =
smartUTxOState
emptyPParams
utxo
zero
zero
emptyGovState
mempty
, lsCertState = def
}
, esNonMyopic = def
}
& prevPParamsEpochStateL .~ pp
& curPParamsEpochStateL .~ pp
utxo = mempty
mkTxId :: Crypto c => Int -> TxId c
mkTxId idx = TxId (mkDummySafeHash Proxy idx)
instance
( Crypto c
, NFData (SigDSIGN (DSIGN c))
, NFData (VerKeyDSIGN (DSIGN c))
, DSIGN c ~ Ed25519DSIGN
, Signable (DSIGN c) (Hash (HASH c) EraIndependentTxBody)
) =>
ShelleyEraImp (ShelleyEra c)
where
initImpNES = initShelleyImpNES
impSatisfyNativeScript providedVKeyHashes script = do
keyPairs <- gets impKeyPairs
let
satisfyMOf m []
| m <= 0 = Just mempty
| otherwise = Nothing
satisfyMOf m (x : xs) =
case satisfyScript x of
Nothing -> satisfyMOf m xs
Just kps -> do
kps' <- satisfyMOf (m - 1) xs
Just $ kps <> kps'
satisfyScript = \case
RequireSignature keyHash
| keyHash `Set.member` providedVKeyHashes -> Just mempty
| otherwise -> do
keyPair <- Map.lookup keyHash keyPairs
Just $ Map.singleton keyHash keyPair
RequireAllOf ss -> satisfyMOf (length ss) ss
RequireAnyOf ss -> satisfyMOf 1 ss
RequireMOf m ss -> satisfyMOf m ss
pure $ satisfyScript script
fixupTx = shelleyFixupTx
-- | Figure out all the Byron Addresses that need witnesses as well as all of the
-- KeyHashes for Shelley Key witnesses that are required.
impWitsVKeyNeeded ::
EraUTxO era =>
TxBody era ->
ImpTestM
era
( Set.Set (BootstrapAddress (EraCrypto era)) -- Byron Based Addresses
, Set.Set (KeyHash 'Witness (EraCrypto era)) -- Shelley Based KeyHashes
)
impWitsVKeyNeeded txBody = do
ls <- getsNES (nesEsL . esLStateL)
utxo <- getUTxO
let toBootAddr txIn = do
txOut <- txinLookup txIn utxo
txOut ^. bootAddrTxOutF
bootAddrs = Set.fromList $ mapMaybe toBootAddr $ Set.toList (txBody ^. spendableInputsTxBodyF)
bootKeyHashes = Set.map (coerceKeyRole . bootstrapKeyHash) bootAddrs
allKeyHashes =
getWitsVKeyNeeded (ls ^. lsCertStateL) (ls ^. lsUTxOStateL . utxosUtxoL) txBody
pure (bootAddrs, allKeyHashes Set.\\ bootKeyHashes)
data ImpTestEnv era = ImpTestEnv
{ iteState :: !(IORef (ImpTestState era))
, iteDoTxFixup :: !Bool
-- ^ This flag is used to toggle the fixing up of transactions. If it
-- is set to False then any transaction should be submitted as-is.
}
iteDoTxFixupL :: Lens' (ImpTestEnv era) Bool
iteDoTxFixupL = lens iteDoTxFixup (\x y -> x {iteDoTxFixup = y})
newtype ImpTestM era a = ImpTestM {unImpTestM :: ReaderT (ImpTestEnv era) (GenT IO) a}
deriving
( Functor
, Applicative
, Monad
, MonadIO
, MonadUnliftIO
, MonadReader (ImpTestEnv era)
)
instance
( Testable a
, ShelleyEraImp era
) =>
Testable (ImpTestM era a)
where
property m = property . fmap ioProperty . runGenT $ do
st <- liftIO mkImpState
res <- liftGen $ runImpTestGenM st m
liftIO $ fst <$> res
instance MonadWriter [SomeSTSEvent era] (ImpTestM era) where
writer (x, evs) = (impEventsL %= (<> evs)) $> x
listen act = do
oldEvs <- use impEventsL
impEventsL .= mempty
res <- act
newEvs <- use impEventsL
impEventsL .= oldEvs
pure (res, newEvs)
pass act = do
((a, f), evs) <- listen act
writer (a, f evs)
instance MonadFail (ImpTestM era) where
fail = assertFailure
instance MonadState (ImpTestState era) (ImpTestM era) where
get = ImpTestM $ do
liftIO . readIORef . iteState =<< ask
put x = ImpTestM $ do
liftIO . flip writeIORef x . iteState =<< ask
instance Example (ImpTestM era ()) where
type Arg (ImpTestM era ()) = ImpTestState era
evaluateExample impTest params =
evaluateExample (\s -> evalImpTestM (getParamsQCGen params) s impTest) params
instance (Arbitrary a, Show a) => Example (a -> ImpTestM era ()) where
type Arg (a -> ImpTestM era ()) = ImpTestState era
evaluateExample impTest params =
evaluateExample (\s -> property $ evalImpTestM (getParamsQCGen params) s . impTest) params
instance MonadGen (ImpTestM era) where
liftGen = ImpTestM . lift . liftGen
variant n (ImpTestM f) = ImpTestM $ ask >>= lift . variant n . runReaderT f
sized f = ImpTestM $ do
env <- ask
lift $ sized (\n -> runReaderT (unImpTestM (f n)) env)
resize n (ImpTestM f) = ImpTestM $ ask >>= lift . resize n . runReaderT f
choose = ImpTestM . lift . choose
instance HasStatefulGen (StateGenM (ImpTestState era)) (ImpTestM era) where
askStatefulGen = pure StateGenM
instance HasSubState (ImpTestState era) where
type SubState (ImpTestState era) = StateGen QCGen
getSubState = StateGen . impGen
setSubState s (StateGen g) = s {impGen = g}
getParamsQCGen :: Params -> Maybe (QCGen, Int)
getParamsQCGen params = replay (paramsQuickCheckArgs params)
evalImpTestGenM :: ImpTestState era -> ImpTestM era b -> Gen (IO b)
evalImpTestGenM impState = fmap (fmap fst) . runImpTestGenM impState
evalImpTestM :: Maybe (QCGen, Int) -> ImpTestState era -> ImpTestM era b -> IO b
evalImpTestM qc impState = fmap fst . runImpTestM qc impState
execImpTestGenM :: ImpTestState era -> ImpTestM era b -> Gen (IO (ImpTestState era))
execImpTestGenM impState = fmap (fmap snd) . runImpTestGenM impState
execImpTestM :: Maybe (QCGen, Int) -> ImpTestState era -> ImpTestM era b -> IO (ImpTestState era)
execImpTestM qc impState = fmap snd . runImpTestM qc impState
runImpTestGenM_ :: ImpTestState era -> ImpTestM era b -> Gen (IO ())
runImpTestGenM_ impState = fmap void . runImpTestGenM impState
runImpTestM_ :: Maybe (QCGen, Int) -> ImpTestState era -> ImpTestM era b -> IO ()
runImpTestM_ qc impState = void . runImpTestM qc impState
runImpTestGenM :: ImpTestState era -> ImpTestM era b -> Gen (IO (b, ImpTestState era))
runImpTestGenM impState m = MkGen $ \qcGen qcSz -> runImpTestM (Just (qcGen, qcSz)) impState m
runImpTestM :: Maybe (QCGen, Int) -> ImpTestState era -> ImpTestM era b -> IO (b, ImpTestState era)
runImpTestM mQCGen impState (ImpTestM m) = do
let
(qcGen, qcSize, impState') =
case fromMaybe (impGen impState, 30) mQCGen of
(initGen, sz) ->
case split initGen of
(qc, stdGen) -> (qc, sz, impState {impGen = stdGen})
ioRef <- newIORef impState'
let
env =
ImpTestEnv
{ iteState = ioRef
, iteDoTxFixup = True
}
res <-
unGenT (runReaderT m env) qcGen qcSize `catchAny` \exc -> do
logsDoc <- impLog <$> readIORef ioRef
let logs = renderString (layoutPretty defaultLayoutOptions logsDoc)
adjustHUnitExc header (HUnitFailure srcLoc failReason) =
toException $
HUnitFailure srcLoc $
case failReason of
Reason msg -> Reason $ logs <> "\n" <> header <> msg
ExpectedButGot Nothing expected got ->
ExpectedButGot (Just $ logs <> header) expected got
ExpectedButGot (Just msg) expected got ->
ExpectedButGot (Just (logs <> "\n" <> header <> msg)) expected got
newExc
| Just hUnitExc <- fromException exc =
adjustHUnitExc [] hUnitExc
| Just (ImpException ann excThrown) <- fromException exc =
let header = unlines $ zipWith (\n str -> replicate n ' ' <> str) [0, 2 ..] ann
in case fromException excThrown of
Nothing -> toException $ ImpException [logs, header] excThrown
Just hUnitExc -> adjustHUnitExc header hUnitExc
| otherwise = toException $ ImpException [logs] exc
throwIO newExc
endState <- readIORef ioRef
pure (res, endState)
runShelleyBase :: Globals -> ShelleyBase a -> a
runShelleyBase globals act = runIdentity $ runReaderT act globals
getRewardAccountAmount :: RewardAccount (EraCrypto era) -> ImpTestM era Coin
getRewardAccountAmount rewardAcount = do
umap <- getsNES $ nesEsL . epochStateUMapL
let cred = raCredential rewardAcount
case UMap.lookup cred (RewDepUView umap) of
Nothing -> assertFailure $ "Expected a reward account: " ++ show cred
Just RDPair {rdReward} -> pure $ fromCompact rdReward
lookupImpRootTxOut :: ImpTestM era (TxIn (EraCrypto era), TxOut era)
lookupImpRootTxOut = do
ImpTestState {impRootTxIn} <- get
utxo <- getUTxO
case txinLookup impRootTxIn utxo of
Nothing -> error "Root txId no longer points to an existing unspent output"
Just rootTxOut -> pure (impRootTxIn, rootTxOut)
impAddNativeScript ::
forall era.
EraScript era =>
NativeScript era ->
ImpTestM era (ScriptHash (EraCrypto era))
impAddNativeScript nativeScript = do
let script = fromNativeScript nativeScript
scriptHash = hashScript @era script
impNativeScriptsL %= Map.insert scriptHash nativeScript
pure scriptHash
impNativeScriptsRequired ::
EraUTxO era =>
Tx era ->
ImpTestM era (Map (ScriptHash (EraCrypto era)) (NativeScript era))
impNativeScriptsRequired tx = do
utxo <- getUTxO
ImpTestState {impNativeScripts} <- get
let needed = getScriptsNeeded utxo (tx ^. bodyTxL)
hashesNeeded = getScriptsHashesNeeded needed
pure $ impNativeScripts `Map.restrictKeys` hashesNeeded
-- | Modifies transaction by adding necessary scripts
addNativeScriptTxWits ::
ShelleyEraImp era =>
Tx era ->
ImpTestM era (Tx era)
addNativeScriptTxWits tx = do
scriptsRequired <- impNativeScriptsRequired tx
utxo <- getUTxO
let ScriptsProvided provided = getScriptsProvided utxo tx
scriptsToAdd = scriptsRequired Map.\\ provided
pure $
tx
& witsTxL . scriptTxWitsL <>~ fmap fromNativeScript scriptsToAdd
-- | Adds @TxWits@ that will satisfy all of the required key witnesses
updateAddrTxWits ::
( HasCallStack
, ShelleyEraImp era
) =>
Tx era ->
ImpTestM era (Tx era)
updateAddrTxWits tx = do
let txBody = tx ^. bodyTxL
txBodyHash = hashAnnotated txBody
(bootAddrs, witsVKeyNeeded) <- impWitsVKeyNeeded txBody
-- Shelley Based Addr Witnesses
let curAddrWitHashes = Set.map witVKeyHash $ tx ^. witsTxL . addrTxWitsL
extraKeyPairs <- mapM lookupKeyPair $ Set.toList (witsVKeyNeeded Set.\\ curAddrWitHashes)
let extraAddrVKeyWits = mkWitnessesVKey txBodyHash extraKeyPairs
addrWitHashes = curAddrWitHashes <> Set.map witVKeyHash extraAddrVKeyWits
-- Shelley Based Native Script Witnesses
scriptsRequired <- impNativeScriptsRequired tx
nativeScriptsKeyPairs <- mapM (impSatisfyNativeScript addrWitHashes) (Map.elems scriptsRequired)
let extraNativeScriptVKeyWits =
mkWitnessesVKey txBodyHash $ Map.elems (mconcat (catMaybes nativeScriptsKeyPairs))
-- Byron Based Witessed
let curBootAddrWitHashes = Set.map bootstrapWitKeyHash $ tx ^. witsTxL . bootAddrTxWitsL
bootAddrWitsNeeded =
[ bootAddr
| bootAddr <- Set.toList bootAddrs
, not (coerceKeyRole (bootstrapKeyHash bootAddr) `Set.member` curBootAddrWitHashes)
]
extraBootAddrWits <- forM bootAddrWitsNeeded $ \bootAddr@(BootstrapAddress byronAddr) -> do
ByronKeyPair _ signingKey <- lookupByronKeyPair bootAddr
let attrs = Byron.addrAttributes byronAddr
pure $ makeBootstrapWitness (extractHash txBodyHash) signingKey attrs
pure $
tx
& witsTxL . addrTxWitsL <>~ extraAddrVKeyWits <> extraNativeScriptVKeyWits
& witsTxL . bootAddrTxWitsL <>~ Set.fromList extraBootAddrWits
-- | This fixup step ensures that there are enough funds in the transaction.
addRootTxIn ::
EraTx era =>
Tx era ->
ImpTestM era (Tx era)
addRootTxIn tx = do
rootTxIn <- fst <$> lookupImpRootTxOut
pure $
tx
& bodyTxL . inputsTxBodyL %~ Set.insert rootTxIn
impNativeScriptKeyPairs ::
ShelleyEraImp era =>
Tx era ->
ImpTestM
era
(Map (KeyHash 'Witness (EraCrypto era)) (KeyPair 'Witness (EraCrypto era)))
impNativeScriptKeyPairs tx = do
scriptsRequired <- impNativeScriptsRequired tx
let nativeScripts = Map.elems scriptsRequired
curAddrWits = Set.map witVKeyHash $ tx ^. witsTxL . addrTxWitsL
keyPairs <- mapM (impSatisfyNativeScript curAddrWits) nativeScripts
pure . mconcat $ catMaybes keyPairs
fixupFees ::
(ShelleyEraImp era, HasCallStack) =>
Tx era ->
ImpTestM era (Tx era)
fixupFees tx = do
pp <- getsNES $ nesEsL . curPParamsEpochStateL
utxo <- getUTxO
certState <- getsNES $ nesEsL . esLStateL . lsCertStateL
kpSpending <- lookupKeyPair =<< freshKeyHash
kpStaking <- lookupKeyPair =<< freshKeyHash
nativeScriptKeyPairs <- impNativeScriptKeyPairs tx
let
nativeScriptKeyWits = Map.keysSet nativeScriptKeyPairs
consumedValue = consumed pp certState utxo (tx ^. bodyTxL)
producedValue = produced pp certState (tx ^. bodyTxL)
changeBeforeFee = consumedValue <-> producedValue
changeBeforeFeeTxOut =
mkBasicTxOut
(mkAddr (kpSpending, kpStaking))
changeBeforeFee
let
txNoWits = tx & bodyTxL . outputsTxBodyL %~ (:|> changeBeforeFeeTxOut)
outsBeforeFee = tx ^. bodyTxL . outputsTxBodyL
fee = calcMinFeeTxNativeScriptWits utxo pp txNoWits nativeScriptKeyWits
change = changeBeforeFeeTxOut ^. coinTxOutL <-> fee
changeTxOut = changeBeforeFeeTxOut & coinTxOutL .~ change
-- If the remainder is sufficently big we add it to outputs, otherwise we add the
-- extraneous coin to the fee and discard the remainder TxOut
txWithFee
| change >= getMinCoinTxOut pp changeTxOut =
txNoWits
& bodyTxL . outputsTxBodyL .~ (outsBeforeFee :|> changeTxOut)
& bodyTxL . feeTxBodyL .~ fee
| otherwise =
txNoWits
& bodyTxL . outputsTxBodyL .~ outsBeforeFee
& bodyTxL . feeTxBodyL .~ (fee <> changeTxOut ^. coinTxOutL)
pure txWithFee
shelleyFixupTx ::
forall era.
(ShelleyEraImp era, HasCallStack) =>
Tx era ->
ImpTestM era (Tx era)
shelleyFixupTx =
addNativeScriptTxWits
>=> addRootTxIn
>=> fixupFees
>=> updateAddrTxWits
>=> (\tx -> logFeeMismatch tx $> tx)
logFeeMismatch :: (EraGov era, EraUTxO era) => Tx era -> ImpTestM era ()
logFeeMismatch tx = do
pp <- getsNES $ nesEsL . curPParamsEpochStateL
utxo <- getsNES $ nesEsL . esLStateL . lsUTxOStateL . utxosUtxoL
let Coin feeUsed = tx ^. bodyTxL . feeTxBodyL
Coin feeMin = getMinFeeTxUtxo pp tx utxo
when (feeUsed /= feeMin) $ do
logEntry $
"Estimated fee " <> show feeUsed <> " while required fee is " <> show feeMin
submitTx_ :: (HasCallStack, ShelleyEraImp era) => Tx era -> ImpTestM era ()
submitTx_ = void . submitTx
submitTx :: (HasCallStack, ShelleyEraImp era) => Tx era -> ImpTestM era (Tx era)
submitTx tx = trySubmitTx tx >>= expectRightDeepExpr
trySubmitTx ::
forall era.
( ShelleyEraImp era
, HasCallStack
) =>
Tx era ->
ImpTestM era (Either (NonEmpty (PredicateFailure (EraRule "LEDGER" era))) (Tx era))
trySubmitTx tx = do
doFixup <- asks iteDoTxFixup
txFixed <-
if doFixup
then fixupTx tx
else pure tx
logToExpr txFixed
st <- gets impNES
lEnv <- impLedgerEnv st
ImpTestState {impRootTxIn} <- get
res <- tryRunImpRule @"LEDGER" lEnv (st ^. nesEsL . esLStateL) txFixed
let txId = TxId . hashAnnotated $ txFixed ^. bodyTxL
outsSize = SSeq.length $ txFixed ^. bodyTxL . outputsTxBodyL
rootIndex
| outsSize > 0 = outsSize - 1
| otherwise = error ("Expected at least 1 output after submitting tx: " <> show txId)
forM res $ \(st', events) -> do
tell $ fmap (SomeSTSEvent @era @"LEDGER") events
modify $ impNESL . nesEsL . esLStateL .~ st'
UTxO utxo <- getUTxO
-- This TxIn is in the utxo, and thus can be the new root, only if the transaction was phase2-valid.
-- Otherwise, no utxo with this id would have been created, and so we need to set the new root
-- to what it was before the submission.
let assumedNewRoot = TxIn txId (mkTxIxPartial (fromIntegral rootIndex))
let newRoot
| Map.member assumedNewRoot utxo = assumedNewRoot
| Map.member impRootTxIn utxo = impRootTxIn
| otherwise = error "Root not found in UTxO"
impRootTxInL .= newRoot
pure txFixed
-- | Submit a transaction that is expected to be rejected. The inputs and
-- outputs are automatically balanced.
submitFailingTx ::
( HasCallStack
, ShelleyEraImp era
) =>
Tx era ->
NonEmpty (PredicateFailure (EraRule "LEDGER" era)) ->
ImpTestM era ()
submitFailingTx tx expectedFailure = trySubmitTx tx >>= (`shouldBeLeftExpr` expectedFailure)
tryRunImpRule ::
forall rule era.
(STS (EraRule rule era), BaseM (EraRule rule era) ~ ShelleyBase) =>
Environment (EraRule rule era) ->
State (EraRule rule era) ->
Signal (EraRule rule era) ->
ImpTestM
era
( Either
(NonEmpty (PredicateFailure (EraRule rule era)))
(State (EraRule rule era), [Event (EraRule rule era)])
)
tryRunImpRule stsEnv stsState stsSignal = do
let trc = TRC (stsEnv, stsState, stsSignal)
globals <- use $ to impGlobals
let
stsOpts =
ApplySTSOpts
{ asoValidation = ValidateAll
, asoEvents = EPReturn
, asoAssertions = AssertionsAll
}
pure $ runShelleyBase globals (applySTSOptsEither @(EraRule rule era) stsOpts trc)
runImpRule ::
forall rule era.
( HasCallStack
, KnownSymbol rule
, STS (EraRule rule era)
, BaseM (EraRule rule era) ~ ShelleyBase
, NFData (State (EraRule rule era))
, NFData (Event (EraRule rule era))
, ToExpr (Event (EraRule rule era))
, Eq (Event (EraRule rule era))
, Typeable (Event (EraRule rule era))
) =>
Environment (EraRule rule era) ->
State (EraRule rule era) ->
Signal (EraRule rule era) ->
ImpTestM era (State (EraRule rule era))
runImpRule stsEnv stsState stsSignal = do
let ruleName = symbolVal (Proxy @rule)
(res, ev) <-
tryRunImpRule @rule stsEnv stsState stsSignal >>= \case
Left fs ->
assertFailure $
unlines $
("Failed to run " <> ruleName <> ":") : map show (toList fs)
Right res -> evaluateDeep res
tell $ fmap (SomeSTSEvent @era @rule) ev
pure res
-- | Runs the TICK rule once
passTick ::
forall era.
( HasCallStack
, ShelleyEraImp era
) =>
ImpTestM era ()
passTick = do
impLastTick <- gets impLastTick
curNES <- getsNES id