This repository was archived by the owner on Jan 9, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathAnalyzeSpec.hs
More file actions
4394 lines (3788 loc) · 147 KB
/
Copy pathAnalyzeSpec.hs
File metadata and controls
4394 lines (3788 loc) · 147 KB
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 CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ViewPatterns #-}
module AnalyzeSpec (spec) where
import Control.Lens (findOf, ix, matching, (&),
(.~), (^..), _Left)
import Control.Monad (unless)
import Control.Monad.Except (runExceptT)
import Control.Monad.State.Strict (runStateT)
import Data.Either (isLeft, isRight)
import Data.Foldable (asum, find, for_)
import qualified Data.HashMap.Strict as HM
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.SBV (isConcretely)
import Data.SBV.Internals (SBV (SBV))
import Data.Text (Text)
import qualified Data.Text as T
import NeatInterpolation (text)
import Prelude hiding (read)
import Test.Hspec hiding (xdescribe)
import Pact.Parse (parseExprs)
import Pact.Repl (evalRepl', initReplState, replLookupModule)
import Pact.Repl.Types (ReplMode (StringEval))
import Pact.Types.Runtime (Exp, Info, ModuleData(..), Ref, ModuleName)
import Pact.Runtime.Utils
import Pact.Types.Pretty
import Pact.Types.Util (tShow)
import Pact.Analyze.Check
import Pact.Analyze.Eval.Numerical (banker'sMethodS)
import qualified Pact.Analyze.Model as Model
import Pact.Analyze.Parse (PreProp (..), TableEnv,
expToProp, inferProp)
import Pact.Analyze.PrenexNormalize (prenexConvert)
import Pact.Analyze.Types
import Pact.Analyze.Util
wrap :: Text -> Text -> Text
wrap code model =
[text|
(env-exec-config ["DisablePact44"])
(env-keys ["admin"])
(env-data { "keyset": { "keys": ["admin"], "pred": "=" } })
(begin-tx)
(define-keyset 'ks (read-keyset "keyset"))
(module test 'ks
@model
[; (defproperty dec-conserves-mass (t:table c:column) (= (column-delta t c) 0.0))
; (defproperty int-conserves-mass (t:table c:column) (= (column-delta t c) 0))
(defproperty my-column-delta (d:integer) (= (column-delta accounts 'balance) d))
(defproperty conserves-balance (= (column-delta accounts 'balance) 0))
(defproperty conserves-balance2 (my-column-delta 0))
; this hash the same name as the column, but the column name takes
; precedence
(defproperty balance (> 0 1))
(defproperty bad-recursive-prop bad-recursive-prop)
(defproperty bad-recursive-prop2 (d:integer) (bad-recursive-prop2 d))
$model
]
(defschema account
"Row type for accounts table."
balance:integer
; data
)
(deftable accounts:{account}
"Main table for test module.")
$code
)
(commit-tx)
|]
wrapNoTable :: Text -> Text
wrapNoTable code =
[text|
(env-keys ["admin"])
(env-data { "keyset": { "keys": ["admin"], "pred": "=" } })
(begin-tx)
(env-exec-config ["DisablePact44"])
(define-keyset 'ks (read-keyset "keyset"))
(module test 'ks $code)
(commit-tx)
|]
data TestFailure
= TestCheckFailure CheckFailure
| NoTestModule
| ReplError String
| VerificationFailure VerificationFailure
| ScopeError' ScopeError
deriving Show
renderTestFailure :: TestFailure -> IO String
renderTestFailure = \case
TestCheckFailure cf -> do
svgInfo <- case falsifyingModel cf of
Nothing -> pure ""
Just m -> do
let fp = "/tmp/execution-graph.dot"
Model.renderDot fp m
pure $ "\n\nrendered execution graph to DOT: " ++ fp
pure $ renderCompactString (describeCheckFailure cf) ++ svgInfo
NoTestModule -> pure "example is missing a module named 'test'"
ReplError err -> pure $ "ReplError: " ++ err
VerificationFailure vf ->
pure $ T.unpack $ T.unlines $ map renderCompactText $ renderVerifiedModule $ Left vf
ScopeError' err -> pure $ "ScopeError: " ++ show err
--
-- TODO: use ExceptT
--
compile' :: ModuleName -> Text -> IO (Either TestFailure (ModuleData Ref))
compile' modName code = do
replState0 <- initReplState StringEval Nothing
(r, replState) <- runStateT (evalRepl' $ T.unpack code) replState0
case r of
Left e -> return $ Left $ ReplError (show e)
Right {} -> do
moduleM <- replLookupModule replState modName
pure $ case moduleM of
Left err -> Left $ ReplError (show err)
Right m -> Right (inlineModuleData m)
compile :: Text -> IO (Either TestFailure (ModuleData Ref))
compile = compile' "test"
runVerification :: Text -> IO (Maybe TestFailure)
runVerification code = do
eModuleData <- compile code
case eModuleData of
Left tf -> pure $ Just tf
Right moduleData -> do
results <- verifyModule Nothing mempty (HM.fromList [("test", moduleData)]) moduleData
case results of
Left failure -> pure $ Just $ VerificationFailure failure
Right (ModuleChecks propResults stepResults invariantResults _) ->
pure $ asum
[ case findOf (traverse . traverse) isLeft propResults of
Just (Left failure) -> Just $ TestCheckFailure failure
_ -> Nothing
, case findOf (traverse . traverse) isLeft stepResults of
Just (Left failure) -> Just $ TestCheckFailure failure
_ -> Nothing
, case findOf (traverse . traverse . traverse) isLeft invariantResults of
Just (Left failure) -> Just $ TestCheckFailure failure
_ -> Nothing
]
runCheck :: CheckableType -> Text -> Check -> IO (Maybe TestFailure)
runCheck checkType code check =
either Just (const Nothing) <$> runCheck' checkType code check
runCheck' :: CheckableType -> Text -> Check -> IO (Either TestFailure [CheckResult])
runCheck' checkType code check = do
eModuleData <- compile code
case eModuleData of
Left tf -> pure $ Left tf
Right moduleData -> do
result <- runExceptT $ verifyCheck mempty moduleData "test" check checkType
pure $ case result of
Left failure -> Left $ VerificationFailure failure
Right (Left cf:_) -> Left $ TestCheckFailure cf
Right rs -> Right rs
checkInterface :: Text -> IO (Maybe TestFailure)
checkInterface code = do
eModuleData <- compile' "coin-sig" code
case eModuleData of
Left tf -> pure $ Just tf
Right moduleData -> do
result <- verifyModule Nothing mempty HM.empty moduleData
pure $ case result of
Left failure -> Just $ VerificationFailure failure
Right _ -> Nothing
-- | 'TestEnv' represents the environment a test runs in. Used with
-- 'expectTest'.
data TestEnv = TestEnv
{ testCode :: !Text
, testCheck :: !Check
, testName :: !String
, testPred :: !(Maybe TestFailure -> IO ())
}
expectTest :: HasCallStack => TestEnv -> Spec
expectTest (TestEnv code check name p) =
before (runCheck CheckDefun code check) $
it name p
handlePositiveTestResult :: HasCallStack => Maybe TestFailure -> Expectation
handlePositiveTestResult = \case
Nothing -> pure ()
Just (TestCheckFailure (CheckFailure _ (SmtFailure (SortMismatch msg))))
-> pendingWith msg
Just tf -> expectationFailure =<< renderTestFailure tf
expectVerified :: HasCallStack => Text -> Spec
expectVerified = expectVerified' ""
expectVerified' :: HasCallStack => Text -> Text -> Spec
expectVerified' model code =
before (runVerification $ wrap code model) $
it "passes in-code checks" $ handlePositiveTestResult
expectFalsified :: HasCallStack => Text -> Spec
expectFalsified = expectFalsified' ""
expectFalsifiedMessage :: HasCallStack => Text -> Text -> Spec
expectFalsifiedMessage code needleMsg =
before (runVerification $ wrap code "") $
it "passes in-code checks" $ \res ->
res `shouldSatisfy` \case
Just (TestCheckFailure cf) ->
needleMsg `isInCheckFailure` cf
_ -> False
expectVerificationFailure :: HasCallStack => Text -> Spec
expectVerificationFailure code =
before (runVerification $ wrap code "") $
it "fails in-code checks" $ \res ->
res `shouldSatisfy` \case
Just (VerificationFailure _) -> True
_ -> False
isInCheckFailure :: Text -> CheckFailure -> Bool
isInCheckFailure needle cf = needle `T.isInfixOf` renderCompactText (describeCheckFailure cf)
expectFalsified' :: HasCallStack => Text -> Text -> Spec
expectFalsified' model code =
before (runVerification $ wrap code model) $
it "passes in-code checks" $ (`shouldSatisfy` isJust)
expectPassWithWarning :: HasCallStack => Text -> Text -> Check -> Spec
expectPassWithWarning code wgText check =
before (runCheck' CheckDefun (wrap code "") check) $
it "expectPassWithWarning" $ \r -> case r of
Left e -> expectationFailure =<< renderTestFailure e
Right rs -> case filter findWg rs of
[] -> expectationFailure $ "no warning found for " ++ show wgText ++ ": " ++
renderCompactString (concatMap describeCheckResult rs)
_ -> return ()
where
findWg (Left w) = wgText `isInCheckFailure` w
findWg _ = False
expectPass :: HasCallStack => Text -> Check -> Spec
expectPass code check = expectTest
TestEnv { testCode = wrap code ""
, testCheck = check
, testPred = handlePositiveTestResult
, testName = "expectPass"
}
expectFail :: HasCallStack => Text -> Check -> Spec
expectFail code check = expectTest
TestEnv { testCode = wrap code ""
, testCheck = check
, testPred = (`shouldSatisfy` isJust)
, testName = "expectFail"
}
expectFailureMessage :: HasCallStack => Text -> Text -> Spec
expectFailureMessage code needleMsg = expectTest
TestEnv { testCode = wrap code ""
, testCheck = Valid (CoreProp $ IntegerComparison Eq 0 0)
, testPred =
\res -> res `shouldSatisfy` \case
Just (TestCheckFailure cf) ->
needleMsg `isInCheckFailure` cf
_ ->
False
, testName = "expectFailureMessage"
}
intConserves :: TableName -> ColumnName -> Prop 'TyBool
intConserves (TableName tn) (ColumnName cn)
= CoreProp $ IntegerComparison Eq 0 $ Inj $
IntColumnDelta (StrLit tn) (StrLit cn)
decConserves :: TableName -> ColumnName -> Prop 'TyBool
decConserves (TableName tn) (ColumnName cn)
= CoreProp $ DecimalComparison Eq 0 $ Inj $
DecColumnDelta (StrLit tn) (StrLit cn)
pattern Success' :: Prop 'TyBool
pattern Success' = PropSpecific Success
pattern Abort' :: Prop 'TyBool
pattern Abort' = PropSpecific Abort
pattern Result' :: Prop t
pattern Result' = PropSpecific Result
xdescribeWith :: HasCallStack => String -> String -> SpecWith a -> SpecWith a
xdescribeWith reason label = before_ (pendingWith reason) . describe label
spec :: Spec
spec = describe "analyze" $ do
describe "decimal arithmetic" $ do
let unlit :: S Decimal -> Decimal
unlit = fromJust . unliteralS
it "+" $ unlit (1.1 + 2.2) == 3.3
it "* + +" $ unlit (1.5 * 1.5) == 2.25
it "* + -" $ unlit (1.5 * (-1.5)) == -2.25
it "* - +" $ unlit (-1.5 * 1.5) == -2.25
it "* - -" $ unlit (-1.5 * (-1.5)) == 2.25
it "negate" $ unlit (negate 1.5) == -1.5
it "negate" $ unlit (negate (-1.5)) == 1.5
it "shifts" $ unlit ( 1.5 * fromInteger 10) == 15
it "shifts" $ unlit (-1.5 * fromInteger 10) == -15
it "shifts" $ lShift255D (rShift255D 1.5) == (1 :: Decimal)
it "floor" $ floorD @Decimal 0 == 0
it "floor" $ floorD @Decimal 1.5 == 1
it "floor" $ floorD @Decimal (-1.5) == -2
describe "decimal division" $ do
let unlit = fromJust . unliteralS @Decimal
it "can be one half" $ unlit (1 / 2) == 0.5
it "handles the last decimal correctly" $
unlit (1581138830084.1918464 / 1581138830084)
==
1.000000000000121334316980759948431357013938975877803928214364623522650045615600621337146939720454311443026061056754776474139591383112306668111215913835129748371209820415844429729847990579481732664375546615468582277686924612859136684739968417878803629721864
let i256 :: Int
i256 = 256
i255 :: Int
i255 = 255
it "handles the last decimal digit correctly (positive, round up 1)" $
unlit (15 / (10 ^ i256))
==
2 / 10 ^ i255
it "handles the last decimal digit correctly (positive, round up 2)" $
unlit (17 / (10 ^ i256))
==
2 / 10 ^ i255
it "handles the last decimal digit correctly (positive, round up 3)" $
unlit ((-17) / (-(10 ^ i256)))
==
2 / 10 ^ i255
it "handles the last decimal digit correctly (positive, round down 1)" $
unlit (25 / (10 ^ i256))
==
2 / 10 ^ i255
it "handles the last decimal digit correctly (positive, round down 2)" $
unlit (13 / (10 ^ i256))
==
1 / 10 ^ i255
it "handles the last decimal digit correctly (positive, round down 3)" $
unlit ((-13) / (-(10 ^ i256)))
==
1 / 10 ^ i255
it "handles the last decimal digit correctly (negative, round down 1)" $
unlit ((-15) / (10 ^ i256))
==
-2 / 10 ^ i255
it "handles the last decimal digit correctly (negative, round down 2)" $
unlit ((-17) / (10 ^ i256))
==
-2 / 10 ^ i255
it "handles the last decimal digit correctly (negative, round down 3)" $
unlit (17 / (-(10 ^ i256)))
==
-2 / 10 ^ i255
it "handles the last decimal digit correctly (negative, round up 1)" $
unlit ((-25) / (10 ^ i256))
==
-2 / 10 ^ i255
it "handles the last decimal digit correctly (negative, round up 2)" $
unlit ((-13) / (10 ^ i256))
==
-1 / 10 ^ i255
it "handles the last decimal digit correctly (negative, round up 3)" $
unlit (13 / (-(10 ^ i256)))
==
-1 / 10 ^ i255
it "handles division by a negative number correctly" $
unlit (0 / (-1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000))
==
0
describe "big multiplications" $ do
let unlit = fromJust . unliteralS @Decimal
let code =
[text|
(defun test:bool ()
(let ((x:decimal (*
1.58113883008419202353012810347474735209747288392336210205455502815728238592
1.5811388300841925223288550988445549742724468531346309495428665472399639648496680411494875076793255338200521528740886266294574044913261377201695510306266771994578476399139180068539229254218727314228818363809792
))
(y:decimal 2.500000000000008243836642384325766770967352358818865769190857605784112966024663251834475644384046904403556387019539234091871481832161009920035987673979588455403008477585022252399854826133637675727060845285897044645837341219331160090749369830048441622744791))
(enforce (= x y) "x and y are not equal")))
|]
expectPass code $ Valid Success'
it "rounds up the last digit when appropriate" $
unlit (1581138830084.192052937980207914179905763920823196984267407804357031202155885633105058076747359551154153957331638299995511193600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
* 1581138830084.192220194412674817793768840142081644758814711734437239116786835916965025889939456340088832614965073903903044055232345709136743725518878029119488000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000)
==
2500000000000007812618040.433562734137684699135011741551181715981891159652849247733486729055338549963875582523604695139936764674737736206382376787827325735603006181405156090936148131370459148823374617217523084670407741689762536216481173675491045653179580074788284514172469055900877
let code' =
[text|
(defun test:bool ()
(let ((x:decimal (*
1581138830084.192052937980207914179905763920823196984267407804357031202155885633105058076747359551154153957331638299995511193600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
1581138830084.192220194412674817793768840142081644758814711734437239116786835916965025889939456340088832614965073903903044055232345709136743725518878029119488000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
))
(y:decimal 2500000000000007812618040.433562734137684699135011741551181715981891159652849247733486729055338549963875582523604695139936764674737736206382376787827325735603006181405156090936148131370459148823374617217523084670407741689762536216481173675491045653179580074788284514172469055900877))
(enforce (= x y) "x and y are not equal")))
|]
expectPass code' $ Valid Success'
describe "banker's method" $ do
let unlit = fromJust . unliteralS
it "rounds (_.5) to the nearest even" $ unlit (banker'sMethodS 1.5) == 2
it "rounds (_.5) to the nearest even" $ unlit (banker'sMethodS 2.5) == 2
it "rounds (_.5) to the nearest even" $ unlit (banker'sMethodS (-1.5)) == -2
it "rounds (_.5) to the nearest even" $ unlit (banker'sMethodS (-2.5)) == -2
describe "result" $ do
let code =
[text|
(defun test:integer (x:integer)
(* x -1))
|]
expectPass code $ Valid $ CoreProp $ IntegerComparison Eq
(Inj (IntArithOp Mul (-1) (PVar 1 "x")))
(Inj Result :: Prop 'TyInteger)
describe "inlining" $ do
let code =
[text|
(defun helper:integer (b:integer)
(if (< b 10)
10
b))
(defun test:integer (a:integer)
(helper a))
|]
expectPass code $ Valid $ CoreProp $
IntegerComparison Gte (Inj Result :: Prop 'TyInteger) 10
describe "success" $ do
let code =
[text|
(defun test:bool (x:integer)
(if (< x 10) true false))
|]
expectPass code $ Valid (Inj Success)
expectPass code $ Valid $ sNot Abort'
describe "enforce.trivial" $ do
let code =
[text|
(defun test:bool ()
(enforce false "cannot pass"))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Valid Abort'
expectFail code $ Satisfiable (Inj Success)
describe "enforce.conditional" $ do
let code =
[text|
(defun test:bool (x:integer)
(if (< x 10)
(enforce (< x 5) "abort sometimes")
true))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable $ sNot Abort'
expectPass code $ Satisfiable (Inj Success)
expectFail code $ Valid Abort'
describe "enforce.sequence" $ do
let code =
[text|
(defun test:bool (x:integer)
(enforce (> x 0) "positive")
(enforce false "impossible")
(if (< x 10)
true
false))
|]
expectPass code $ Valid Abort'
describe "enforce.sequence" $ do
let code =
[text|
(defun test:bool (x:integer)
(enforce (> x 0) "positive")
(if (< x 10)
true
false))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable (Inj Success)
describe "enforce.sequence" $ do
let code =
[text|
(defun test:bool (x:integer)
(enforce (> x 0) "positive")
(if (< x 10)
true
false))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable (Inj Success)
expectPass code $ Valid $ (CoreProp $ IntegerComparison Gt (PVar 1 "x") 0) .=>
Inj Success
expectPass code $ Valid $ (CoreProp $ IntegerComparison Eq (PVar 1 "x") 5) .=>
Inj Success .&&
(CoreProp $ BoolComparison Eq (Inj Result :: Prop 'TyBool) sTrue)
describe "enforce.purity.read" $ do
let code =
[text|
(defschema row i:integer)
(deftable integers:{row})
(defun test:bool ()
(enforce
(= 1 (at "i" (read integers "key")))
""))
|]
expectFailureMessage code "disallowed DB read"
describe "enforce.purity.write" $ do
let code =
[text|
(defschema row i:integer)
(deftable integers:{row})
(defun test:bool ()
(enforce
(= "key" (write integers "key" {"i": 10}))
""))
|]
expectFailureMessage code "disallowed DB write"
describe "enforce.purity.insert" $ do
let code =
[text|
(defschema row i:integer)
(deftable integers:{row})
(defun test:bool ()
(enforce
(= "key" (insert integers "key" {"i": 10}))
""))
|]
expectFailureMessage code "disallowed DB insert"
describe "enforce.purity.update" $ do
let code =
[text|
(defschema row i:integer)
(deftable integers:{row})
(defun test:bool ()
(enforce
(= "key" (update integers "key" {"i": 10}))
""))
|]
expectFailureMessage code "disallowed DB update"
describe "read-keyset.equality" $ do
let code =
[text|
(defun test:bool ()
(enforce
(= (read-keyset "ks")
(read-keyset (+ "k" "s")))
"keysets equality failed"))
|]
expectPass code $ Valid (Inj Success)
--
-- TODO: test use of read-keyset from property once possible
--
describe "enforce-keyset.name.static" $ do
let code =
[text|
(defun test:bool ()
(enforce-keyset 'ks))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable (Inj Success)
expectPass code $ Valid $ Inj Success .=> Inj (GuardPassed "ks")
expectFail code $ Valid $ Inj Success .=> Inj (GuardPassed "different-ks")
describe "enforce-keyset.name.dynamic" $ do
let code =
[text|
(defun test:bool ()
(enforce-keyset (+ "k" "s")))
|]
expectPass code $ Valid $ sNot (Inj (GuardPassed "ks")) .=> Abort'
describe "enforce-keyset.value" $ do
let code =
[text|
(defun test:bool (ks:keyset)
(enforce-keyset ks))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable Success'
describe "enforce-keyset.purity" $ do
let code =
[text|
(defschema row ks:keyset)
(deftable keysets:{row})
(defun test:bool ()
(enforce-keyset (at "ks" (read keysets "123"))))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable Success'
-- this used to verify that `enforce-keyset` failed on read
-- but this hasn't been true for a while, arguments to
-- `enforce-keyset` are normally evaluated, while the actual
-- enforcement is pure. This test isn't terribly useful
-- but leaving the code around if needed later.
-- expectFailureMessage code "disallowed DB read"
describe "enforce-guard" $ do
let code =
[text|
(defun test:bool (ks:keyset)
(enforce-guard ks))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable Success'
describe "enforce-guard.purity" $ do
let code =
[text|
(defschema row ks:keyset)
(deftable keysets:{row})
(defun test:bool ()
(enforce-guard (at "ks" (read keysets "123"))))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable Success'
-- this used to verify that `enforce-guard` failed on read
-- but this hasn't been true for a while, arguments to
-- `enforce-guard` are normally evaluated, while the actual
-- enforcement is pure. This test isn't terribly useful
-- but leaving the code around if needed later.
-- expectFailureMessage code "disallowed DB read"
describe "read-decimal" $ do
let code =
[text|
(defun test:decimal ()
(read-decimal "foo"))
|]
expectPass code $ Satisfiable $ CoreProp $ DecimalComparison Eq (Inj Result) 0
expectPass code $ Satisfiable $ CoreProp $ DecimalComparison Eq (Inj Result) 1
--
-- TODO: test use of read-decimal from property once possible
--
describe "read-integer" $ do
let code =
[text|
(defun test:integer ()
(+ (read-integer "key")
(read-integer (+ "ke" "y"))))
|]
expectPass code $ Satisfiable $ CoreProp $ IntegerComparison Eq (Inj Result) 0
expectFail code $ Satisfiable $ CoreProp $ IntegerComparison Eq (Inj Result) 1 -- <- FAIL
expectPass code $ Satisfiable $ CoreProp $ IntegerComparison Eq (Inj Result) 2
--
-- TODO: test use of read-integer from property once possible
--
describe "read-string" $ do
describe "value can be anything" $ do
let code =
[text|
(defun test:bool ()
(enforce
(= "arbitrary string"
(read-string "some-key"))
""))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable Success'
describe "read always produces the same value" $ do
let code =
[text|
(defun test:bool ()
(enforce
(= (read-string "some-key")
(read-string "some-key"))
""))
|]
expectPass code $ Valid Success'
describe "enforce-keyset.row-level.at" $ do
let code =
[text|
(defschema token-row
name:string
balance:integer
ks:keyset)
(deftable tokens:{token-row})
(defun test:integer (acct:string)
(let* ((obj (read tokens acct))
(ks (at 'ks obj))
(bal (at 'balance obj))
)
(enforce-keyset ks)
bal
))
|]
expectPass code $ Valid $ Inj Success .=>
Inj (RowEnforced "tokens" "ks" (PVar 1 "acct"))
describe "enforce-keyset.row-level.read" $ do
let code =
[text|
(defschema token-row
name:string
balance:integer
ks:keyset)
(deftable tokens:{token-row})
(defun test:integer (acct:string)
(with-read tokens acct { "ks" := ks, "balance" := bal }
(enforce-keyset ks)
bal))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable (Inj Success)
expectPass code $ Valid $ sNot $ Inj $ Exists 1 "row" (EType SStr) $
Inj $ RowWrite "tokens" (PVar 1 "row")
expectPass code $ Valid $ Inj $ Forall 1 "row" (EType SStr) $
CoreProp $ IntegerComparison Eq
(Inj (RowWriteCount "tokens" (PVar 1 "row"))) 0
expectPass code $ Valid $ Inj Success .=>
Inj (Exists 1 "row" (EType SStr) (Inj $ RowRead "tokens" (PVar 1 "row")))
expectPass code $ Valid $ Inj Success .=>
Inj (Exists 1 "row" (EType SStr)
(CoreProp $ IntegerComparison Eq
(Inj (RowReadCount "tokens" (PVar 1 "row"))) 1))
expectPass code $ Satisfiable $ Inj $ Exists 1 "row" (EType SStr) $
Inj $ RowEnforced "tokens" "ks" (PVar 1 "row")
expectPass code $ Satisfiable $ Inj $ Exists 1 "row" (EType SStr) $
sNot $ Inj $ RowEnforced "tokens" "ks" (PVar 1 "row")
expectPass code $ Valid $ Inj Success .=> (Inj $ Forall 1 "row" (EType SStr) $
Inj (RowRead "tokens" (PVar 1 "row")) .=>
Inj (RowEnforced "tokens" "ks" (PVar 1 "row")))
expectPass code $ Valid $ Inj Success .=>
Inj (RowEnforced "tokens" "ks" (PVar 1 "acct"))
describe "enforce-keyset.row-level.read.syntax" $ do
let code =
[text|
(defschema token-row
name:string
balance:integer
ks:keyset)
(deftable tokens:{token-row})
(defun test:integer (acct:string)
@doc "test"
@model
[(property (forall (row:string) (row-enforced "tokens" "ks" row)))]
(with-read tokens acct { "ks" := ks, "balance" := bal }
(enforce-keyset ks)
bal))
|]
-- TODO: come up with better tests. Right now this just tests that this
-- parses correctly.
expectPass code $ Satisfiable Abort'
describe "enforce-keyset.row-level.multiple-keysets" $ do
let code =
[text|
(defschema token-row
name:string
balance:integer
ks1:keyset
ks2:keyset)
(deftable tokens:{token-row})
(defun test:integer (acct:string)
(with-read tokens acct { "ks1" := ks, "balance" := bal }
(enforce-keyset ks)
bal))
|]
expectPass code $ Valid $ Inj $ Forall 1 "row" (EType SStr) $
Inj (RowRead "tokens" (PVar 1 "row")) .=>
Inj (RowEnforced "tokens" "ks1" (PVar 1 "row"))
-- Using the other keyset:
expectFail code $ Valid $ Inj $ Forall 1 "row" (EType SStr) $
Inj (RowRead "tokens" (PVar 1 "row")) .=>
Inj (RowEnforced "tokens" "ks2" (PVar 1 "row"))
describe "enforce-keyset.row-level.write" $ do
let code =
[text|
(defschema token-row
name:string
balance:integer
ks:keyset)
(deftable tokens:{token-row})
(defun test:integer (acct:string)
(with-read tokens acct { "ks" := ks, "balance" := bal }
(let ((new-bal (+ bal 1)))
(update tokens acct {"balance": new-bal})
(enforce-keyset ks)
new-bal)))
|]
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable $ Inj Success
expectPass code $ Valid $ Inj Success .=>
Inj (Exists 1 "row" (EType SStr)
(Inj (RowWrite "tokens" (PVar 1 "row"))))
expectPass code $ Valid $ Inj Success .=>
Inj (Exists 1 "row" (EType SStr)
(CoreProp $ IntegerComparison Eq
(Inj (RowWriteCount "tokens" (PVar 1 "row"))) 1))
expectPass code $ Valid $ Inj Success .=>
Inj (Exists 1 "row" (EType SStr)
(Inj (RowRead "tokens" (PVar 1 "row"))))
expectPass code $ Valid $ Inj Success .=>
Inj (Exists 1 "row" (EType SStr)
(CoreProp $ IntegerComparison Eq
(Inj (RowReadCount "tokens" (PVar 1 "row"))) 1))
expectPass code $ Valid $ Inj Success .=>
Inj (Exists 1 "row" (EType SStr)
(Inj (RowEnforced "tokens" "ks" (PVar 1 "row"))))
expectPass code $ Satisfiable $ Inj $ Exists 1 "row" (EType SStr) $
sNot $ Inj $ RowEnforced "tokens" "ks" (PVar 1 "row")
expectPass code $ Valid $ Inj $ Forall 1 "row" (EType SStr) $
Inj (RowRead "tokens" (PVar 1 "row")) .=>
Inj (RowEnforced "tokens" "ks" (PVar 1 "row"))
expectPass code $ Valid $ Inj $ Forall 1 "row" (EType SStr) $
Inj (RowWrite "tokens" (PVar 1 "row")) .=>
Inj (RowEnforced "tokens" "ks" (PVar 1 "row"))
expectPass code $ Valid $ Inj (RowWrite "tokens" (PVar 1 "acct"))
.=> Inj (RowEnforced "tokens" "ks" (PVar 1 "acct"))
describe "enforce-keyset.row-level.write-count" $ do
let code =
[text|
(defschema token-row balance:integer)
(deftable tokens:{token-row})
(defun test:string ()
(write tokens 'joel { 'balance: 10 })
(write tokens 'joel { 'balance: 100 }))
|]
expectPass code $ Valid $
CoreProp $ IntegerComparison Eq
(Inj (RowWriteCount "tokens" (Lit' "joel"))) 2
expectPass code $ Valid $ PNot $
CoreProp $ IntegerComparison Eq
(Inj (RowWriteCount "tokens" (Lit' "joel"))) 1
expectPass code $ Valid $ PNot $
CoreProp $ IntegerComparison Eq
(Inj (RowWriteCount "tokens" (Lit' "joel"))) 3
expectPass code $ Valid $
CoreProp $ IntegerComparison Eq
(Inj (RowReadCount "tokens" (Lit' "joel"))) 0
describe "enforce-keyset.row-level.write.invalidation" $ do
let code =
[text|
(defschema token-row
name:string
balance:integer
ks:keyset)
(deftable tokens:{token-row})
(defun test:bool (acct:string user-controlled:keyset)
;; Overwrite existing keyset:
(update tokens acct {"ks": user-controlled})
;; Then standard row-level keyset enforcement occurs:
(with-read tokens acct { "ks" := ks, "balance" := bal }
(let ((new-bal (+ bal 1)))
(update tokens acct {"balance": new-bal})
(enforce-keyset ks)
new-bal)))
|]
-- When a user overwrites an existing keyset and then enforces *that* new
-- keyset, we don't consider the row to have been enforced due to
-- invalidation:
--
expectFail code $ Valid $ Inj $ Forall 1 "row" (EType SStr) $
Inj (RowRead "tokens" (PVar 1 "row")) .=>
Inj (RowEnforced "tokens" "ks" (PVar 1 "row"))
expectFail code $ Valid $ Inj $ Forall 1 "row" (EType SStr) $
Inj (RowWrite "tokens" (PVar 1 "row")) .=>
Inj (RowEnforced "tokens" "ks" (PVar 1 "row"))
describe "enforce-guard.row-level" $ do
let code =
[text|
(defschema token-row
name:string
balance:integer
g:guard)
(deftable tokens:{token-row})
(defun test:integer (acct:string)
@model
[(property (forall (row:string)
(when (row-read tokens row)
(row-enforced tokens "g" row))))]
(with-read tokens acct { "g" := g, "balance" := bal }
(enforce-guard g)
bal))
|]
expectVerified code
describe "keyset-ref-guard" $ do
let code =
[text|
(defun test:bool ()
@model [(property (authorized-by "foo"))]
(enforce-guard (keyset-ref-guard "foo")))
|]
expectVerified code
describe "create-pact-guard" $ do
let code =
[text|
(defun test:bool ()
(enforce-guard (create-pact-guard "foo")))
|]
-- Depending on whether we're executing in a pact:
expectPass code $ Satisfiable Abort'
expectPass code $ Satisfiable Success'
describe "create-user-guard passing" $ do
let code =
[text|
(defun enforce-range:bool (x:integer)
(enforce (> x 1) ""))