-
Notifications
You must be signed in to change notification settings - Fork 213
/
GameModel.hs
598 lines (524 loc) · 18.2 KB
/
GameModel.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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -Wno-name-shadowing -Wno-unused-matches -Wno-unused-do-bind -Wno-unused-local-binds #-}
module GameModel where
import Control.Applicative
import Control.Lens hiding (elements)
import Control.Monad
import System.Random
-- START import Log
import Control.Monad.Freer.Extras.Log (LogLevel (..))
-- END import Log
import Data.Maybe
import Test.QuickCheck
-- START import Contract.Test
import Plutus.Contract.Test
-- END import Contract.Test
-- START import ContractModel
import Plutus.Contract.Test.ContractModel
-- END import ContractModel
import Plutus.Contract.Test.ContractModel as ContractModel
-- START import Game
import Plutus.Contracts.GameStateMachine as G
-- END import Game
-- START import Ada
import Ledger.Ada qualified as Ada
import Ledger.Value
-- END import Ada
-- START import Scripts
import Ledger.Typed.Scripts qualified as Scripts
-- END import Scripts
-- START import Emulator
import Plutus.Trace.Emulator as Trace
-- END import Emulator
-- START import Contract.Security
import Plutus.Contract.Secrets
-- END import Contract.Security
-- START import TimeSlot
import Ledger.TimeSlot qualified as TimeSlot
-- END import TimeSlot
-- START import Data.Default
import Data.Default (Default (def))
-- END import Data.Default
-- START gameParam
gameParam :: G.GameParam
gameParam = G.GameParam (mockWalletPaymentPubKeyHash w1) (TimeSlot.scSlotZeroTime def)
-- END gameParam
-- * QuickCheck model
-- START GameModel
data GameModel = GameModel
{ _gameValue :: Integer
, _hasToken :: Maybe Wallet
, _currentSecret :: String }
deriving (Show)
makeLenses 'GameModel
-- END GameModel
deriving instance Eq (ContractInstanceKey GameModel w schema err)
deriving instance Show (ContractInstanceKey GameModel w schema err)
-- START instance ContractModel and Action type
instance ContractModel GameModel where
data Action GameModel = Lock Wallet String Integer
| Guess Wallet String String Integer
| GiveToken Wallet
deriving (Eq, Show)
-- END instance ContractModel and Action type
-- START ContractInstanceKey
data ContractInstanceKey GameModel w schema err where
WalletKey :: Wallet -> ContractInstanceKey GameModel () G.GameStateMachineSchema G.GameError
-- END ContractInstanceKey
-- START initialState
initialState = GameModel
{ _gameValue = 0
, _hasToken = Nothing
, _currentSecret = ""
}
-- END initialState
-- START initialHandleSpecs
initialHandleSpecs = [ ContractInstanceSpec (WalletKey w) w G.contract | w <- wallets ]
-- END initialHandleSpecs
-- START perform
perform handle s cmd = case cmd of
Lock w new val -> do
callEndpoint @"lock" (handle $ WalletKey w)
LockArgs { lockArgsGameParam = gameParam
, lockArgsSecret = secretArg new
, lockArgsValue = Ada.lovelaceValueOf val
}
delay 2
Guess w old new val -> do
callEndpoint @"guess" (handle $ WalletKey w)
GuessArgs{ guessArgsGameParam = gameParam
, guessArgsOldSecret = old
, guessArgsNewSecret = secretArg new
, guessArgsValueTakenOut = Ada.lovelaceValueOf val }
delay 1
GiveToken w' -> do
let w = fromJust (s ^. contractState . hasToken)
payToWallet w w' guessTokenVal
delay 1
-- END perform
-- 'nextState' descibes how each command affects the state of the model
nextState (Lock w secret val) = do
wasUnlocked <- (Nothing ==) <$> viewContractState hasToken
when wasUnlocked $ do
hasToken $= Just w
currentSecret $= secret
gameValue $= val
mint guessTokenVal
deposit w guessTokenVal
withdraw w $ Ada.lovelaceValueOf val
wait 2
-- START nextState Guess
nextState (Guess w old new val) = do
correctGuess <- (old ==) <$> viewContractState currentSecret
holdsToken <- (Just w ==) <$> viewContractState hasToken
enoughAda <- (val <=) <$> viewContractState gameValue
when (correctGuess && holdsToken && enoughAda) $ do
currentSecret $= new
gameValue $~ subtract val
deposit w $ Ada.lovelaceValueOf val
wait 1
-- END nextState Guess
nextState (GiveToken w) = do
w0 <- fromJust <$> viewContractState hasToken
transfer w0 w guessTokenVal
hasToken $= Just w
wait 1
-- START arbitraryAction
arbitraryAction s = oneof $
[ Lock <$> genWallet <*> genGuess <*> genValue ] ++
[ frequency $
[ (10, Guess w <$> genGuess <*> genGuess <*> choose (0, val))
| Just w <- [tok] ] ++
[ (1, Guess <$> genWallet <*> genGuess <*> genGuess <*> genValue) ] ] ++
[ GiveToken <$> genWallet ]
where
tok = s ^. contractState . hasToken
val = s ^. contractState . gameValue
-- END arbitraryAction
-- START precondition
precondition s cmd = case cmd of
Lock _ _ v -> isNothing tok
Guess w _ _ v -> tok == Just w && v <= val
GiveToken w -> isJust tok
where
tok = s ^. contractState . hasToken
val = s ^. contractState . gameValue
-- END precondition
-- START shrinkAction
shrinkAction _s (Lock w secret val) =
[Lock w' secret val | w' <- shrinkWallet w] ++
[Lock w secret val' | val' <- shrink val]
shrinkAction _s (GiveToken w) =
[GiveToken w' | w' <- shrinkWallet w]
shrinkAction _s (Guess w old new val) =
[Guess w' old new val | w' <- shrinkWallet w] ++
[Guess w old new val' | val' <- shrink val]
-- END shrinkAction
-- START monitoring
monitoring (s, _) (Guess w guess new v) =
tabulate "Guesses" [if guess == secret then "Right" else "Wrong"]
where secret = s ^. contractState . currentSecret
monitoring _ _ = id
-- END monitoring
-- START prop_Game
prop_Game :: Actions GameModel -> Property
prop_Game actions = propRunActions_ actions
-- END prop_Game
-- START propGame'
propGame' :: LogLevel -> Actions GameModel -> Property
propGame' l s = propRunActionsWithOptions
(set minLogLevel l defaultCheckOptions)
defaultCoverageOptions
(\ _ -> pure True)
s
-- END propGame'
-- START Generators
genWallet :: Gen Wallet
genWallet = elements wallets
genGuess :: Gen String
genGuess = elements ["hello", "secret", "hunter2", "*******"]
genValue :: Gen Integer
genValue = getNonNegative <$> arbitrary
-- END Generators
-- START shrinkWallet
shrinkWallet :: Wallet -> [Wallet]
shrinkWallet w = [w' | w' <- wallets, w' < w]
-- END shrinkWallet
guesses :: [String]
guesses = ["hello", "secret", "hunter2", "*******"]
-- START delay
delay :: Int -> EmulatorTraceNoStartContract ()
delay n = void $ waitNSlots (fromIntegral n)
-- END delay
-- Dynamic Logic ----------------------------------------------------------
prop_UnitTest :: Property
prop_UnitTest = withMaxSuccess 1 $ forAllDL unitTest prop_Game
-- START propDL
propDL :: DL GameModel () -> Property
propDL dl = forAllDL dl prop_Game
-- END propDL
-- START unitTest
unitTest :: DL GameModel ()
unitTest = do
val <- forAllQ $ chooseQ (3, 20)
action $ Lock w1 "hello" val
action $ GiveToken w2
action $ Guess w2 "hello" "new secret" 3
-- END unitTest
-- START badUnitTest
badUnitTest :: DLTest GameModel
badUnitTest =
BadPrecondition
[Witness (1 :: Integer),
Do $ Lock w1 "hello" 1,
Do $ GiveToken w2]
[Action (Guess w2 "hello" "new secret" 3)]
(GameModel {_gameValue = 1, _hasToken = Just w2, _currentSecret = "hello"})
-- END badUnitTest
unitTest2 :: DL GameModel ()
unitTest2 = do
unitTest
action $ GiveToken w3
action $ Guess w3 "new secret" "hello" 4
unitTestFail :: DL GameModel ()
unitTestFail = do
action $ Lock w1 "hello" 8
action $ GiveToken w2
action $ Guess w2 "hola" "new secret" 3
-- START noLockedFunds
noLockedFunds :: DL GameModel ()
noLockedFunds = do
(w0, funds, pass) <- forAllQ (elementsQ wallets, chooseQ (1, 10000), elementsQ guesses)
action $ Lock w0 pass funds
anyActions_
w <- forAllQ $ elementsQ wallets
secret <- viewContractState currentSecret
val <- viewContractState gameValue
when (val > 0) $ do
monitor $ label "Unlocking funds"
action $ GiveToken w
action $ Guess w secret "" val
assertModel "Locked funds should be zero" $ isZero . lockedValue
-- END noLockedFunds
-- | Check that we can always get the money out of the guessing game (by guessing correctly).
prop_NoLockedFunds :: Property
prop_NoLockedFunds = forAllDL noLockedFunds prop_Game
-- | Wallets and game token.
-- START wallets
wallets :: [Wallet]
wallets = [w1, w2, w3]
-- END wallets
-- START guessTokenVal
guessTokenVal :: Value
guessTokenVal =
let sym = Scripts.forwardingMintingPolicyHash $ G.typedValidator gameParam
in G.token sym "guess"
-- END guessTokenVal
-- START testLock v1
testLock :: Property
testLock = prop_Game $ Actions [Lock w1 "hunter2" 0]
-- END testLock v1
testLockWithMaxSuccess :: ()
testLockWithMaxSuccess = ()
where
-- START testLock withMaxSuccess
testLock :: Property
testLock = withMaxSuccess 1 . prop_Game $ Actions [Lock w1 "hunter2" 0]
-- END testLock withMaxSuccess
-- START testDoubleLock
testDoubleLock :: Property
testDoubleLock = prop_Game $
Actions
[Lock w1 "*******" 0,
Lock w1 "secret" 0]
-- END testDoubleLock
anyActionsDef :: ()
anyActionsDef = ()
where
-- START anyActions
anyActions :: Int -> DL s ()
anyActions n = stopping
<|> weight (1 / fromIntegral n)
<|> (anyAction >> anyActions n)
-- END anyActions
-- Code for preliminary versions
v1_model :: ()
v1_model = ()
where
arbitraryAction :: ModelState GameModel -> Gen (Action GameModel)
-- START arbitraryAction v1
arbitraryAction s = oneof $
[ Lock <$> genWallet <*> genGuess <*> genValue ] ++
[ Guess <$> genWallet <*> genGuess <*> genGuess <*> genValue ] ++
[ GiveToken <$> genWallet ]
-- END arbitraryAction v1
nextState :: Action GameModel -> Spec GameModel ()
-- START nextState Lock v1
nextState (Lock w secret val) = do
hasToken $= Just w
currentSecret $= secret
gameValue $= val
mint guessTokenVal
deposit w guessTokenVal
withdraw w $ Ada.lovelaceValueOf val
-- END nextState Lock v1
-- START nextState Guess v1
nextState (Guess w old new val) = do
correctGuess <- (old ==) <$> viewContractState currentSecret
holdsToken <- (Just w ==) <$> viewContractState hasToken
enoughAda <- (val <=) <$> viewContractState gameValue
when (correctGuess && holdsToken && enoughAda) $ do
currentSecret $= new
gameValue $~ subtract val
deposit w $ Ada.lovelaceValueOf val
-- END nextState Guess v1
-- START nextState GiveToken v1
nextState (GiveToken w) = do
w0 <- fromJust <$> viewContractState hasToken
transfer w0 w guessTokenVal
hasToken $= Just w
-- END nextState GiveToken v1
precondition :: ModelState GameModel -> Action GameModel -> Bool
-- START precondition v1
precondition s (GiveToken _) = isJust tok
where
tok = s ^. contractState . hasToken
precondition s _ = True
-- END precondition v1
perform :: HandleFun GameModel -> ModelState GameModel -> Action GameModel -> EmulatorTraceNoStartContract ()
-- START perform v1
perform handle s cmd = case cmd of
Lock w new val -> do
callEndpoint @"lock" (handle $ WalletKey w)
LockArgs{ lockArgsGameParam = gameParam
, lockArgsSecret = secretArg new
, lockArgsValue = Ada.lovelaceValueOf val}
Guess w old new val -> do
callEndpoint @"guess" (handle $ WalletKey w)
GuessArgs{ guessArgsGameParam = gameParam
, guessArgsOldSecret = old
, guessArgsNewSecret = secretArg new
, guessArgsValueTakenOut = Ada.lovelaceValueOf val}
GiveToken w' -> do
let w = fromJust (s ^. contractState . hasToken)
payToWallet w w' guessTokenVal
return ()
-- END perform v1
v2_model :: ()
v2_model = ()
where
nextState :: Action GameModel -> Spec GameModel ()
-- START nextState Lock v2
nextState (Lock w secret val) = do
hasToken $= Just w
currentSecret $= secret
gameValue $= val
mint guessTokenVal
deposit w guessTokenVal
withdraw w $ Ada.lovelaceValueOf val
wait 2
-- END nextState Lock v2
-- START nextState Guess partial
nextState (Guess w old new val) = do
correctGuess <- (old ==) <$> viewContractState currentSecret
-- ...
-- END nextState Guess partial
return ()
nextState _ = return ()
precondition :: ModelState GameModel -> Action GameModel -> Bool
-- START precondition v2
precondition s cmd = case cmd of
Lock {} -> isNothing tok
Guess {} -> True
GiveToken _ -> isJust tok
where
tok = s ^. contractState . hasToken
-- END precondition v2
arbitraryAction :: ModelState GameModel -> Gen (Action GameModel)
-- START arbitaryAction v2
arbitraryAction s = oneof $
[ Lock <$> genWallet <*> genGuess <*> genValue ] ++
[ Guess w <$> genGuess <*> genGuess <*> choose (0, val)
| Just w <- [tok] ] ++
[ GiveToken <$> genWallet ]
where
tok = s ^. contractState . hasToken
val = s ^. contractState . gameValue
-- END arbitaryAction v2
v3_model :: ()
v3_model = ()
where
precondition :: ModelState GameModel -> Action GameModel -> Bool
-- START precondition v3
precondition s cmd = case cmd of
Lock {} -> isNothing tok
Guess w _ _ _ -> tok == Just w
GiveToken _ -> isJust tok
where
tok = s ^. contractState . hasToken
-- END precondition v3
unitTest_v1 :: ()
unitTest_v1 = ()
where
-- START unitTest v1
unitTest :: DL GameModel ()
unitTest = do
action $ Lock w1 "hello" 10
action $ GiveToken w2
action $ Guess w2 "hello" "new secret" 3
-- END unitTest v1
unitTest_v2 :: ()
unitTest_v2 = ()
where
-- START unitTest v2
unitTest :: DL GameModel ()
unitTest = do
val <- forAllQ $ chooseQ (1, 20)
action $ Lock w1 "hello" val
action $ GiveToken w2
action $ Guess w2 "hello" "new secret" 3
-- END unitTest v2
noLockedFunds_v1 :: ()
noLockedFunds_v1 = ()
where
-- START noLockedFunds v1
noLockedFunds :: DL GameModel ()
noLockedFunds = do
anyActions_
assertModel "Locked funds should be zero" $ isZero . lockedValue
-- END noLockedFunds v1
noLockedFunds_v2 :: ()
noLockedFunds_v2 = ()
where
-- START noLockedFunds v2
noLockedFunds :: DL GameModel ()
noLockedFunds = do
anyActions_
w <- forAllQ $ elementsQ wallets
secret <- viewContractState currentSecret
val <- viewContractState gameValue
action $ Guess w "" secret val
assertModel "Locked funds should be zero" $ isZero . lockedValue
-- END noLockedFunds v2
noLockedFunds_v3 :: ()
noLockedFunds_v3 = ()
where
-- START noLockedFunds v3
noLockedFunds :: DL GameModel ()
noLockedFunds = do
anyActions_
w <- forAllQ $ elementsQ wallets
secret <- viewContractState currentSecret
val <- viewContractState gameValue
when (val > 0) $ do
action $ Guess w "" secret val
assertModel "Locked funds should be zero" $ isZero . lockedValue
-- END noLockedFunds v3
noLockedFunds_v4 :: ()
noLockedFunds_v4 = ()
where
-- START noLockedFunds v4
noLockedFunds :: DL GameModel ()
noLockedFunds = do
anyActions_
w <- forAllQ $ elementsQ wallets
secret <- viewContractState currentSecret
val <- viewContractState gameValue
when (val > 0) $ do
action $ GiveToken w
action $ Guess w "" secret val
assertModel "Locked funds should be zero" $ isZero . lockedValue
-- END noLockedFunds v4
noLockedFunds_v5 :: ()
noLockedFunds_v5 = ()
where
-- START noLockedFunds v5
noLockedFunds :: DL GameModel ()
noLockedFunds = do
anyActions_
w <- forAllQ $ elementsQ wallets
secret <- viewContractState currentSecret
val <- viewContractState gameValue
when (val > 0) $ do
monitor $ label "Unlocking funds"
action $ GiveToken w
action $ Guess w secret "" val
assertModel "Locked funds should be zero" $ isZero . lockedValue
-- END noLockedFunds v5
typeSignatures :: forall state. ContractModel state => state -> state
typeSignatures = id
where
-- START nextState type
nextState :: Action state -> Spec state ()
-- END nextState type
nextState = ContractModel.nextState
-- START precondition type
precondition :: ModelState state -> Action state -> Bool
-- END precondition type
precondition = ContractModel.precondition
-- START perform type
perform :: HandleFun state -> ModelState state -> Action state -> EmulatorTraceNoStartContract ()
-- END perform type
perform = ContractModel.perform
-- START shrinkAction type
shrinkAction :: ModelState state -> Action state -> [Action state]
-- END shrinkAction type
shrinkAction = ContractModel.shrinkAction
-- START monitoring type
monitoring :: (ModelState state, ModelState state) -> Action state -> Property -> Property
-- END monitoring type
monitoring = ContractModel.monitoring
-- START chooseQ type
chooseQ :: (Arbitrary a, Random a, Ord a) => (a, a) -> Quantification a
-- END chooseQ type
chooseQ = ContractModel.chooseQ