-
Notifications
You must be signed in to change notification settings - Fork 155
/
ImpTest.hs
1902 lines (1748 loc) · 65.6 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 DefaultSignatures #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FunctionalDependencies #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE NumericUnderscores #-}
{-# LANGUAGE OverloadedLists #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# 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,
impWitsVKeyNeeded,
modifyPrevPParams,
passEpoch,
passNEpochs,
passNEpochsChecking,
passTick,
freshKeyAddr,
freshKeyAddr_,
freshKeyHash,
freshKeyPair,
lookupKeyPair,
freshByronKeyHash,
freshBootstapAddress,
lookupByronKeyPair,
freshSafeHash,
freshKeyHashVRF,
submitTx,
submitTx_,
submitTxAnn,
submitTxAnn_,
submitFailingTx,
submitFailingTxM,
trySubmitTx,
modifyNES,
getProtVer,
getsNES,
getUTxO,
impAddNativeScript,
impAnn,
impAnnDoc,
impLogToExpr,
runImpRule,
tryRunImpRule,
tryRunImpRuleNoAssertions,
delegateStake,
registerRewardAccount,
registerStakeCredential,
getRewardAccountFor,
lookupReward,
poolParams,
registerPool,
registerPoolWithRewardAccount,
registerAndRetirePoolToMakeReward,
getRewardAccountAmount,
withImpState,
withImpStateModified,
shelleyFixupTx,
lookupImpRootTxOut,
sendValueTo,
sendCoinTo,
expectUTxOContent,
expectRegisteredRewardAddress,
expectNotRegisteredRewardAddress,
expectTreasury,
disableTreasuryExpansion,
updateAddrTxWits,
addNativeScriptTxWits,
addRootTxIn,
fixupTxOuts,
fixupFees,
fixupAuxDataHash,
impGetNativeScript,
impLookupUTxO,
defaultInitNewEpochState,
defaultInitImpTestState,
impEraStartEpochNo,
impSetSeed,
-- * Logging
Doc,
AnsiStyle,
logDoc,
logText,
logString,
logToExpr,
logStakeDistr,
logFeeMismatch,
-- * Combinators
withCustomFixup,
withFixup,
withNoFixup,
withPostFixup,
withPreFixup,
withCborRoundTripFailures,
impNESL,
impGlobalsL,
impLastTickG,
impKeyPairsG,
impNativeScriptsG,
produceScript,
advanceToPointOfNoReturn,
) where
import qualified Cardano.Chain.Common as Byron
import qualified Cardano.Chain.UTxO as Byron (empty)
import Cardano.Crypto.DSIGN (DSIGNAlgorithm (..), Ed25519DSIGN)
import Cardano.Crypto.Hash (HashAlgorithm)
import Cardano.Crypto.Hash.Blake2b (Blake2b_224)
import qualified Cardano.Crypto.VRF as VRF
import Cardano.Ledger.Address (
Addr (..),
BootstrapAddress (..),
RewardAccount (..),
bootstrapKeyHash,
)
import Cardano.Ledger.AuxiliaryData (AuxiliaryDataHash (..))
import Cardano.Ledger.BHeaderView (BHeaderView)
import Cardano.Ledger.BaseTypes
import Cardano.Ledger.Binary (DecCBOR, EncCBOR)
import Cardano.Ledger.Block (Block)
import Cardano.Ledger.CertState (certDStateL, dsUnifiedL)
import Cardano.Ledger.Coin (Coin (..))
import Cardano.Ledger.Credential (Credential (..), StakeReference (..), credToText)
import Cardano.Ledger.Crypto (Crypto (..))
import Cardano.Ledger.Genesis (EraGenesis (..), NoGenesis (..))
import Cardano.Ledger.Keys (
HasKeyRole (..),
Hash,
KeyHash,
KeyRole (..),
VerKeyVRF,
asWitness,
bootstrapWitKeyHash,
hashKey,
makeBootstrapWitness,
witVKeyHash,
)
import Cardano.Ledger.PoolParams (PoolParams (..))
import Cardano.Ledger.SafeHash (HashAnnotated (..), SafeHash, extractHash)
import Cardano.Ledger.Shelley (ShelleyEra)
import Cardano.Ledger.Shelley.API.ByronTranslation (translateToShelleyLedgerStateFromUtxo)
import Cardano.Ledger.Shelley.AdaPots (sumAdaPots, totalAdaPotsES)
import Cardano.Ledger.Shelley.Core
import Cardano.Ledger.Shelley.Genesis (
ShelleyGenesis (..),
describeValidationErr,
fromNominalDiffTimeMicro,
mkShelleyGlobals,
validateGenesis,
)
import Cardano.Ledger.Shelley.LedgerState (
LedgerState (..),
NewEpochState (..),
StashedAVVMAddresses,
asTreasuryL,
consumed,
curPParamsEpochStateL,
epochStateIncrStakeDistrL,
epochStateUMapL,
esAccountStateL,
esLStateL,
lsCertStateL,
lsUTxOStateL,
nesELL,
nesEsL,
prevPParamsEpochStateL,
produced,
utxosDonationL,
utxosUtxoL,
)
import Cardano.Ledger.Shelley.Rules (
BbodyEnv (..),
LedgerEnv (..),
ShelleyBbodyState,
)
import Cardano.Ledger.Shelley.Scripts (
ShelleyEraScript,
pattern RequireAllOf,
pattern RequireAnyOf,
pattern RequireMOf,
pattern RequireSignature,
)
import Cardano.Ledger.Shelley.Translation (toFromByronTranslationContext)
import Cardano.Ledger.Slot (epochInfoFirst, getTheSlotOfNoReturn)
import Cardano.Ledger.Tools (
calcMinFeeTxNativeScriptWits,
setMinCoinTxOut,
)
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 Cardano.Slotting.EpochInfo (fixedEpochInfo)
import Cardano.Slotting.Time (mkSlotLength)
import Control.Monad (forM)
import Control.Monad.IO.Class
import Control.Monad.Reader (MonadReader (..), asks)
import Control.Monad.State.Strict (MonadState (..), StateT, evalStateT, gets, modify)
import Control.Monad.Trans.Fail.String (errorFail)
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.Bifunctor (first)
import Data.Coerce (coerce)
import Data.Data (Proxy (..), type (:~:) (..))
import Data.Default.Class (Default (..))
import Data.Foldable (toList, traverse_)
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 Data.Text (Text)
import qualified Data.Text as T
import Data.Time.Format.ISO8601 (iso8601ParseM)
import Data.TreeDiff (ansiWlExpr)
import Data.Type.Equality (TestEquality (..))
import Data.Void
import GHC.Stack (CallStack, 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 (..),
annotate,
hcat,
indent,
line,
vsep,
)
import Prettyprinter.Render.Terminal (AnsiStyle, Color (..), color)
import System.Random
import qualified System.Random as Random
import Test.Cardano.Ledger.Binary.RoundTrip (roundTripCborRangeFailureExpectation)
import Test.Cardano.Ledger.Binary.TreeDiff (srcLocToLocation)
import Test.Cardano.Ledger.Core.Arbitrary ()
import Test.Cardano.Ledger.Core.Binary.RoundTrip (roundTripEraExpectation)
import Test.Cardano.Ledger.Core.KeyPair (
ByronKeyPair (..),
KeyPair (..),
mkAddr,
mkWitnessesVKey,
)
import Test.Cardano.Ledger.Core.Rational ((%!))
import Test.Cardano.Ledger.Core.Utils (mkDummySafeHash, 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,
Result (..),
paramsQuickCheckArgs,
)
import qualified Test.Hspec.Core.Spec as H
import Test.QuickCheck.Gen (Gen (..))
import Test.QuickCheck.Random (QCGen (..), integerVariant, 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 :: !(Map (KeyHash 'Witness (EraCrypto era)) (KeyPair 'Witness (EraCrypto era)))
, impByronKeyPairs :: !(Map (BootstrapAddress (EraCrypto era)) ByronKeyPair)
, impNativeScripts :: !(Map (ScriptHash (EraCrypto era)) (NativeScript era))
, impLastTick :: !SlotNo
, impGlobals :: !Globals
, impLog :: !(Doc AnsiStyle)
, impGen :: !QCGen
, impEvents :: [SomeSTSEvent era]
}
-- | This is a preliminary state that is used to prepare the actual `ImpTestState`
data ImpPrepState c = ImpPrepState
{ impPrepKeyPairs :: !(Map (KeyHash 'Witness c) (KeyPair 'Witness c))
, impPrepByronKeyPairs :: !(Map (BootstrapAddress c) ByronKeyPair)
, impPrepGen :: !QCGen
}
instance HasSubState (ImpPrepState era) where
type SubState (ImpPrepState era) = StateGen QCGen
getSubState = StateGen . impPrepGen
setSubState s (StateGen g) = s {impPrepGen = g}
class Crypto c => HasKeyPairs t c | t -> c where
keyPairsL :: Lens' t (Map (KeyHash 'Witness c) (KeyPair 'Witness c))
keyPairsByronL :: Lens' t (Map (BootstrapAddress c) ByronKeyPair)
instance (Era era, c ~ EraCrypto era) => HasKeyPairs (ImpTestState era) c where
keyPairsL = lens impKeyPairs (\x y -> x {impKeyPairs = y})
keyPairsByronL = lens impByronKeyPairs (\x y -> x {impByronKeyPairs = y})
instance Crypto c => HasKeyPairs (ImpPrepState c) c where
keyPairsL = lens impPrepKeyPairs (\x y -> x {impPrepKeyPairs = y})
keyPairsByronL = lens impPrepByronKeyPairs (\x y -> x {impPrepByronKeyPairs = y})
instance Monad m => HasStatefulGen (StateGenM (ImpPrepState era)) (StateT (ImpPrepState era) m) where
askStatefulGen = pure StateGenM
impGlobalsL :: Lens' (ImpTestState era) Globals
impGlobalsL = lens impGlobals (\x y -> x {impGlobals = y})
impLogL :: Lens' (ImpTestState era) (Doc AnsiStyle)
impLogL = lens impLog (\x y -> x {impLog = y})
impNESL :: Lens' (ImpTestState era) (NewEpochState era)
impNESL = lens impNES (\x y -> x {impNES = y})
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 'Witness (EraCrypto era)) (KeyPair 'Witness (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
( EraGov era
, EraUTxO era
, EraTxOut era
, EraPParams era
, ShelleyEraTxCert era
, ShelleyEraScript era
, ToExpr (Tx era)
, NFData (Tx era)
, ToExpr (TxBody era)
, ToExpr (TxOut era)
, ToExpr (Value era)
, ToExpr (PParams era)
, ToExpr (PParamsHKD Identity era)
, ToExpr (PParamsHKD StrictMaybe era)
, Show (NewEpochState era)
, ToExpr (NewEpochState era)
, ToExpr (GovState era)
, Eq (StashedAVVMAddresses era)
, Show (StashedAVVMAddresses era)
, ToExpr (StashedAVVMAddresses era)
, NFData (StashedAVVMAddresses era)
, Default (StashedAVVMAddresses era)
, -- For BBODY rule
STS (EraRule "BBODY" era)
, BaseM (EraRule "BBODY" era) ~ ShelleyBase
, Environment (EraRule "BBODY" era) ~ BbodyEnv era
, State (EraRule "BBODY" era) ~ ShelleyBbodyState era
, Signal (EraRule "BBODY" era) ~ Block (BHeaderView (EraCrypto era)) era
, State (EraRule "LEDGERS" era) ~ LedgerState era
, -- For the LEDGER rule
STS (EraRule "LEDGER" era)
, BaseM (EraRule "LEDGER" era) ~ ShelleyBase
, Signal (EraRule "LEDGER" era) ~ Tx era
, State (EraRule "LEDGER" era) ~ LedgerState era
, Environment (EraRule "LEDGER" era) ~ LedgerEnv era
, Eq (PredicateFailure (EraRule "LEDGER" era))
, Show (PredicateFailure (EraRule "LEDGER" era))
, ToExpr (PredicateFailure (EraRule "LEDGER" era))
, NFData (PredicateFailure (EraRule "LEDGER" era))
, EncCBOR (PredicateFailure (EraRule "LEDGER" era))
, DecCBOR (PredicateFailure (EraRule "LEDGER" era))
, EraRuleEvent "LEDGER" era ~ Event (EraRule "LEDGER" era)
, Eq (EraRuleEvent "LEDGER" era)
, ToExpr (EraRuleEvent "LEDGER" era)
, NFData (EraRuleEvent "LEDGER" era)
, Typeable (EraRuleEvent "LEDGER" era)
, -- For the TICK rule
STS (EraRule "TICK" era)
, BaseM (EraRule "TICK" era) ~ ShelleyBase
, Signal (EraRule "TICK" era) ~ SlotNo
, State (EraRule "TICK" era) ~ NewEpochState era
, Environment (EraRule "TICK" era) ~ ()
, NFData (PredicateFailure (EraRule "TICK" era))
, EraRuleEvent "TICK" era ~ Event (EraRule "TICK" era)
, Eq (EraRuleEvent "TICK" era)
, ToExpr (EraRuleEvent "TICK" era)
, NFData (EraRuleEvent "TICK" era)
, Typeable (EraRuleEvent "TICK" era)
, ToExpr (PredicateFailure (EraRule "UTXOW" era))
, -- Necessary Crypto
DSIGN (EraCrypto era) ~ Ed25519DSIGN
, NFData (VerKeyDSIGN (DSIGN (EraCrypto era)))
, VRF.VRFAlgorithm (VRF (EraCrypto era))
, HashAlgorithm (HASH (EraCrypto era))
, DSIGNAlgorithm (DSIGN (EraCrypto era))
, Signable (DSIGN (EraCrypto era)) (Hash (EraCrypto era) EraIndependentTxBody)
, ADDRHASH (EraCrypto era) ~ Blake2b_224
) =>
ShelleyEraImp era
where
initGenesis ::
(HasKeyPairs s (EraCrypto era), MonadState s m, HasStatefulGen (StateGenM s) m, MonadFail m) =>
m (Genesis era)
default initGenesis ::
(Monad m, Genesis era ~ NoGenesis era) =>
m (Genesis era)
initGenesis = pure NoGenesis
initNewEpochState ::
(HasKeyPairs s (EraCrypto era), MonadState s m, HasStatefulGen (StateGenM s) m, MonadFail m) =>
m (NewEpochState era)
default initNewEpochState ::
( HasKeyPairs s (EraCrypto era)
, MonadState s m
, HasStatefulGen (StateGenM s) m
, MonadFail m
, ShelleyEraImp (PreviousEra era)
, TranslateEra era NewEpochState
, TranslationError era NewEpochState ~ Void
, TranslationContext era ~ Genesis era
, EraCrypto era ~ EraCrypto (PreviousEra era)
) =>
m (NewEpochState era)
initNewEpochState = defaultInitNewEpochState id
initImpTestState ::
( HasKeyPairs s (EraCrypto era)
, MonadState s m
, HasSubState s
, SubState s ~ StateGen QCGen
, HasStatefulGen (StateGenM s) m
, MonadFail m
) =>
m (ImpTestState era)
initImpTestState = initNewEpochState >>= defaultInitImpTestState
-- | 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)
defaultInitNewEpochState ::
forall era s m.
( MonadState s m
, HasKeyPairs s (EraCrypto era)
, HasStatefulGen (StateGenM s) m
, MonadFail m
, ShelleyEraImp era
, ShelleyEraImp (PreviousEra era)
, TranslateEra era NewEpochState
, TranslationError era NewEpochState ~ Void
, TranslationContext era ~ Genesis era
, EraCrypto era ~ EraCrypto (PreviousEra era)
) =>
(NewEpochState (PreviousEra era) -> NewEpochState (PreviousEra era)) ->
m (NewEpochState era)
defaultInitNewEpochState modifyPrevEraNewEpochState = do
genesis <- initGenesis @era
nes <- initNewEpochState @(PreviousEra era)
let majProtVer = eraProtVerLow @era
-- We need to set the protocol version for the current era and for debugging
-- purposes we start the era at the epoch number that matches the protocol version
-- times a 100. However, because this is the NewEpochState from the previous era, we
-- initialize it with futurePParams preset and epoch number that is one behind the
-- beginning of this era. Note that all imp tests will start with a TICK, in order
-- for theses changes to be applied.
prevEraNewEpochState =
nes
& nesEsL . curPParamsEpochStateL . ppProtocolVersionL .~ ProtVer majProtVer 0
& nesELL .~ pred (impEraStartEpochNo @era)
pure $ translateEra' genesis $ modifyPrevEraNewEpochState prevEraNewEpochState
-- | For debugging purposes we start the era at the epoch number that matches the starting
-- protocol version for the era times a 100
impEraStartEpochNo :: forall era. Era era => EpochNo
impEraStartEpochNo = EpochNo (getVersion majProtVer * 100)
where
majProtVer = eraProtVerLow @era
defaultInitImpTestState ::
forall era s m.
( EraGov era
, EraTxOut era
, DSIGN (EraCrypto era) ~ Ed25519DSIGN
, ADDRHASH (EraCrypto era) ~ Blake2b_224
, HasKeyPairs s (EraCrypto era)
, MonadState s m
, HasStatefulGen (StateGenM s) m
, MonadFail m
, HasSubState s
, SubState s ~ StateGen QCGen
) =>
NewEpochState era ->
m (ImpTestState era)
defaultInitImpTestState nes = do
shelleyGenesis <- initGenesis @(ShelleyEra (EraCrypto era))
rootKeyHash <- freshKeyHash
let
rootAddr :: Addr (EraCrypto era)
rootAddr = Addr Testnet (KeyHashObj rootKeyHash) StakeRefNull
rootTxOut :: TxOut era
rootTxOut = mkBasicTxOut rootAddr $ inject rootCoin
rootCoin = Coin (toInteger (sgMaxLovelaceSupply shelleyGenesis))
rootTxIn :: TxIn (EraCrypto era)
rootTxIn = TxIn (mkTxId 0) minBound
nesWithRoot =
nes & nesEsL . esLStateL . lsUTxOStateL . utxosUtxoL <>~ UTxO (Map.singleton rootTxIn rootTxOut)
prepState <- get
let StateGen qcGen = getSubState prepState
epochInfoE =
fixedEpochInfo
(sgEpochLength shelleyGenesis)
(mkSlotLength . fromNominalDiffTimeMicro $ sgSlotLength shelleyGenesis)
globals = mkShelleyGlobals shelleyGenesis epochInfoE
epochNo = nesWithRoot ^. nesELL
slotNo = runIdentity $ runReaderT (epochInfoFirst (epochInfoPure globals) epochNo) globals
pure $
ImpTestState
{ impNES = nesWithRoot
, impRootTxIn = rootTxIn
, impKeyPairs = prepState ^. keyPairsL
, impByronKeyPairs = prepState ^. keyPairsByronL
, impNativeScripts = mempty
, impLastTick = slotNo
, impGlobals = globals
, impLog = mempty
, impGen = qcGen
, impEvents = mempty
}
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
, ledgerMempool = False
}
-- | 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 :: HasCallStack => ImpTestM era ()
logStakeDistr = do
stakeDistr <- getsNES $ nesEsL . epochStateIncrStakeDistrL
logDoc $ "Stake distr: " <> ansiExpr stakeDistr
mkTxId :: Crypto c => Int -> TxId c
mkTxId idx = TxId (mkDummySafeHash Proxy idx)
instance
( Crypto c
, NFData (SigDSIGN (DSIGN c))
, NFData (VerKeyDSIGN (DSIGN c))
, ADDRHASH c ~ Blake2b_224
, DSIGN c ~ Ed25519DSIGN
, Signable (DSIGN c) (Hash c EraIndependentTxBody)
, ShelleyEraScript (ShelleyEra c)
) =>
ShelleyEraImp (ShelleyEra c)
where
initGenesis = do
let
gen =
ShelleyGenesis
{ sgSystemStart = errorFail $ iso8601ParseM "2017-09-23T21:44:51Z"
, sgNetworkMagic = 123456 -- Mainnet value: 764824073
, sgNetworkId = Testnet
, sgActiveSlotsCoeff = 20 %! 100 -- Mainnet value: 5 %! 100
, sgSecurityParam = 108 -- Mainnet value: 2160
, sgEpochLength = 4320 -- Mainnet value: 432000
, sgSlotsPerKESPeriod = 129600
, sgMaxKESEvolutions = 62
, sgSlotLength = 1
, sgUpdateQuorum = 5
, sgMaxLovelaceSupply = 45_000_000_000_000_000
, sgProtocolParams =
emptyPParams
& ppMinFeeAL .~ Coin 44
& ppMinFeeBL .~ Coin 155_381
& ppMaxBBSizeL .~ 65536
& ppMaxTxSizeL .~ 16384
& ppKeyDepositL .~ Coin 2_000_000
& ppPoolDepositL .~ Coin 500_000_000
& ppEMaxL .~ EpochInterval 18
& ppNOptL .~ 150
& ppA0L .~ (3 %! 10)
& ppRhoL .~ (3 %! 1000)
& ppTauL .~ (2 %! 10)
& ppDL .~ (1 %! 1)
& ppExtraEntropyL .~ NeutralNonce
& ppMinUTxOValueL .~ Coin 2_000_000
& ppMinPoolCostL .~ Coin 340_000_000
, -- TODO: Add a top level definition and add private keys to ImpState:
sgGenDelegs = mempty
, sgInitialFunds = mempty
, sgStaking = mempty
}
case validateGenesis gen of
Right () -> pure gen
Left errs -> fail . T.unpack . T.unlines $ map describeValidationErr errs
initNewEpochState = do
shelleyGenesis <- initGenesis @(ShelleyEra c)
let transContext = toFromByronTranslationContext shelleyGenesis
startEpochNo = impEraStartEpochNo @(ShelleyEra c)
pure $ translateToShelleyLedgerStateFromUtxo transContext startEpochNo Byron.empty
impSatisfyNativeScript providedVKeyHashes script = do
keyPairs <- gets impKeyPairs
let
satisfyMOf m Empty
| 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
_ -> error "Impossible: All NativeScripts should have been accounted for"
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))
, iteFixup :: Tx era -> ImpTestM era (Tx era)
, iteQuickCheckSize :: !Int
, iteCborRoundTripFailures :: !Bool
-- ^ Expect failures in CBOR round trip serialization tests for predicate failures
}
iteFixupL :: Lens' (ImpTestEnv era) (Tx era -> ImpTestM era (Tx era))
iteFixupL = lens iteFixup (\x y -> x {iteFixup = y})
iteCborRoundTripFailuresL :: Lens' (ImpTestEnv era) Bool
iteCborRoundTripFailuresL = lens iteCborRoundTripFailures (\x y -> x {iteCborRoundTripFailures = y})
newtype ImpTestM era a = ImpTestM {unImpTestM :: ReaderT (ImpTestEnv era) IO a}
deriving
( Functor
, Applicative
, Monad
, MonadIO
, MonadUnliftIO
, MonadReader (ImpTestEnv era)
)
instance (Testable a, ShelleyEraImp era) => Testable (ImpTestM era a) where
property m = property $ MkGen $ \qcGen qcSize ->
ioProperty $ do
impTestState <- evalStateT initImpTestState (emptyImpPrepState @(EraCrypto era) (Just qcGen))
evalImpTestM (Just qcSize) impTestState m
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 (ShelleyEraImp era, Testable prop) => Example (ImpTestM era prop) where
type Arg (ImpTestM era prop) = ImpTestState era
evaluateExample impTest =
evaluateExample (\() -> impTest)
instance (ShelleyEraImp era, Arbitrary a, Show a, Testable prop) => Example (a -> ImpTestM era prop) where
type Arg (a -> ImpTestM era prop) = ImpTestState era
evaluateExample impTest params hook progressCallback =
let runImpTestExample s = property $ \x -> do
let args = paramsQuickCheckArgs params
(r, testable, logs) <- uncurry evalImpTestM (applyParamsQCGen params s) $ do
t <- impTest x
qcSize <- asks iteQuickCheckSize
StateGen qcGen <- subStateM split
logs <- gets impLog
pure (Just (qcGen, qcSize), t, logs)
let params' = params {paramsQuickCheckArgs = args {replay = r, chatty = False}}
res <-
evaluateExample
(counterexample (ansiDocToString logs) testable)
params'
(\f -> hook (\_st -> f ()))
progressCallback
void $ throwIO $ resultStatus res
in evaluateExample runImpTestExample params hook progressCallback
instance MonadGen (ImpTestM era) where
liftGen (MkGen f) = do
qcSize <- asks iteQuickCheckSize
StateGen qcGen <- subStateM split
pure $ f qcGen qcSize
variant n action = do
subStateM (\(StateGen qcGen) -> ((), StateGen (integerVariant (toInteger n) qcGen)))
action
sized f = do
qcSize <- asks iteQuickCheckSize
f qcSize
resize n = local (\env -> env {iteQuickCheckSize = n})
choose r = subStateM (Random.randomR r)
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}
-- | Override the QuickCheck generator using a fixed seed.
impSetSeed :: Int -> ImpTestM era ()
impSetSeed seed = setSubStateM $ StateGen $ mkQCGen seed
applyParamsQCGen :: Params -> ImpTestState era -> (Maybe Int, ImpTestState era)
applyParamsQCGen params impTestState =
case replay (paramsQuickCheckArgs params) of
Nothing -> (Nothing, impTestState)
Just (qcGen, qcSize) -> (Just qcSize, mixinCurrentGen impTestState qcGen)
-- | Instead of reqplacing the current QC generator in the state, we use the current and
-- the supplied to make the new generator
mixinCurrentGen :: ImpTestState era -> QCGen -> ImpTestState era
mixinCurrentGen impTestState qcGen =
impTestState {impGen = integerVariant (fst (Random.random (impGen impTestState))) qcGen}
evalImpTestGenM :: ShelleyEraImp era => ImpTestState era -> ImpTestM era b -> Gen (IO b)
evalImpTestGenM impState = fmap (fmap fst) . runImpTestGenM impState
evalImpTestM ::
ShelleyEraImp era => Maybe Int -> ImpTestState era -> ImpTestM era b -> IO b
evalImpTestM qc impState = fmap fst . runImpTestM qc impState
execImpTestGenM ::
ShelleyEraImp era => ImpTestState era -> ImpTestM era b -> Gen (IO (ImpTestState era))
execImpTestGenM impState = fmap (fmap snd) . runImpTestGenM impState
emptyImpPrepState :: Maybe QCGen -> ImpPrepState c
emptyImpPrepState mQCGen =
ImpPrepState
{ impPrepKeyPairs = mempty
, impPrepByronKeyPairs = mempty
, impPrepGen = fromMaybe (mkQCGen 2024) mQCGen
}
execImpTestM ::
ShelleyEraImp era =>
Maybe Int ->
ImpTestState era ->
ImpTestM era b ->
IO (ImpTestState era)
execImpTestM qcSize impState = fmap snd . runImpTestM qcSize impState
runImpTestGenM_ :: ShelleyEraImp era => ImpTestState era -> ImpTestM era b -> Gen (IO ())
runImpTestGenM_ impState = fmap void . runImpTestGenM impState
runImpTestM_ ::
ShelleyEraImp era => Maybe Int -> ImpTestState era -> ImpTestM era b -> IO ()
runImpTestM_ qcSize impState = void . runImpTestM qcSize impState
runImpTestGenM ::
ShelleyEraImp era => ImpTestState era -> ImpTestM era b -> Gen (IO (b, ImpTestState era))
runImpTestGenM impState m =
MkGen $ \qcGen qcSz -> runImpTestM (Just qcSz) (mixinCurrentGen impState qcGen) m
runImpTestM ::
ShelleyEraImp era =>
Maybe Int ->
ImpTestState era ->
ImpTestM era b ->
IO (b, ImpTestState era)
runImpTestM mQCSize impState action = do
let qcSize = fromMaybe 30 mQCSize
ioRef <- newIORef impState
let
env =
ImpTestEnv
{ iteState = ioRef
, iteFixup = fixupTx
, iteQuickCheckSize = qcSize
, iteCborRoundTripFailures = True
}
res <-
-- There is an important step here of running TICK rule. This is necessary as a final
-- step of `era` initialization, because on the very first TICK of an era the
-- `futurePParams` are applied and the epoch number is updated to the first epoch
-- number of the current era
runReaderT (unImpTestM (passTick >> action)) env `catchAny` \exc -> do
logs <- impLog <$> readIORef ioRef
let x <?> my = case my of
Nothing -> x
Just y -> x ++ [pretty y]
uncaughtException header excThrown =
H.ColorizedReason $
ansiDocToString $
vsep $
header ++ [pretty $ "Uncaught Exception: " <> displayException excThrown]
fromHUnitFailure header (HUnitFailure mSrcLoc failReason) =
case failReason of
Reason msg ->
H.Failure (srcLocToLocation <$> mSrcLoc) $
H.ColorizedReason $
ansiDocToString $
vsep $
header ++ [annotate (color Red) (pretty msg)]
ExpectedButGot mMsg expected got ->
H.Failure (srcLocToLocation <$> mSrcLoc) $
H.ExpectedButGot (Just (ansiDocToString $ vsep (header <?> mMsg))) expected got
adjustFailureReason header = \case
H.Failure mLoc failureReason ->
H.Failure mLoc $
case failureReason of
H.NoReason ->
H.ColorizedReason $ ansiDocToString $ vsep $ header ++ [annotate (color Red) "NoReason"]
H.Reason msg ->
H.ColorizedReason $ ansiDocToString $ vsep $ header ++ [annotate (color Red) (pretty msg)]
H.ColorizedReason msg ->
H.ColorizedReason $ ansiDocToString $ vsep $ header ++ [pretty msg]
H.ExpectedButGot mPreface expected actual ->
H.ExpectedButGot (Just (ansiDocToString $ vsep (header <?> mPreface))) expected actual
H.Error mInfo excThrown -> uncaughtException (header <?> mInfo) excThrown
result -> result
newExc
| Just hUnitExc <- fromException exc = fromHUnitFailure [logs] hUnitExc
| Just hspecFailure <- fromException exc = adjustFailureReason [logs] hspecFailure
| Just (ImpException ann excThrown) <- fromException exc =
let annLen = length ann
header =
logs
: [ let prefix
| annLen <= 1 = "╺╸"
| n <= 0 = "┏╸"
| n + 1 == annLen = indent (n - 1) "┗━╸"
| otherwise = indent (n - 1) "┗┳╸"
in annotate (color Red) prefix <> annotate (color Yellow) a
| (n, a) <- zip [0 ..] ann
]
++ [""]
in case fromException excThrown of
Just hUnitExc -> fromHUnitFailure header hUnitExc
Nothing ->
case fromException excThrown of
Just hspecFailure -> adjustFailureReason header hspecFailure
Nothing -> H.Failure Nothing $ uncaughtException header excThrown
| otherwise = H.Failure Nothing $ uncaughtException [logs] exc
throwIO newExc
endState <- readIORef ioRef