-
Notifications
You must be signed in to change notification settings - Fork 211
/
TypesSpec.hs
1355 lines (1203 loc) · 50.9 KB
/
TypesSpec.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 DataKinds #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Cardano.Wallet.Primitive.TypesSpec
( spec
) where
import Prelude
import Cardano.Address.Derivation
( XPrv )
import Cardano.Pool.Types
( PoolId (..), PoolOwner (..), decodePoolIdBech32, encodePoolIdBech32 )
import Cardano.Wallet.Gen
( genActiveSlotCoefficient
, genBlockHeader
, genNestedTxMetadata
, genSlotNo
, shrinkActiveSlotCoefficient
, shrinkSlotNo
, shrinkTxMetadata
)
import Cardano.Wallet.Primitive.AddressDerivation
( Depth (..), WalletKey (..), digest, publicKey )
import Cardano.Wallet.Primitive.AddressDerivation.Shelley
( ShelleyKey (..), generateKeyFromSeed )
import Cardano.Wallet.Primitive.Slotting.Legacy
( SlotParameters (..)
, epochStartTime
, flatSlot
, fromFlatSlot
, slotAt'
, slotCeiling
, slotDifference
, slotFloor
, slotMinBound
, slotPred
, slotRangeFromTimeRange'
, slotStartTime
, slotSucc
)
import Cardano.Wallet.Primitive.SyncProgress
( SyncTolerance (..), mkSyncTolerance )
import Cardano.Wallet.Primitive.Types
( ActiveSlotCoefficient (..)
, Block (..)
, BlockHeader (..)
, EpochLength (..)
, EpochNo (..)
, FeePolicy (..)
, LinearFunction (..)
, Range (..)
, RangeBound (..)
, SlotId (..)
, SlotInEpoch (..)
, SlotLength (..)
, SlotNo (..)
, StartTime (..)
, WalletId (..)
, WalletName (..)
, isAfterRange
, isBeforeRange
, isSubrangeOf
, isWithinRange
, mapRangeLowerBound
, mapRangeUpperBound
, rangeHasLowerBound
, rangeHasUpperBound
, rangeIsFinite
, rangeIsSingleton
, rangeIsValid
, rangeLowerBound
, rangeUpperBound
, unsafeEpochNo
, walletNameMaxLength
, walletNameMinLength
, wholeRange
)
import Cardano.Wallet.Primitive.Types.Address
( Address (..), AddressState (..) )
import Cardano.Wallet.Primitive.Types.Coin
( Coin (..) )
import Cardano.Wallet.Primitive.Types.Coin.Gen
( genCoin )
import Cardano.Wallet.Primitive.Types.Hash
( Hash (..) )
import Cardano.Wallet.Primitive.Types.RewardAccount
( RewardAccount (..) )
import Cardano.Wallet.Primitive.Types.Tx.Gen
( genTx, shrinkTx )
import Cardano.Wallet.Primitive.Types.Tx.Tx
( Tx (..), TxMetadata (..), TxMetadataValue (..) )
import Cardano.Wallet.Primitive.Types.Tx.TxIn
( TxIn (..) )
import Cardano.Wallet.Primitive.Types.Tx.TxMeta
( Direction (..), TxMeta (..), TxStatus (..) )
import Cardano.Wallet.Primitive.Types.Tx.TxOut
( TxOut (..) )
import Cardano.Wallet.Primitive.Types.UTxO
( UTxO (..)
, balance
, dom
, excluding
, isSubsetOf
, restrictedBy
, restrictedTo
)
import Cardano.Wallet.Primitive.Types.UTxOStatistics
( HistogramBar (..), UTxOStatistics (..) )
import Cardano.Wallet.Unsafe
( someDummyMnemonic, unsafeFromHex )
import Cardano.Wallet.Util
( ShowFmt (..) )
import Control.Monad
( forM_, replicateM )
import Crypto.Hash
( hash )
import Data.Either
( isRight )
import Data.Function
( (&) )
import Data.Function.Utils
( applyN )
import Data.IntCast
( intCast )
import Data.Maybe
( fromMaybe, isJust, isNothing, mapMaybe )
import Data.Proxy
( Proxy (..) )
import Data.Quantity
( Quantity (..) )
import Data.Set
( Set, (\\) )
import Data.Text
( Text )
import Data.Text.Class
( TextDecodingError (..), fromText, toText )
import Data.Time
( Day (ModifiedJulianDay), UTCTime, toModifiedJulianDay, utctDay )
import Data.Time.Utils
( utcTimePred, utcTimeSucc )
import Data.Word
( Word32 )
import Data.Word.Odd
( Word31 )
import Fmt
( pretty )
import Test.Hspec
( Spec
, anyErrorCall
, describe
, it
, shouldBe
, shouldNotSatisfy
, shouldSatisfy
, shouldThrow
)
import Test.Hspec.Extra
( parallel )
import Test.QuickCheck
( Arbitrary (..)
, NonNegative (..)
, NonZero (..)
, Property
, Small (..)
, applyArbitrary4
, arbitraryBoundedEnum
, arbitraryBoundedIntegral
, arbitraryPrintableChar
, arbitrarySizedBoundedIntegral
, checkCoverage
, choose
, counterexample
, cover
, elements
, infiniteList
, oneof
, property
, scale
, shrinkIntegral
, vector
, withMaxSuccess
, (.&&.)
, (=/=)
, (===)
, (==>)
)
import Test.QuickCheck.Arbitrary.Generic
( genericArbitrary, genericShrink )
import Test.QuickCheck.Classes
( eqLaws, ordLaws )
import Test.QuickCheck.Monadic
( monadicIO, run )
import Test.Text.Roundtrip
( textRoundtrip )
import Test.Utils.Laws
( testLawsMany )
import Test.Utils.Time
( genUniformTime, genUniformTimeWithinRange, getUniformTime )
import UnliftIO.Exception
( evaluate )
import qualified Cardano.Wallet.Primitive.Types.Coin as Coin
import qualified Cardano.Wallet.Primitive.Types.TokenBundle as TokenBundle
import qualified Cardano.Wallet.Primitive.Types.UTxOStatistics as UTxOStatistics
import qualified Data.ByteString as BS
import qualified Data.Map
import qualified Data.Map.Strict as Map
import qualified Data.Set as Set
import qualified Data.Text as T
spec :: Spec
spec = describe "Cardano.Wallet.Primitive.Types" $ do
describe "Class instances obey laws" $ do
testLawsMany @TxOut
[ eqLaws
, ordLaws
]
parallel $ describe "Can perform roundtrip textual encoding & decoding" $ do
textRoundtrip $ Proxy @Address
textRoundtrip $ Proxy @AddressState
textRoundtrip $ Proxy @Direction
textRoundtrip $ Proxy @FeePolicy
textRoundtrip $ Proxy @TxStatus
textRoundtrip $ Proxy @WalletName
textRoundtrip $ Proxy @WalletId
textRoundtrip $ Proxy @SyncTolerance
textRoundtrip $ Proxy @PoolId
textRoundtrip $ Proxy @PoolOwner
-- Extra hand-crafted tests
it "Valid account IDs are properly decoded from text" $ do
forM_ testAccountIdTexts $ \text ->
toText <$> fromText @(Hash "Account") text
`shouldBe` Right text
it "Can roundtrip {decode,encode}PoolIdBech32" $
withMaxSuccess 1000 $ property $ \(pid :: PoolId) ->
decodePoolIdBech32 (encodePoolIdBech32 pid) === Right pid
parallel $ describe "Buildable" $ do
it "WalletId" $ do
let mw = someDummyMnemonic (Proxy @12)
let xprv = generateKeyFromSeed
(mw, Nothing) mempty :: ShelleyKey 'RootK XPrv
let wid = WalletId $ digest $ publicKey xprv
"c225b83f...1d9d620e" === pretty @_ @Text wid
it "TxMeta (1)" $ do
let txMeta = TxMeta
{ status = Pending
, direction = Outgoing
, slotNo = SlotNo 1442
, blockHeight = Quantity 37
, amount = Coin 1337
, expiry = Just (SlotNo 2442)
}
"-0.001337 pending since 1442#37 (expires slot 2442)"
=== pretty @_ @Text txMeta
it "TxMeta (2)" $ do
let txMeta = TxMeta
{ status = InLedger
, direction = Incoming
, slotNo = SlotNo 140
, blockHeight = Quantity 1
, amount = Coin 13371442
, expiry = Nothing
}
"+13.371442 in ledger since 140#1" === pretty @_ @Text txMeta
it "TxMetadata" $ do
let md = TxMetadata $ Data.Map.fromList
[ (1, TxMetaNumber 1)
, (2, TxMetaText "cześć")
, (3, TxMetaBytes (BS.pack [222,173,190,239]))
, (10, TxMetaList [ TxMetaText "a", TxMetaNumber 65 ])
, (20, TxMetaMap
[ ( TxMetaText "key", TxMetaList [TxMetaText "v0", TxMetaText "v1"] )
, ( TxMetaNumber 0, TxMetaText "value" ) ])
]
pretty md `shouldBe` unlines
[ "element 1: 1"
, "element 2: \"cze\\347\\263\""
, "element 3: deadbeef"
, "element 10:"
, " list:"
, " - \"a\""
, " - 65"
, "element 20:"
, " - key: \"key\""
, " - val:"
, " list:"
, " - \"v0\""
, " - \"v1\""
, " - key: 0"
, " - val: \"value\""
]
it "UTxOStatistics" $ do
let txin h = TxIn (Hash h) 0
let txout c = TxOut (Address "") (TokenBundle.fromCoin $ Coin c)
let ada l = l * 1000*1000
let utxo = UTxO $ Map.fromList
[ (txin "a", txout 1)
, (txin "b", txout 4)
, (txin "c", txout $ ada 44)
, (txin "d", txout $ ada 17)
, (txin "e", txout $ ada 2000)
, (txin "f", txout $ ada 9000)
, (txin "g", txout $ ada 3000)
]
let stats = UTxOStatistics.compute utxo
pretty stats `shouldBe` mconcat @String
[ "= Total value of 14061000005 lovelace across 7 UTxOs\n"
, ""
, " ... 10 2\n"
, " ... 100 0\n"
, " ... 1000 0\n"
, " ... 10000 0\n"
, " ... 100000 0\n"
, " ... 1000000 0\n"
, " ... 10000000 0\n"
, " ... 100000000 2\n"
, " ... 1000000000 0\n"
, " ... 10000000000 3\n"
, " ... 100000000000 0\n"
, " ... 1000000000000 0\n"
, " ... 10000000000000 0\n"
, " ... 100000000000000 0\n"
, " ... 1000000000000000 0\n"
, " ... 10000000000000000 0\n"
, " ... 45000000000000000 0\n"
]
let sp = SlotParameters
{ getEpochLength = EpochLength 21600
, getSlotLength = SlotLength 10
, getGenesisBlockDate = StartTime (read "2019-11-09 16:43:02 UTC")
, getActiveSlotCoefficient = 1
}
let slotsPerEpoch = getEpochLength sp
parallel $ describe "flatSlot" $ do
it "fromFlatSlot . flatSlot == id" $ property $ \sl ->
fromFlatSlot slotsPerEpoch (flatSlot slotsPerEpoch sl) === sl
it "flatSlot . fromFlatSlot == id" $ property $ \n -> do
-- The value of 'fromFlatSlot' is undefined when applied to a value
-- that is higher than the maximum value of 'flatSlot' for that
-- epoch length.
--
-- Therefore, the roundtrip property only holds when the flat slot
-- value is less than or equal to this maximum.
--
-- For flat slot values that are higher than this maximum, we expect
-- the 'fromFlatSlot' function to fail with an error.
let maxSlotInEpoch = SlotInEpoch $ unEpochLength slotsPerEpoch - 1
let maxSlotId = SlotId (EpochNo maxBound) maxSlotInEpoch
let maxFlatSlot = flatSlot slotsPerEpoch maxSlotId
let result = flatSlot slotsPerEpoch $ fromFlatSlot slotsPerEpoch n
checkCoverage $
cover 20 (n <= maxFlatSlot) "<= maxFlatSlot" $
cover 20 (n > maxFlatSlot) "> maxFlatSlot" $
if n <= maxFlatSlot then
result `shouldBe` n
else
evaluate result `shouldThrow` anyErrorCall
parallel $ describe "Ranges" $ do
it "arbitrary ranges are valid" $
withMaxSuccess 1000 $ property $ \(r :: Range Integer) ->
checkCoverage $
cover 10 (rangeIsFinite r) "finite range" $
rangeIsValid r .&&.
all rangeIsValid (shrink r)
it "arbitrary non-singleton ranges are valid" $
withMaxSuccess 1000 $ property $ \(nsr :: NonSingletonRange Int) ->
let isValidNonSingleton (NonSingletonRange r) =
rangeIsValid r && not (rangeIsSingleton r) in
checkCoverage $
cover 10 (rangeIsFinite (getNonSingletonRange nsr))
"finite range" $
isValidNonSingleton nsr .&&.
all isValidNonSingleton (shrink nsr)
it "functions is{Before,Within,After}Range are mutually exclusive" $
withMaxSuccess 1000 $ property $ \(a :: Integer) r ->
let options =
[ (isBeforeRange)
, (isWithinRange)
, (isAfterRange) ] in
checkCoverage $
cover 10 (a `isBeforeRange` r) "isBeforeRange" $
cover 10 (a `isWithinRange` r) "isWithinRange" $
cover 10 (a `isAfterRange` r) "isAfterRange" $
1 === length (filter (\f -> f a r) options)
it "pred (inclusiveLowerBound r) `isBeforeRange` r" $
withMaxSuccess 1000 $ property $ \(r :: Range Integer) ->
checkCoverage $
cover 10 (rangeHasLowerBound r) "has lower bound" $
((`isBeforeRange` r) . pred <$> inclusiveLowerBound r)
=/= Just False
it "inclusiveLowerBound r `isWithinRange` r" $
withMaxSuccess 1000 $ property $ \(r :: Range Integer) ->
checkCoverage $
cover 10 (rangeHasLowerBound r) "has lower bound" $
((`isWithinRange` r) <$> inclusiveLowerBound r)
=/= Just False
it "inclusiveUpperBound r `isWithinRange` r" $
withMaxSuccess 1000 $ property $ \(r :: Range Integer) ->
checkCoverage $
cover 10 (rangeHasUpperBound r) "has upper bound" $
((`isWithinRange` r) <$> inclusiveUpperBound r)
=/= Just False
it "succ (inclusiveUpperBound r) `isAfterRange` r" $
withMaxSuccess 1000 $ property $ \(r :: Range Integer) ->
checkCoverage $
cover 10 (rangeHasUpperBound r) "has upper bound" $
((`isAfterRange` r) . succ <$> inclusiveUpperBound r)
=/= Just False
it "a `isWithinRange` wholeRange == True" $
property $ \(a :: Integer) ->
a `isWithinRange` wholeRange === True
it "rangeIsSingleton (Range a a)" $
property $ \(a :: Int) ->
Range (Just a) (Just a) `shouldSatisfy` rangeIsSingleton
it "not (rangeIsSingleton (Range (pred a) a))" $
property $ \(a :: Int) ->
Range (Just (pred a)) (Just a)
`shouldNotSatisfy` rangeIsSingleton
it "not (rangeIsSingleton (Range a (succ a)))" $
property $ \(a :: Int) ->
Range (Just a) (Just (succ a))
`shouldNotSatisfy` rangeIsSingleton
it "rangeLowerBound r = rangeUpperBound r <=> rangeIsSingleton r" $
property $ \(r :: Range Bool) ->
checkCoverage $
cover 10 (rangeIsFinite r) "is finite" $
(rangeLowerBound r == rangeUpperBound r) === rangeIsSingleton r
it "r `isSubrangeOf` r" $
property $ \(r :: Range Int) ->
r `isSubrangeOf` r
it "r `isSubrangeOf` wholeRange" $
property $ \(r :: Range Int) ->
checkCoverage $
cover 10 (rangeHasLowerBound r) "has lower bound" $
cover 10 (rangeHasUpperBound r) "has upper bound" $
cover 10 (rangeIsFinite r) "is finite" $
r `isSubrangeOf` wholeRange
it "Range (succ a) b `isSubrangeOf` Range a b" $
withMaxSuccess 1000 $ property $ \nsr ->
let r@(Range a b :: Range Int) = getNonSingletonRange nsr in
checkCoverage $
cover 10 (rangeHasLowerBound r) "has lower bound" $
cover 10 (rangeHasUpperBound r) "has upper bound" $
cover 10 (rangeIsFinite r) "is finite" $
Range (succ <$> a) b `isSubrangeOf` Range a b
it "Range a (pred b) `isSubrangeOf` Range a b" $
withMaxSuccess 1000 $ property $ \nsr ->
let r@(Range a b :: Range Int) = getNonSingletonRange nsr in
checkCoverage $
cover 10 (rangeHasLowerBound r) "has lower bound" $
cover 10 (rangeHasUpperBound r) "has upper bound" $
cover 10 (rangeIsFinite r) "is finite" $
Range a (pred <$> b) `isSubrangeOf` Range a b
it "Range a b `isSubrangeOf` Range (pred a) b" $
property $ \r@(Range a b :: Range Int) ->
checkCoverage $
cover 10 (rangeHasLowerBound r) "has lower bound" $
cover 10 (rangeHasUpperBound r) "has upper bound" $
cover 10 (rangeIsFinite r) "is finite" $
Range a b `isSubrangeOf` Range (pred <$> a) b
it "Range a b `isSubrangeOf` Range a (succ b)" $
property $ \r@(Range a b :: Range Int) ->
checkCoverage $
cover 10 (rangeHasLowerBound r) "has lower bound" $
cover 10 (rangeHasUpperBound r) "has upper bound" $
cover 10 (rangeIsFinite r) "is finite" $
Range a b `isSubrangeOf` Range a (succ <$> b)
parallel $ describe "Range bounds" $ do
it "NegativeInfinity < InclusiveBound a" $
property $ \(a :: Int) ->
NegativeInfinity < InclusiveBound a
it "InclusiveBound a < PositiveInfinity" $
property $ \(a :: Int) ->
InclusiveBound a < PositiveInfinity
it "compare (InclusiveBound a) (InclusiveBound b) = compare a b" $
property $ \(a :: Int) (b :: Int) ->
compare (InclusiveBound a) (InclusiveBound b) === compare a b
parallel $ describe "Epoch arithmetic: arbitrary value generation" $ do
it "EpochNo generation covers interesting cases" $
withMaxSuccess 10000 $ property $ \(epoch :: EpochNo) ->
checkCoverage
$ cover 10 (epoch == minBound)
"minBound"
$ cover 10 (epoch == maxBound)
"maxBound"
$ cover 10 (epoch == minBound + 1)
"minBound + 1"
$ cover 10 (epoch == maxBound - 1)
"maxBound - 1"
$ cover 10 (epoch > minBound && epoch < maxBound)
"intermediate value"
True
it "SlotParametersAndTimePoint generation covers interesting cases" $
withMaxSuccess 10000 $ property $
\(SlotParametersAndTimePoint sps t) ->
let belowMin = t < epochStartTime sps minBound
aboveMax = t > epochStartTime sps maxBound
in
checkCoverage
$ cover 10 belowMin
"time point before the earliest representable slot"
$ cover 10 aboveMax
"time point after the latest representable slot"
$ cover 10 (not belowMin && not aboveMax)
"time point during the lifetime of the blockchain"
True
parallel $ describe "Slot arithmetic" $ do
it "slotFloor (slotStartTime slotMinBound) == Just slotMinBound" $
withMaxSuccess 1000 $ property $ \sps ->
slotFloor sps (slotStartTime sps slotMinBound)
=== Just slotMinBound
it "slotFloor (utcTimePred (slotStartTime slotMinBound)) == Nothing" $
withMaxSuccess 1000 $ property $ \sps ->
slotFloor sps (utcTimePred (slotStartTime sps slotMinBound))
=== Nothing
it "t < slotStartTime slotMinBound => slotFloor t == Nothing" $
withMaxSuccess 1000 $ property $ \sps t ->
StartTime (getUniformTime t) < getGenesisBlockDate sps ==>
slotFloor sps (getUniformTime t) === Nothing
it "t < slotStartTime slotMinBound => slotCeiling t == slotMinBound" $
withMaxSuccess 1000 $ property $ \sps t ->
StartTime (getUniformTime t) < getGenesisBlockDate sps ==>
slotCeiling sps (getUniformTime t) === slotMinBound
it "slotStartTime slotMinBound `isAfterRange` r => \
\isNothing (slotRangeFromTimeRange r)" $
withMaxSuccess 1000 $ property $ \sps r -> do
let r' = getUniformTime <$> r
slotStartTime sps slotMinBound `isAfterRange` r' ==>
isNothing (slotRangeFromTimeRange' sps r')
it "applyN (flatSlot slot) slotPred slot == Just slotMinBound" $
withMaxSuccess 10 $ property $
\(sps, slot) -> do
let n = flatSlot (getEpochLength sps) slot
Just slotMinBound ===
applyN n (slotPred sps =<<) (Just slot)
it "applyN (flatSlot slot + 1) slotPred slot == Nothing" $
withMaxSuccess 10 $ property $
\(sps, slot) -> do
let n = flatSlot (getEpochLength sps) slot + 1
Nothing === applyN n (slotPred sps =<<) (Just slot)
it "(applyN n slotSucc) . (applyN n slotPred) == id" $
withMaxSuccess 1000 $ property $
\(sps, slot) (NonNegative (n :: Int)) ->
flatSlot (getEpochLength sps) slot >= fromIntegral n ==> do
let s = applyN n (slotSucc sps <$>)
let p = applyN n (slotPred sps =<<)
Just slot === (s . p) (Just slot)
it "(applyN n slotPred) . (applyN n slotSucc) == id" $
withMaxSuccess 1000 $ property $
\(sps, slot) (NonNegative (n :: Int)) -> do
let s = applyN n (slotSucc sps <$>)
let p = applyN n (slotPred sps =<<)
Just slot === (p . s) (Just slot)
it "slotDifference (applyN n slotSucc slot) slot == \
\n (valid difference)" $
withMaxSuccess 1000 $ property $
\(sps, slot) (NonNegative (n :: Int)) ->
Quantity (fromIntegral n) ===
slotDifference sps (applyN n (slotSucc sps) slot) slot
it "slotDifference slot (applyN n slotPred slot) == \
\n (valid difference)" $
withMaxSuccess 1000 $ property $
\(sps, slot) (NonNegative (n :: Int)) ->
flatSlot (getEpochLength sps) slot >= fromIntegral n ==>
Just (Quantity (fromIntegral n)) ===
(slotDifference sps slot <$>
applyN n (slotPred sps =<<) (Just slot))
it "slotDifference (applyN n slotPred slot) slot == \
\0 (invalid difference)" $
withMaxSuccess 1000 $ property $
\(sps, slot) (NonNegative (n :: Int)) ->
flatSlot (getEpochLength sps) slot >= fromIntegral n ==>
Just (Quantity 0) ===
(flip (slotDifference sps) slot <$>
applyN n (slotPred sps =<<) (Just slot))
it "slotDifference slot (applyN n slotSucc slot) == \
\0 (invalid difference)" $
withMaxSuccess 1000 $ property $
\(sps, slot) (NonNegative (n :: Int)) ->
Quantity 0 ===
slotDifference sps slot (applyN n (slotSucc sps) slot)
it "slotAt' . slotStartTime == id" $
withMaxSuccess 1000 $ property $
\(sps, slot) -> do
let f = slotAt' sps . slotStartTime sps
Just slot === f slot
it "slotCeiling . slotStartTime == id" $
withMaxSuccess 1000 $ property $
\(sps, slot) -> do
let f = slotCeiling sps . slotStartTime sps
slot === f slot
it "slotFloor . slotStartTime == id" $
withMaxSuccess 1000 $ property $
\(sps, slot) -> do
let f = slotFloor sps . slotStartTime sps
Just slot === f slot
it "slot > slotMinBound => \
\slotSucc . slotFloor . utcTimePred . slotStartTime == id" $
withMaxSuccess 1000 $ property $
\(sps, slot) -> slot > slotMinBound ==> do
let f = fmap (slotSucc sps)
. slotFloor sps
. utcTimePred
. slotStartTime sps
Just slot === f slot
it "slotPred . slotCeiling . utcTimeSucc . slotStartTime == id" $
withMaxSuccess 1000 $ property $
\(sps, slot) -> do
let f = slotPred sps
. slotCeiling sps
. utcTimeSucc
. slotStartTime sps
Just slot === f slot
it "slotRangeFromTimeRange is maximal" $
property $ \(sps, uniformTimeRange) ->
let timeRange :: Range UTCTime
timeRange = getUniformTime <$> uniformTimeRange
maybeSlotRange :: Maybe (Range SlotId)
maybeSlotRange = slotRangeFromTimeRange' sps timeRange
startsWithin :: Range SlotId -> Range UTCTime -> Bool
startsWithin sr tr =
(`isSubrangeOf` tr) $ fmap (slotStartTime sps) sr
lowerBoundPred = mapRangeLowerBound slotPred'
upperBoundSucc = mapRangeUpperBound slotSucc'
slotPred' :: SlotId -> SlotId
slotPred' s = fromMaybe slotMinBound $ slotPred sps s
slotSucc' :: SlotId -> SlotId
slotSucc' = slotSucc sps
in
checkCoverage $
cover 20 (isNothing maybeSlotRange)
"have no slot range" $
cover 50 (isJust maybeSlotRange)
"have slot range" $
cover 20 (fmap rangeHasLowerBound maybeSlotRange == Just True)
"slot range has lower bound" $
cover 20 (fmap rangeHasUpperBound maybeSlotRange == Just True)
"slot range has upper bound" $
cover 20 (fmap rangeIsFinite maybeSlotRange == Just True)
"slot range is finite" $
case maybeSlotRange of
Nothing ->
(Just True ===
((< getGenesisBlockDate sps) . StartTime
<$> inclusiveUpperBound timeRange))
Just slotRange ->
-- Rule 1: Slot range is within specified time range:
(slotRange `startsWithin` timeRange)
.&&.
-- Rule 2: Slot range lower bound is minimal:
(not (lowerBoundPred slotRange `startsWithin` timeRange)
-- Exceptions to the rule:
|| not (rangeHasLowerBound slotRange)
|| lowerBoundPred slotRange == slotRange)
.&&.
-- Rule 3: Slot range upper bound is maximal:
(not (upperBoundSucc slotRange `startsWithin` timeRange)
-- Exceptions to the rule:
|| not (rangeHasUpperBound slotRange)
|| upperBoundSucc slotRange == slotRange)
it ("`slotStartTime . slotRangeFromTimeRange` is idempotent") $
withMaxSuccess 1000 $ property $
\sps timeRange -> do
let f = fmap (fmap (slotStartTime sps))
. slotRangeFromTimeRange' sps
let r = getUniformTime <$> timeRange
checkCoverage $
cover 20 (isJust $ f r)
"`slotRangeFromTimeRange` yielded a slot range" $
cover 20 (isNothing $ f r)
"`slotRangeFromTimeRange` yielded nothing" $
(f =<< f r) === f r
parallel $ describe "Negative cases for types decoding" $ do
it "fail fromText @SyncTolerance \"patate\"" $ do
let err = "Cannot parse given time duration. Here are a few \
\examples of valid text representing a sync tolerance: \
\'3s', '3600s', '42s'."
fromText @SyncTolerance "patate" === Left (TextDecodingError err)
it "fail fromText @AddressState \"unusedused\"" $ do
let err = "Unable to decode the given text value.\
\ Please specify one of the following values: used, unused."
fromText @AddressState "unusedused" === Left (TextDecodingError err)
it "fail fromText @WalletName \"\"" $ do
let err = "name is too short: expected at least "
<> show walletNameMinLength <> " character"
fromText @WalletName "" === Left (TextDecodingError err)
it "fail fromText @WalletName > walletNameMaxLength" $ do
let err = "name is too long: expected at most "
<> show walletNameMaxLength <> " characters"
let walName = T.pack (replicate (walletNameMaxLength + 1) 'x')
fromText @WalletName walName === Left (TextDecodingError err)
it "fail fromText @WalletId \"101\"" $ do
let err = "wallet id should be a hex-encoded string \
\of 40 characters"
fromText @WalletId "101" === Left (TextDecodingError err)
it "Invalid account IDs cannot be decoded from text" $ do
let expectedErrorMessage =
"Invalid account hash: \
\expecting a hex-encoded value that is 32 bytes in length."
forM_ invalidAccountIdTexts $ \text ->
toText <$> fromText @(Hash "Account") text
`shouldBe` Left (TextDecodingError expectedErrorMessage)
let invalidFeePolicyTexts =
[ ""
, " "
, "1"
, "1x"
, "1 + 1"
, "1x + 1"
, "1+1x"
, "1 +1x"
, "1+ 1x"
, "1+ 1x"
, "1 +1x"
, "1 + 1x + 1y" -- old style
, "xxxx"
, "a + bx"
, "dasd + asdax"
]
forM_ invalidFeePolicyTexts $ \policyText ->
it ("fail fromText @FeePolicy " <> show policyText) $ do
let err =
"Unable to decode FeePolicy: \
\Linear equation not in expected format: a + bx \
\where 'a' and 'b' are numbers"
fromText @FeePolicy policyText === Left (TextDecodingError err)
let correctPolicyTexts =
[ "1 + 6667x"
, "1.12 + 1.4324x"
, "1 + 0x"
, "-13 + 3.14159265359x"
, "-3.14159265359 + - 1 x"
, "1 + 11 x"
]
forM_ correctPolicyTexts $ \policyText ->
it ("correct fromText @FeePolicy " <> show policyText) $ do
fromText @FeePolicy policyText `shouldSatisfy` isRight
let poolOwnerTests =
[ ( "Invalid bech32"
, "hello"
, "Stake pool owner is not a valid bech32 string: "
<> "StringToDecodeTooShort" )
, ( "Wrong HRP"
, "split1checkupstagehandshakeupstreamerranterredcaperred2y9e3w"
, "Stake pool owner has wrong prefix: expected ed25519_pk "
<> "but got HumanReadablePart \"split\"" )
]
forM_ poolOwnerTests $ \(title, str, msg) ->
it ("fail fromText @PoolOwner " ++ title) $
fromText @PoolOwner str `shouldBe` Left (TextDecodingError msg)
parallel $ describe "unsafeEpochNo" $ do
it "returns a successful result for any Word31" $
property prop_unsafeEpochNoValid
it "throws an exception for any value bigger than a Word31" $
property prop_unsafeEpochNoThrows
parallel $ describe "Lemma 2.1 - Properties of UTxO operations" $ do
it "2.1.1) ins⊲ u ⊆ u"
(checkCoverage prop_2_1_1)
it "2.1.2) ins⋪ u ⊆ u"
(checkCoverage prop_2_1_2)
it "2.1.3) u ⊳ outs ⊆ u"
(checkCoverage prop_2_1_3)
it "2.1.4) ins⊲ (u ⋃ v) = (ins⊲ u) ⋃ (ins⊲ v)"
(checkCoverage prop_2_1_4)
it "2.1.5) ins⋪ (u ⋃ v) = (ins⋪ u) ⋃ (ins⋪ v)"
(checkCoverage prop_2_1_5)
it "2.1.6) (dom u ⋂ ins) ⊲ u = ins⊲ u"
(checkCoverage prop_2_1_6)
it "2.1.7) (dom u ⋂ ins) ⋪ u = ins⋪ u"
(checkCoverage prop_2_1_7)
it "2.1.8) (dom u ⋃ ins) ⋪ (u ⋃ v) = (ins ⋃ dom u) ⋪ v"
(checkCoverage prop_2_1_8)
it "2.1.9) ins⋪ u = (dom u \\ ins)⊲ u"
(checkCoverage prop_2_1_9)
parallel $ describe "Lemma 2.6 - Properties of balance" $ do
it "2.6.1) dom u ⋂ dom v ==> balance (u ⋃ v) = balance u + balance v"
(checkCoverage prop_2_6_1)
it "2.6.2) balance (ins⋪ u) = balance u - balance (ins⊲ u)"
(checkCoverage prop_2_6_2)
parallel $ describe "Slotting ordering" $ do
it "Any Slot >= slotMinBound"
(property (>= slotMinBound))
it "SlotId 1 2 < SlotId 2 1"
(property $ SlotId { epochNumber = 1, slotNumber = 2 } < SlotId 2 1)
it "SlotId 1 1 < SlotId 1 2"
(property $ SlotId { epochNumber = 1, slotNumber = 1 } < SlotId 1 2)
it "SlotId 1 2 < SlotId 2 2"
(property $ SlotId { epochNumber = 1, slotNumber = 2 } < SlotId 2 2)
parallel $ describe "UtxoStatistics" $ do
it "total statistics == balance utxo"
(checkCoverage propUtxoTotalIsBalance)
it "sum of weighted distribution >= total balance"
(checkCoverage propUtxoSumDistribution)
it "distribution == empty <=> UTxO == empty"
(checkCoverage propUtxoEmptyIsEmpty)
it "sum of the distribution coeffs == sizeOf UTxO"
(checkCoverage propUtxoWeightsEqualSize)
{-------------------------------------------------------------------------------
Wallet Specification - Lemma 2.1 - Properties of UTxO operations
-------------------------------------------------------------------------------}
prop_2_1_1 :: (Set TxIn, UTxO) -> Property
prop_2_1_1 (ins, u) =
cover 50 cond "dom u ⋂ ins ≠ ∅" (property prop)
where
cond = not $ dom u `Set.disjoint` ins
prop = (u `restrictedBy` ins) `isSubsetOf` u
prop_2_1_2 :: (Set TxIn, UTxO) -> Property
prop_2_1_2 (ins, u) =
cover 50 cond "dom u ⋂ ins ≠ ∅" (property prop)
where
cond = not $ dom u `Set.disjoint` ins
prop = (u `excluding` ins) `isSubsetOf` u
prop_2_1_3 :: (Set TxOut, UTxO) -> Property
prop_2_1_3 (outs, u) =
cover 50 cond "u ⋂ outs ≠ ∅" (property prop)
where
cond = not $ Set.fromList (Map.elems (unUTxO u)) `Set.disjoint` outs
prop = (u `restrictedTo` outs) `isSubsetOf` u
prop_2_1_4 :: (Set TxIn, UTxO, UTxO) -> Property
prop_2_1_4 (ins, u, v) =
cover 50 cond "(dom u ⋃ dom v) ⋂ ins ≠ ∅" (property prop)
where
cond = not $ Set.union (dom u) (dom v) `Set.disjoint` ins
prop =
((u <> v) `restrictedBy` ins)
===
(u `restrictedBy` ins) <> (v `restrictedBy` ins)
prop_2_1_5 :: (Set TxIn, UTxO, UTxO) -> Property
prop_2_1_5 (ins, u, v) =
cover 50 cond "(dom u ⋃ dom v) ⋂ ins ≠ ∅" (property prop)
where
cond = not $ Set.union (dom u) (dom v) `Set.disjoint` ins
prop =
((u <> v) `excluding` ins)
===
(u `excluding` ins) <> (v `excluding` ins)
prop_2_1_6 :: (Set TxIn, UTxO) -> Property
prop_2_1_6 (ins, u) =
cover 50 cond "dom u ⋂ ins ≠ ∅" (property prop)
where
cond = not $ dom u `Set.disjoint` ins
prop =
(u `restrictedBy` (dom u `Set.intersection` ins))
===
(u `restrictedBy` ins)
prop_2_1_7 :: (Set TxIn, UTxO) -> Property
prop_2_1_7 (ins, u) =
cover 50 cond "dom u ⋂ ins ≠ ∅" (property prop)
where
cond = not $ dom u `Set.disjoint` ins
prop =
(u `excluding` (dom u `Set.intersection` ins))
===
(u `excluding` ins)
prop_2_1_8 :: (Set TxIn, UTxO, UTxO) -> Property
prop_2_1_8 (ins, u, v) =
cover 50 cond "dom u ⋂ ins ≠ ∅" (property prop)
where
cond = not $ dom u `Set.disjoint` ins
prop =
((u <> v) `excluding` (dom u <> ins))
===
v `excluding` (ins <> dom u)
prop_2_1_9 :: (Set TxIn, UTxO) -> Property
prop_2_1_9 (ins, u) =
cover 50 cond "dom u ⋂ ins ≠ ∅" (property prop)
where
cond = not $ dom u `Set.disjoint` ins
prop = (u `excluding` ins) === u `restrictedBy` (dom u \\ ins)
{-------------------------------------------------------------------------------
Wallet Specification - Lemma 2.6 - Properties of Balance
-------------------------------------------------------------------------------}
prop_2_6_1 :: (UTxO, UTxO) -> Property
prop_2_6_1 (u, v) =
cover 50 cond "u ≠ ∅ , v ≠ ∅" (property prop)
where
-- NOTE:
-- A precondition (u ⋂ v = ∅ ) is hard to satisfy because our generators
-- are built in order to not be 'too entropic'. So, we better just create
-- a v' that has no overlap with u.
v' = v `excluding` dom u
cond = not (u `isSubsetOf` mempty || v' `isSubsetOf` mempty)
prop = balance (u <> v') === balance u `TokenBundle.add` balance v'
prop_2_6_2 :: (Set TxIn, UTxO) -> Property
prop_2_6_2 (ins, u) =
cover 50 cond "dom u ⋂ ins ≠ ∅" (property prop)
where
cond = not $ Set.null $ dom u `Set.intersection` ins
prop =
balance (u `excluding` ins)
===
balance u `TokenBundle.unsafeSubtract` balance (u `restrictedBy` ins)
{-------------------------------------------------------------------------------
UTxO statistics Properties
-------------------------------------------------------------------------------}
-- | The 'total' stake in the statistics is the UTxO's balance
propUtxoTotalIsBalance
:: ShowFmt UTxO -> Property