-
Notifications
You must be signed in to change notification settings - Fork 211
/
Arbitrary.hs
393 lines (349 loc) · 12.6 KB
/
Arbitrary.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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedLabels #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Cardano.Pool.DB.Arbitrary
( MultiPoolCertificateSequence (..)
, getMultiPoolCertificateSequence
, SinglePoolCertificateSequence (..)
, StakePoolsFixture (..)
, genStakePoolMetadata
, isValidSinglePoolCertificateSequence
) where
import Prelude
import Cardano.Wallet.Gen
( genPercentage, genSlotNo, shrinkSlotNo )
import Cardano.Wallet.Primitive.Slotting
( unsafeEpochNo )
import Cardano.Wallet.Primitive.Types
( BlockHeader (..)
, CertificatePublicationTime (..)
, EpochNo (..)
, Hash (..)
, PoolCertificate (..)
, PoolId (..)
, PoolMetadataSource (..)
, PoolMetadataSource (..)
, PoolOwner (..)
, PoolRegistrationCertificate (..)
, PoolRetirementCertificate (..)
, Settings (..)
, SlotInEpoch (..)
, SlotNo (..)
, SlotNo (..)
, StakePoolMetadata (..)
, StakePoolMetadataHash (..)
, StakePoolMetadataUrl (..)
, StakePoolTicker (..)
, getPoolCertificatePoolId
, setPoolCertificatePoolId
)
import Control.Arrow
( second )
import Control.Monad
( foldM, replicateM )
import Data.Function
( (&) )
import Data.Generics.Internal.VL.Lens
( (^.) )
import Data.Maybe
( fromJust )
import Data.Ord
( Down (..) )
import Data.Quantity
( Quantity (..) )
import Data.Text
( Text )
import Data.Word
( Word32, Word64 )
import Data.Word.Odd
( Word31 )
import Network.URI
( URI, parseURI )
import Test.QuickCheck
( Arbitrary (..)
, Gen
, PrintableString (..)
, arbitraryBoundedEnum
, arbitrarySizedBoundedIntegral
, choose
, elements
, frequency
, genericShrink
, oneof
, shrinkIntegral
, shuffle
, vector
, vectorOf
)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as B8
import qualified Data.List as L
import qualified Data.Text as T
{-------------------------------------------------------------------------------
Modifiers
-------------------------------------------------------------------------------}
data StakePoolsFixture = StakePoolsFixture
{ poolSlots :: [(PoolId, BlockHeader)]
, rollbackSlots :: [SlotNo] }
deriving stock (Eq, Show)
genPrintableText :: Gen Text
genPrintableText = T.pack . getPrintableString <$> arbitrary
{-------------------------------------------------------------------------------
Stake Pools
-------------------------------------------------------------------------------}
instance Arbitrary CertificatePublicationTime where
arbitrary = CertificatePublicationTime <$> arbitrary <*> arbitrary
shrink = genericShrink
instance Arbitrary SlotNo where
arbitrary = genSlotNo
shrink = shrinkSlotNo
instance Arbitrary SlotInEpoch where
shrink (SlotInEpoch x) = SlotInEpoch <$> shrink x
arbitrary = SlotInEpoch <$> choose (0, fromIntegral arbitraryChainLength)
instance Arbitrary EpochNo where
shrink (EpochNo x) = EpochNo <$> shrink x
arbitrary = unsafeEpochNo <$> choose (0, arbitraryEpochLength)
instance Arbitrary Word31 where
arbitrary = arbitrarySizedBoundedIntegral
shrink = shrinkIntegral
instance Arbitrary (Quantity "lovelace" Word64) where
shrink (Quantity q) = [ Quantity q' | q' <- shrink q ]
arbitrary = Quantity <$> arbitrary
arbitraryEpochLength :: Word32
arbitraryEpochLength = 100
arbitraryChainLength :: Word32
arbitraryChainLength = 10
-- NOTE Expected to have a high entropy
instance Arbitrary PoolId where
arbitrary = PoolId . BS.pack <$> vector 32
shrink (PoolId p) = do
let s = BS.unpack p
result <-
[ -- Zero out everything:
replicate 32 z
-- Zero out different halves:
, replicate 16 z <> drop 16 s
, take 16 s <> replicate 16 z
-- Zero out different quarters:
, replicate 8 z <> drop 8 s
, take 8 s <> replicate 8 z <> drop 16 s
, take 16 s <> replicate 8 z <> drop 24 s
, take 24 s <> replicate 8 z
]
[PoolId $ BS.pack result | result /= s]
where
z = toEnum 0
-- NOTE Excepted to have a reasonnably small entropy
instance Arbitrary PoolOwner where
arbitrary = do
byte <- elements ['0'..'8']
return $ PoolOwner $ B8.pack (replicate 32 byte)
instance Arbitrary PoolRegistrationCertificate where
shrink (PoolRegistrationCertificate pid owners m c pl md) =
(\pid' owners' -> PoolRegistrationCertificate pid' owners' m c pl md)
<$> shrink pid
<*> shrinkOwners owners
where
shrinkOwners os =
-- A valid registration certificate must have at least one owner:
[ps | ps <- shrink os, not (null ps)]
arbitrary = PoolRegistrationCertificate
<$> arbitrary
<*> genOwners
<*> genPercentage
<*> fmap Quantity arbitrary
<*> fmap Quantity arbitrary
<*> oneof [pure Nothing, Just <$> genMetadata]
where
genMetadata = (,)
<$> fmap StakePoolMetadataUrl genURL
<*> arbitrary
genOwners = do
-- A valid registration certificate must have at least one owner:
ownerCount <- choose (1, 4)
replicateM ownerCount arbitrary
genURL = do
protocol <- elements [ "http", "https" ]
fstP <- elements [ "cardano", "ada", "pool", "staking", "reward" ]
sndP <- elements [ "rocks", "moon", "digital", "server", "fast" ]
extP <- elements [ ".io", ".dev", ".com", ".eu" ]
pure $ protocol <> "://" <> fstP <> "-" <> sndP <> extP
instance Arbitrary PoolRetirementCertificate where
arbitrary = PoolRetirementCertificate
<$> arbitrary
<*> arbitrary
shrink = genericShrink
instance Arbitrary PoolCertificate where
arbitrary = oneof
[ Registration
<$> arbitrary
, Retirement
<$> arbitrary
]
shrink = genericShrink
-- | Represents a valid sequence of registration and retirement certificates
-- for a single pool.
--
data SinglePoolCertificateSequence = SinglePoolCertificateSequence
{ getSinglePoolId :: PoolId
, getSinglePoolCertificateSequence :: [PoolCertificate]
}
deriving (Eq, Show)
isValidSinglePoolCertificateSequence :: SinglePoolCertificateSequence -> Bool
isValidSinglePoolCertificateSequence
(SinglePoolCertificateSequence sharedPoolId certificates) =
allCertificatesReferToSamePool &&
firstCertificateIsNotRetirement
where
allCertificatesReferToSamePool =
all (== sharedPoolId) (getPoolCertificatePoolId <$> certificates)
firstCertificateIsNotRetirement = case certificates of
[] -> True
Registration _ : _ -> True
Retirement _ : _ -> False
instance Arbitrary SinglePoolCertificateSequence where
arbitrary = do
sharedPoolId <- arbitrary
frequency
[ (1, genEmptySequence sharedPoolId)
, (9, genNonEmptySequence sharedPoolId)
]
where
genEmptySequence sharedPoolId =
pure $ SinglePoolCertificateSequence sharedPoolId []
genNonEmptySequence sharedPoolId = do
-- We must start with a registration certificate:
certificates <- (:)
<$> (Registration <$> arbitrary)
<*> arbitrary
pure $ SinglePoolCertificateSequence sharedPoolId $
setPoolCertificatePoolId sharedPoolId <$> certificates
shrink (SinglePoolCertificateSequence sharedPoolId certificates) =
genericShrink certificates
& fmap (fmap (setPoolCertificatePoolId sharedPoolId))
& fmap (SinglePoolCertificateSequence sharedPoolId)
& filter isValidSinglePoolCertificateSequence
-- | Represents valid sequences of registration and retirement certificates
-- for multiple pools.
--
-- Use 'getMultiPoolCertificateSequence' to obtain a single, flattened list
-- of pool certificates.
--
data MultiPoolCertificateSequence = MultiPoolCertificateSequence
{ getSerializationMethod :: ListSerializationMethod
, getSinglePoolSequences :: [SinglePoolCertificateSequence]
}
deriving (Eq, Show)
instance Arbitrary MultiPoolCertificateSequence where
arbitrary = MultiPoolCertificateSequence
<$> arbitrary
<*> arbitrary
shrink mpcs =
[ MultiPoolCertificateSequence (getSerializationMethod mpcs) sequences
| sequences <- shrink (getSinglePoolSequences mpcs)
]
getMultiPoolCertificateSequence
:: MultiPoolCertificateSequence -> [PoolCertificate]
getMultiPoolCertificateSequence mpcs =
serializeLists
(getSerializationMethod mpcs)
(getSinglePoolCertificateSequence <$> getSinglePoolSequences mpcs)
-- | Indicates a way to serialize a list of lists into a single list.
--
data ListSerializationMethod
= Interleave
| Concatenate
deriving (Bounded, Enum, Eq, Show)
-- | Serializes a list of lists into a single list using the given
-- serialization method.
serializeLists :: ListSerializationMethod -> [[a]] -> [a]
serializeLists = \case
Interleave -> interleave
Concatenate -> concat
-- Interleaves the given list of lists together in a fair way.
--
-- Example:
--
-- >>> interleave [["a1", "a2", "a3"], ["b1", "b2", "b3"], ["c1", "c2", "c3"]]
-- ["a1", "b1", "c1", "a2", "b2", "c3", "a3", "b3", "c3"]
--
interleave :: [[a]] -> [a]
interleave = concat . L.transpose
instance Arbitrary ListSerializationMethod where
arbitrary = arbitraryBoundedEnum
shrink = const []
instance Arbitrary StakePoolMetadataHash where
arbitrary = fmap (StakePoolMetadataHash . BS.pack) (vector 32)
genStakePoolMetadata
:: StakePoolMetadataUrl
-> Gen StakePoolMetadata
genStakePoolMetadata (StakePoolMetadataUrl url) = StakePoolMetadata
<$> genStakePoolTicker
<*> genPrintableText
<*> oneof [ pure Nothing, Just <$> genPrintableText ]
<*> pure url
genStakePoolTicker :: Gen StakePoolTicker
genStakePoolTicker = (StakePoolTicker . T.pack) <$>
(choose (3,5) >>= \n -> vectorOf n (elements ['A','B'..'Z']))
instance Arbitrary StakePoolsFixture where
-- Shrink the second element
shrink (StakePoolsFixture (p0:(p, bh):ps) r) = map reconstruct $ shrink (bh ^. #slotNo)
where
reconstruct s = StakePoolsFixture
(p0:(p, bh {slotNo = s} :: BlockHeader):ps)
(map (\x -> if x == bh ^. #slotNo then s else x) r)
-- Shrink the first element
shrink (StakePoolsFixture ((p, bh):ps) r) = map reconstruct $ shrink (bh ^. #slotNo)
where
reconstruct s = StakePoolsFixture
((p, bh {slotNo = s} :: BlockHeader):ps)
(map (\x -> if x == bh ^. #slotNo then s else x) r)
shrink _ = []
arbitrary = do
poolsNumber <- choose (1, 5)
pools <- vector poolsNumber
slotsNumber <- choose (0, 2)
firstSlot <- arbitrary
slotsGenerated <-
foldM (appendPair pools) [] (generateNextSlots [firstSlot] slotsNumber)
rNum <- choose (1, slotsNumber + 1)
rSlots <-
(L.sortOn Down . take rNum) <$> shuffle (map snd slotsGenerated)
pure $ StakePoolsFixture (second mkBlockHeader <$> slotsGenerated) rSlots
where
mkBlockHeader :: SlotNo -> BlockHeader
mkBlockHeader s = BlockHeader
{ slotNo = s
, blockHeight = Quantity 0
, headerHash = Hash "00000000000000000000000000000001"
, parentHeaderHash = Hash "00000000000000000000000000000000"
}
generateNextSlots :: [SlotNo] -> Int -> [SlotNo]
generateNextSlots slots@(s:_) num =
if (num < 1) then
reverse slots
else
generateNextSlots ((s + 1):slots) (num - 1)
generateNextSlots [] _ = []
appendPair
:: [PoolId]
-> [(PoolId, SlotNo)]
-> SlotNo
-> Gen [(PoolId, SlotNo)]
appendPair pools pairs slot = do
pool <- elements pools
return $ (pool,slot):pairs
instance Arbitrary URI where
arbitrary = elements
[fromJust (parseURI "https://my.little.friend")
,fromJust (parseURI "http://its-friday.com:8000")]
instance Arbitrary PoolMetadataSource where
arbitrary = oneof [ pure None
, pure FetchDirect
, fmap FetchSMASH arbitrary]
instance Arbitrary Settings where
arbitrary = fmap Settings arbitrary