-
Notifications
You must be signed in to change notification settings - Fork 86
/
Node.hs
1327 lines (1192 loc) · 55.6 KB
/
Node.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 FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE QuantifiedConstraints #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{-# OPTIONS_GHC -Wno-incomplete-uni-patterns #-}
module Test.Ouroboros.Network.Testnet.Simulation.Node
( SimArgs (..)
, mainnetSimArgs
, NodeArgs (..)
, ServiceDomainName (..)
, DiffusionScript (..)
, HotDiffusionScript (..)
, DiffusionSimulationTrace (..)
, prop_diffusionScript_fixupCommands
, prop_diffusionScript_commandScript_valid
, diffusionSimulation
, Command (..)
-- * Tracing
, DiffusionTestTrace (..)
, iosimTracer
-- * Re-exports
, TestAddress (..)
, RelayAccessPoint (..)
, Script (..)
, module PeerSelection
) where
import Control.Applicative (Alternative)
import Control.Concurrent.Class.MonadMVar (MonadMVar)
import Control.Concurrent.Class.MonadSTM.Strict
import Control.Monad (forM)
import Control.Monad.Class.MonadAsync
import Control.Monad.Class.MonadFork
import Control.Monad.Class.MonadSay
import Control.Monad.Class.MonadST
import Control.Monad.Class.MonadThrow
import Control.Monad.Class.MonadTime.SI
import Control.Monad.Class.MonadTimer.SI
import Control.Monad.Fix
import Control.Tracer (Tracer (..), contramap, nullTracer, traceWith)
import Control.Monad.IOSim (IOSim, traceM)
import Data.ByteString.Char8 qualified as BSC
import Data.ByteString.Lazy qualified as BL
import Data.IP (IP (..))
import Data.List (delete, nubBy)
import Data.Map (Map)
import Data.Map qualified as Map
import Data.Maybe (catMaybes, fromMaybe, maybeToList)
import Data.Set (Set)
import Data.Set qualified as Set
import Data.Time.Clock (secondsToDiffTime)
import Data.Void (Void)
import System.Random (StdGen, mkStdGen)
import System.Random qualified as Random
import Network.DNS (Domain, TTL)
import Network.TypedProtocol.Core (PeerHasAgency (..))
import Network.TypedProtocol.PingPong.Type qualified as PingPong
import Ouroboros.Network.ConnectionHandler (ConnectionHandlerTrace)
import Ouroboros.Network.ConnectionManager.Types (AbstractTransitionTrace,
ConnectionManagerTrace)
import Ouroboros.Network.Diffusion.P2P qualified as Diff.P2P
import Ouroboros.Network.Driver.Limits (ProtocolSizeLimits (..),
ProtocolTimeLimits (..))
import Ouroboros.Network.InboundGovernor (InboundGovernorTrace,
RemoteTransitionTrace)
import Ouroboros.Network.Mux (MiniProtocolLimits (..))
import Ouroboros.Network.NodeToNode.Version (DiffusionMode (..))
import Ouroboros.Network.PeerSelection.Governor (DebugPeerSelection (..),
PeerSelectionTargets (..), TracePeerSelection)
import Ouroboros.Network.PeerSelection.Governor qualified as PeerSelection
import Ouroboros.Network.PeerSelection.LedgerPeers (AfterSlot (..),
LedgerPeersConsensusInterface (..), LedgerStateJudgement (..),
TraceLedgerPeers, UseLedgerPeers (..), accPoolStake)
import Ouroboros.Network.PeerSelection.PeerStateActions
(PeerSelectionActionsTrace)
import Ouroboros.Network.Protocol.BlockFetch.Codec (byteLimitsBlockFetch,
timeLimitsBlockFetch)
import Ouroboros.Network.Protocol.ChainSync.Codec (ChainSyncTimeout (..),
byteLimitsChainSync, timeLimitsChainSync)
import Ouroboros.Network.Protocol.Handshake.Version (Accept (Accept))
import Ouroboros.Network.Protocol.KeepAlive.Codec (byteLimitsKeepAlive,
timeLimitsKeepAlive)
import Ouroboros.Network.Protocol.Limits (shortWait, smallByteLimit)
import Ouroboros.Network.Server.RateLimiting (AcceptedConnectionsLimit (..))
import Ouroboros.Network.Server2 (ServerTrace)
import Ouroboros.Network.Snocket (Snocket, TestAddress (..))
import Ouroboros.Network.Block (BlockNo)
import Ouroboros.Network.Mock.ConcreteBlock (Block (..), BlockHeader (..))
import Ouroboros.Network.Testing.Data.Script
import Ouroboros.Network.Testing.Utils
import Simulation.Network.Snocket (BearerInfo (..), FD, SnocketTrace,
WithAddr (..), makeFDBearer, withSnocket)
import Test.Ouroboros.Network.Diffusion.Node qualified as NodeKernel
import Test.Ouroboros.Network.Diffusion.Node.NodeKernel (BlockGeneratorArgs,
NtCAddr, NtCVersion, NtCVersionData, NtNAddr, NtNAddr_ (IPAddr),
NtNVersion, NtNVersionData, ntnAddrToRelayAccessPoint,
randomBlockGenerationArgs)
import Test.Ouroboros.Network.PeerSelection.Instances qualified as PeerSelection
import Test.Ouroboros.Network.PeerSelection.RootPeersDNS (DNSLookupDelay (..),
DNSTimeout (..))
import Test.Ouroboros.Network.PeerSelection.RootPeersDNS qualified as PeerSelection hiding
(tests)
import Data.Bool (bool)
import Data.Function (on)
import Data.Typeable (Typeable)
import Ouroboros.Network.BlockFetch (FetchMode (..), TraceFetchClientState,
TraceLabelPeer (..))
import Ouroboros.Network.PeerSelection.Bootstrap (UseBootstrapPeers (..))
import Ouroboros.Network.PeerSelection.PeerAdvertise (PeerAdvertise (..))
import Ouroboros.Network.PeerSelection.PeerSharing (PeerSharing)
import Ouroboros.Network.PeerSelection.PeerTrustable (PeerTrustable)
import Ouroboros.Network.PeerSelection.RelayAccessPoint (DomainAccessPoint (..),
PortNumber, RelayAccessPoint (..))
import Ouroboros.Network.PeerSelection.RootPeersDNS.DNSActions (DNSLookupType)
import Ouroboros.Network.PeerSelection.RootPeersDNS.LocalRootPeers
(TraceLocalRootPeers)
import Ouroboros.Network.PeerSelection.RootPeersDNS.PublicRootPeers
(TracePublicRootPeers)
import Ouroboros.Network.PeerSelection.State.LocalRootPeers (HotValency (..),
WarmValency (..))
import Ouroboros.Network.Protocol.PeerSharing.Codec (byteLimitsPeerSharing,
timeLimitsPeerSharing)
import Test.Ouroboros.Network.LedgerPeers (LedgerPools (..), genLedgerPoolsFrom)
import Test.Ouroboros.Network.PeerSelection.LocalRootPeers ()
import Test.QuickCheck
-- | Diffusion Simulator Arguments
--
-- Contains all necessary randomly generated values needed to run diffusion in
-- simulation.
--
data SimArgs =
SimArgs
{ saSlot :: DiffTime
-- ^ 'randomBlockGenerationArgs' slot duration argument
, saQuota :: Int
-- ^ 'randomBlockGenerationArgs' quota value
}
instance Show SimArgs where
show SimArgs { saSlot, saQuota } =
unwords [ "SimArgs"
, show saSlot
, show saQuota
]
data ServiceDomainName =
DomainName Domain
-- ^ a well configured domain name
| Misconfigured Domain
-- ^ a domain name which is advertised but its' IPs are wrong.
| NoDomainName
deriving Show
instance Arbitrary ServiceDomainName where
arbitrary = frequency [ (8, pure $ DomainName (BSC.pack "iog.io"))
, (1, pure $ Misconfigured (BSC.pack "error.iog.io"))
, (1, pure $ NoDomainName)
]
shrink (DomainName _) = []
shrink (Misconfigured a) = [DomainName a]
shrink NoDomainName = []
-- | Diffusion Simulator Node Arguments
--
-- Contains all necessary randomly generated values needed to run a node in
-- simulation.
--
data NodeArgs =
NodeArgs
{ naSeed :: Int
-- ^ 'randomBlockGenerationArgs' seed argument
, naDiffusionMode :: DiffusionMode
, naMbTime :: Maybe DiffTime
-- ^ 'LimitsAndTimeouts' argument
, naPublicRoots :: Map RelayAccessPoint PeerAdvertise
-- ^ 'Interfaces' relays auxiliary value
, naBootstrapPeers :: Script UseBootstrapPeers
-- ^ 'Interfaces' relays auxiliary value
, naAddr :: NtNAddr
-- ^ 'Arguments' 'aIPAddress' value
, naPeerSharing :: PeerSharing
-- ^ 'Arguments' 'aOwnPeerSharing' value
, naLocalRootPeers :: [( HotValency
, WarmValency
, Map RelayAccessPoint ( PeerAdvertise
, PeerTrustable)
)]
, naLedgerPeers :: Script LedgerPools
-- ^ 'Arguments' 'LocalRootPeers' values
, naLocalSelectionTargets :: PeerSelectionTargets
-- ^ 'Arguments' 'aLocalSelectionTargets' value
, naDNSTimeoutScript :: Script DNSTimeout
-- ^ 'Arguments' 'aDNSTimeoutScript' value
, naDNSLookupDelayScript :: Script DNSLookupDelay
-- ^ 'Arguments' 'aDNSLookupDelayScript' value
, naChainSyncExitOnBlockNo :: Maybe BlockNo
, naChainSyncEarlyExit :: Bool
, naFetchModeScript :: Script FetchMode
}
instance Show NodeArgs where
show NodeArgs { naSeed, naDiffusionMode, naMbTime, naBootstrapPeers, naPublicRoots,
naAddr, naPeerSharing, naLocalRootPeers, naLocalSelectionTargets,
naDNSTimeoutScript, naDNSLookupDelayScript, naChainSyncExitOnBlockNo,
naChainSyncEarlyExit, naFetchModeScript } =
unwords [ "NodeArgs"
, "(" ++ show naSeed ++ ")"
, show naDiffusionMode
, "(" ++ show naMbTime ++ ")"
, "(" ++ show naPublicRoots ++ ")"
, "(" ++ show naBootstrapPeers ++ ")"
, "(" ++ show naAddr ++ ")"
, show naPeerSharing
, show naLocalRootPeers
, show naLocalSelectionTargets
, "(" ++ show naDNSTimeoutScript ++ ")"
, "(" ++ show naDNSLookupDelayScript ++ ")"
, "(" ++ show naChainSyncExitOnBlockNo ++ ")"
, show naChainSyncEarlyExit
, show naFetchModeScript
]
data Command = JoinNetwork DiffTime
| Kill DiffTime
| Reconfigure DiffTime
[( HotValency
, WarmValency
, Map RelayAccessPoint ( PeerAdvertise
, PeerTrustable)
)]
deriving Eq
instance Show Command where
showsPrec d (JoinNetwork delay) = showString "JoinNetwork "
. showsPrec d delay
showsPrec d (Kill delay) = showString "Kill "
. showsPrec d delay
showsPrec d (Reconfigure delay localRoots) = showString "Reconfigure "
. showsPrec d delay
. showString " "
. showsPrec d localRoots
genCommands :: [( HotValency
, WarmValency
, Map RelayAccessPoint (PeerAdvertise, PeerTrustable)
)]
-> Gen [Command]
genCommands localRoots = sized $ \size -> do
commands <- vectorOf size (frequency [ (10, JoinNetwork <$> delay)
, (6, Reconfigure
<$> delay
<*> subLocalRootPeers)
, (3, Kill <$> delay)
])
return (fixupCommands commands)
where
subLocalRootPeers :: Gen [( HotValency
, WarmValency
, Map RelayAccessPoint (PeerAdvertise, PeerTrustable)
)]
subLocalRootPeers = do
subLRP <- sublistOf localRoots
mapM (\(h, w, g) -> (h, w,) <$> (fmap Map.fromList . sublistOf . Map.toList $ g)) subLRP
delay = frequency [ (3, genDelayWithPrecision 65)
, (1, (/ 10) <$> genDelayWithPrecision 60)
]
fixupCommands :: [Command] -> [Command]
fixupCommands [] = []
fixupCommands (jn@(JoinNetwork _):t) = jn : go jn t
where
go :: Command -> [Command] -> [Command]
go _ [] = []
go prev (cmd:cmds) =
case (prev, cmd) of
(JoinNetwork _ , JoinNetwork _ ) -> go prev cmds
(Kill _ , Kill _ ) -> go prev cmds
(Kill _ , Reconfigure _ _ ) -> go prev cmds
(Reconfigure _ _ , JoinNetwork _ ) -> go prev cmds
_ -> cmd : go cmd cmds
fixupCommands (_:t) = fixupCommands t
-- | Simulation arguments.
--
-- Slot length needs to be greater than 0 else we get a livelock on the IOSim.
--
-- Quota values matches mainnet, so a slot length of 1s and 1 / 20 chance that
-- someone gets to make a block.
--
mainnetSimArgs :: Int -> SimArgs
mainnetSimArgs numberOfNodes =
SimArgs {
saSlot = secondsToDiffTime 1,
saQuota = if numberOfNodes > 0
then 20 `div` numberOfNodes
else 100
}
newtype SmallPeerSelectionTargets = SmallTargets PeerSelectionTargets
instance Arbitrary SmallPeerSelectionTargets where
arbitrary = sized $ \size -> do
targetNumberOfKnownPeers <- getNonNegative <$> resize size arbitrary
targetNumberOfRootPeers <- choose (0, targetNumberOfKnownPeers)
targetNumberOfEstablishedPeers <- choose (0, targetNumberOfKnownPeers)
targetNumberOfActivePeers <- choose (0, targetNumberOfEstablishedPeers)
targetNumberOfKnownBigLedgerPeers
<- getNonNegative <$> resize size arbitrary
targetNumberOfEstablishedBigLedgerPeers
<- choose (0 , targetNumberOfKnownBigLedgerPeers)
targetNumberOfActiveBigLedgerPeers
<- choose (0, targetNumberOfEstablishedBigLedgerPeers)
return $ SmallTargets $ PeerSelectionTargets {
targetNumberOfRootPeers,
targetNumberOfKnownPeers,
targetNumberOfEstablishedPeers,
targetNumberOfActivePeers,
targetNumberOfKnownBigLedgerPeers,
targetNumberOfEstablishedBigLedgerPeers,
targetNumberOfActiveBigLedgerPeers
}
shrink (SmallTargets (PeerSelectionTargets r k e a kb eb ab)) =
[ SmallTargets targets'
| (r',k',e',a',kb',eb',ab') <- shrink (r,k,e,a,kb,eb,ab)
, let targets' = PeerSelectionTargets r' k' e' a' kb' eb' ab'
, PeerSelection.sanePeerSelectionTargets targets'
]
-- | Given a NtNAddr generate the necessary things to run a node in
-- Simulation
genNodeArgs :: [RelayAccessInfo]
-> Int
-> [(HotValency, WarmValency, Map RelayAccessPoint (PeerAdvertise, PeerTrustable))]
-> RelayAccessInfo
-> Gen NodeArgs
genNodeArgs relays minConnected localRootPeers relay = flip suchThat hasUpstream $ do
-- Slot length needs to be greater than 0 else we get a livelock on
-- the IOSim.
--
-- Quota values matches mainnet, so a slot length of 1s and 1 / 20
-- chance that someone gets to make a block
seed <- arbitrary
-- Generating an InitiatorResponderMode node is 3 times more likely since we
-- want our tests to cover more this case.
diffusionMode <- frequency [ (1, pure InitiatorOnlyDiffusionMode)
, (3, pure InitiatorAndResponderDiffusionMode)
]
-- These values approximately correspond to false positive
-- thresholds for streaks of empty slots with 99% probability,
-- 99.9% probability up to 99.999% probability.
-- t = T_s [log (1-Y) / log (1-f)]
-- Y = [0.99, 0.999...]
--
-- T_s = slot length of 1s.
-- f = 0.05
-- The timeout is randomly picked per bearer to avoid all bearers
-- going down at the same time in case of a long streak of empty
-- slots. TODO: workaround until peer selection governor.
-- Taken from ouroboros-consensus/src/Ouroboros/Consensus/Node.hs
mustReplyTimeout <- Just <$> oneof (pure <$> [90, 135, 180, 224, 269])
-- Make sure our targets for active peers cover the maximum of peers
-- one generated
SmallTargets peerSelectionTargets <- resize (length relays * 2) arbitrary
`suchThat` hasActive
dnsTimeout <- arbitrary
dnsLookupDelay <- arbitrary
chainSyncExitOnBlockNo
<- frequency [ (1, Just . fromIntegral . getPositive
<$> (arbitrary :: Gen (Positive Int))
`suchThat` (\(Positive a) -> a < 5))
, (4, pure Nothing)
]
chainSyncEarlyExit <- frequency [ (1, pure True)
, (9, pure False)
]
peerSharing <- arbitrary
let (ledgerPeersRelays, publicRootsRelays) =
splitAt (length relays `div` 2) relays
publicRoots =
Map.fromList [ (makeRelayAccessPoint relay', advertise)
| relay' <- publicRootsRelays
, relay' /= relay
, let advertise = case relay' of
RelayAddrInfo _ip _port adv -> adv
RelayDomainInfo _dns _ip _port adv -> adv
]
ledgerPeers <- fmap (map makeRelayAccessPoint) <$> listOf (sublistOf ledgerPeersRelays)
ledgerPeerPools <- traverse genLedgerPoolsFrom ledgerPeers
firstLedgerPool <- arbitrary
let ledgerPeerPoolsScript = Script (firstLedgerPool :| ledgerPeerPools)
fetchModeScript <- fmap (bool FetchModeBulkSync FetchModeDeadline) <$> arbitrary
firstBootstrapPeer <- maybe DontUseBootstrapPeers UseBootstrapPeers
<$> arbitrary
bootstrapPeers <- listOf (maybe DontUseBootstrapPeers UseBootstrapPeers
<$> arbitrary)
let bootstrapPeersDomain = Script (firstBootstrapPeer :| bootstrapPeers)
return
$ NodeArgs
{ naSeed = seed
, naDiffusionMode = diffusionMode
, naMbTime = mustReplyTimeout
, naPublicRoots = publicRoots
-- TODO: we haven't been using public root peers so far because we set
-- `UseLedgerPeers 0`!
, naBootstrapPeers = bootstrapPeersDomain
, naAddr = makeNtNAddr relay
, naLocalRootPeers = localRootPeers
, naLedgerPeers = ledgerPeerPoolsScript
, naLocalSelectionTargets = peerSelectionTargets
, naDNSTimeoutScript = dnsTimeout
, naDNSLookupDelayScript = dnsLookupDelay
, naChainSyncExitOnBlockNo = chainSyncExitOnBlockNo
, naChainSyncEarlyExit = chainSyncEarlyExit
, naPeerSharing = peerSharing
, naFetchModeScript = fetchModeScript
}
where
hasActive :: SmallPeerSelectionTargets -> Bool
hasActive (SmallTargets (PeerSelectionTargets {
targetNumberOfActivePeers = y,
targetNumberOfActiveBigLedgerPeers = z
})) =
y + z >= minConnected
hasUpstream :: NodeArgs -> Bool
hasUpstream NodeArgs { naAddr, naPublicRoots, naLocalRootPeers } =
not (Map.null $ naPublicRoots
`Map.withoutKeys`
Set.fromList (maybeToList (ntnAddrToRelayAccessPoint naAddr)))
|| any id [ v > 0 && not (Map.null m)
| (HotValency v, _, m) <- naLocalRootPeers
]
--
-- DomainMapScript
--
-- 'DomainMapScript' describes evolution of domain name resolution.
--
type DomainMapScript = TimedScript (Map Domain [(IP, TTL)])
-- | Make sure that the final domain map can resolve all the domains correctly.
--
fixupDomainMapScript :: RelayAccessInfos -> DomainMapScript -> DomainMapScript
fixupDomainMapScript relays (Script (a@(_, delay) :| as)) =
case reverse as of
[] -> Script $ (dnsMap, delay) :| as
((_, delay') : as') -> Script $ a :| reverse ((dnsMap, delay') : as')
where
dnsMap :: Map Domain [(IP, TTL)]
dnsMap = Map.fromListWith (++)
[ (domain, [(ip, 300)])
| RelayDomainInfo domain ip _ _ <- getRelayAccessInfos relays
]
-- | Generate a `DomainMapScript`. Each step contains modification of the full
-- dns map with at most 20% entries removed and 20% entries modified. The last
-- scripted value is the full dns map which ensures that eventually all dns
-- names resolve to correct ip addresses.
--
genDomainMapScript :: RelayAccessInfos -> Gen DomainMapScript
genDomainMapScript relays = fixupDomainMapScript relays
<$> arbitraryScriptOf 10
((,) <$> genDomainMap <*> arbitrary)
where
genDomainMap :: Gen (Map Domain [(IP, TTL)])
genDomainMap = do
rm <- removedDomains
md <- modifiedDomains
return $ Map.fromList md `Map.union` foldr Map.delete dnsMap rm
removedDomains :: Gen [Domain]
removedDomains = do
as <- vectorOf (length domains) (frequency [(4, pure True), (1, pure False)])
return $ map fst . filter snd $ zip domains as
where
domains = Map.keys dnsMap
modifiedDomains :: Gen [(Domain, [(IP, TTL)])]
modifiedDomains = do
as <- vectorOf (length domains) (frequency [(4, pure True), (1, pure False)])
let ds :: [Domain]
ds = map fst . filter snd $ zip domains as
ips <- vectorOf (length ds) (case relays of
IPv4RelayAccessInfos _ -> PeerSelection.genIPv4
IPv6RelayAccessInfos _ -> PeerSelection.genIPv6)
return $ zip ds ((\a -> [(a,ttl)]) <$> ips)
where
domains = Map.keys dnsMap
dnsMap :: Map Domain [(IP, TTL)]
dnsMap = Map.fromListWith (++)
[ (domain, [(ip, ttl)])
| RelayDomainInfo domain ip _ _ <- getRelayAccessInfos relays
]
ttl = 300
shrinkDomainMapScript :: RelayAccessInfos -> DomainMapScript -> [DomainMapScript]
shrinkDomainMapScript relays script =
catMaybes $
-- make sure `fixupDomainMapScript` didn't return something that's
-- equal to the original `script`
(\script' -> if script == script' then Nothing else Just script')
. fixupDomainMapScript relays
<$> shrinkScriptWith (shrinkTuple shrinkMap_ shrink) script
where
shrinkMap_ :: Ord a => Map a b -> [Map a b]
shrinkMap_ = map Map.fromList . shrinkList (const []) . Map.toList
shrinkTuple :: (a -> [a]) -> (b -> [b]) -> (a, b) -> [(a, b)]
shrinkTuple f g (a, b) = [(a', b) | a' <- f a]
++ [(a, b') | b' <- g b]
--
-- DiffusionScript
--
-- | Multinode Diffusion Simulator Script
--
-- 'SimArgs' with all the values needed for running the simulation, followed
-- by a list of 'NodeArgs' where each element represents one running node and
-- respective 'Command's.
--
data DiffusionScript = DiffusionScript
SimArgs
DomainMapScript
[(NodeArgs, [Command])]
instance Show DiffusionScript where
show (DiffusionScript args dnsScript nodes) =
"DiffusionScript (" ++ show args ++ ") (" ++ show dnsScript ++ ") " ++ show nodes
-- | Information describing how nodes can be accessed.
--
data RelayAccessInfo
= RelayAddrInfo IP PortNumber PeerAdvertise
-- ^ relays available using ip / port pair
| RelayDomainInfo Domain IP PortNumber PeerAdvertise
-- ^ relays available either using the given domain.
deriving (Show, Eq)
genRelayAccessInfo :: Gen IP
-> Gen RelayAccessInfo
genRelayAccessInfo genIP =
oneof [ RelayAddrInfo <$> genIP
<*> (fromIntegral <$> (arbitrary :: Gen Int))
<*> arbitrary
, (\(DomainAccessPoint domain port) ip advertise -> RelayDomainInfo domain ip port advertise)
<$> arbitrary
<*> genIP
<*> arbitrary
]
makeRelayAccessPoint :: RelayAccessInfo -> RelayAccessPoint
makeRelayAccessPoint (RelayAddrInfo ip port _) = RelayAccessAddress ip port
makeRelayAccessPoint (RelayDomainInfo domain _ip port _) = RelayAccessDomain domain port
makeNtNAddr :: RelayAccessInfo -> NtNAddr
makeNtNAddr (RelayAddrInfo ip port _) = TestAddress (IPAddr ip port)
makeNtNAddr (RelayDomainInfo _dns ip port _) = TestAddress (IPAddr ip port)
data RelayAccessInfos
-- IPv4 only network
= IPv4RelayAccessInfos { getRelayAccessInfos :: [RelayAccessInfo] }
-- IPv6 only network
| IPv6RelayAccessInfos { getRelayAccessInfos :: [RelayAccessInfo] }
deriving Show
fixupRelayAccessInfos :: [RelayAccessInfo] -> [RelayAccessInfo]
fixupRelayAccessInfos as = f <$> as
where
-- map domains to the same port number
m = Map.fromList [ (domain, port)
| RelayDomainInfo domain _ port _ <- as
]
f a@RelayAddrInfo {} = a
f (RelayDomainInfo domain ip _ advertise) = RelayDomainInfo domain ip (m Map.! domain) advertise
-- Generate a list of either IPv4 only or IPv6 only `RelayAccessInfo`. All
-- `IP`'s using the same domain name are guaranteed to use the same port
-- number.
instance Arbitrary RelayAccessInfos where
arbitrary = oneof
[ do -- Limit the number of nodes to run in Simulation in order to limit
-- simulation execution (real) time.
size <- chooseInt (1,3)
IPv4RelayAccessInfos . fixupRelayAccessInfos
<$> vectorOf size (genRelayAccessInfo PeerSelection.genIPv4)
, do -- Limit the number of nodes to run in Simulation in order to limit
-- simulation execution (real) time.
size <- chooseInt (1,3)
IPv6RelayAccessInfos . fixupRelayAccessInfos
<$> vectorOf size (genRelayAccessInfo PeerSelection.genIPv6)
]
shrink (IPv4RelayAccessInfos as) = IPv4RelayAccessInfos . fixupRelayAccessInfos
<$> shrinkList (const []) as
shrink (IPv6RelayAccessInfos as) = IPv6RelayAccessInfos . fixupRelayAccessInfos
<$> shrinkList (const []) as
-- | Relays access info and dns script.
--
data RelayAccessInfosWithDNS = RelayAccessInfosWithDNS RelayAccessInfos DomainMapScript
deriving Show
instance Arbitrary RelayAccessInfosWithDNS where
arbitrary =
flip suchThat (\(RelayAccessInfosWithDNS infos _)
-> length (getRelayAccessInfos infos) >= 2) $ do
infos <- arbitrary
domainMapScript <- genDomainMapScript infos
return $ RelayAccessInfosWithDNS infos domainMapScript
shrink (RelayAccessInfosWithDNS infos dnsMapScript) =
[ RelayAccessInfosWithDNS infos (fixupDomainMapScript infos' dnsMapScript)
| infos' <- shrink infos
, length (getRelayAccessInfos infos') >= 2
]
++
[ RelayAccessInfosWithDNS infos dnsMapScript'
| dnsMapScript' <- shrinkDomainMapScript infos dnsMapScript
]
genDiffusionScript :: ([RelayAccessInfo]
-> RelayAccessInfo
-> Gen [( HotValency
, WarmValency
, Map RelayAccessPoint (PeerAdvertise, PeerTrustable))])
-> RelayAccessInfosWithDNS
-> Gen (SimArgs, DomainMapScript, [(NodeArgs, [Command])])
genDiffusionScript genLocalRootPeers
(RelayAccessInfosWithDNS relays dnsMapScript)
= do
let simArgs = mainnetSimArgs (length relays')
nodesWithCommands <- mapM go (nubBy ((==) `on` getRelayIP) relays')
return (simArgs, dnsMapScript, nodesWithCommands)
where
getRelayIP :: RelayAccessInfo -> IP
getRelayIP (RelayAddrInfo ip _ _) = ip
getRelayIP (RelayDomainInfo _ ip _ _) = ip
relays' :: [RelayAccessInfo]
relays' = getRelayAccessInfos relays
go :: RelayAccessInfo -> Gen (NodeArgs, [Command])
go relay = do
let otherRelays = relay `delete` relays'
minConnected = 3 `max` (length relays' - 1)
localRts <- genLocalRootPeers otherRelays relay
nodeArgs <- genNodeArgs relays' minConnected localRts relay
commands <- genCommands localRts
return (nodeArgs, commands)
-- | Multinode Diffusion Simulator Script
--
-- Tries to generate a reasonable looking network with at most 3 nodes that can
-- or can not be connected to one another. These nodes can also randomly die or
-- have their local configuration changed.
--
genNonHotDiffusionScript :: RelayAccessInfosWithDNS
-> Gen (SimArgs, DomainMapScript, [(NodeArgs, [Command])])
genNonHotDiffusionScript = genDiffusionScript genLocalRootPeers
where
-- | Generate Local Root Peers
--
genLocalRootPeers :: [RelayAccessInfo]
-> RelayAccessInfo
-> Gen [( HotValency
, WarmValency
, Map RelayAccessPoint (PeerAdvertise, PeerTrustable)
)]
genLocalRootPeers relays _relay = flip suchThat hasUpstream $ do
nrGroups <- chooseInt (1, 3)
-- Remove self from local root peers
let size = length relays
sizePerGroup = (size `div` nrGroups) + 1
peerAdvertise <- vectorOf size arbitrary
let relaysAdv = zip (makeRelayAccessPoint <$> relays) peerAdvertise
relayGroups = divvy sizePerGroup relaysAdv
relayGroupsMap = Map.fromList <$> relayGroups
target <- forM relayGroups
(\x -> if null x
then pure (0, 0)
else genTargets (length x))
let lrpGroups = zipWith (\(h, w) g -> (h, w, g))
target
relayGroupsMap
return lrpGroups
genTargets :: Int -> Gen (HotValency, WarmValency)
genTargets l = do
warmValency <- WarmValency <$> chooseEnum (1, l)
hotValency <- HotValency <$> chooseEnum (1, getWarmValency warmValency)
return (hotValency, warmValency)
hasUpstream :: [( HotValency
, WarmValency
, Map RelayAccessPoint (PeerAdvertise, PeerTrustable)
)]
-> Bool
hasUpstream localRootPeers =
any id [ v > 0 && not (Map.null m)
| (HotValency v, _, m) <- localRootPeers
]
-- | Multinode Hot Diffusion Simulator Script
--
-- Tries to generate a network with at most 2 nodes that should
-- be connected to one another. This generator tries to obtain high ratios of
-- active peers so we can test the miniprotocols that run when we have such
-- active connections. These nodes can not randomly die or have their local
-- configuration changed. Their local root peers consist of a single group.
--
genHotDiffusionScript :: RelayAccessInfosWithDNS
-> Gen (SimArgs, DomainMapScript, [(NodeArgs, [Command])])
genHotDiffusionScript = genDiffusionScript genLocalRootPeers
where
-- | Generate Local Root Peers. This only generates 1 group
--
genLocalRootPeers :: [RelayAccessInfo]
-> RelayAccessInfo
-> Gen [( HotValency
, WarmValency
, Map RelayAccessPoint (PeerAdvertise, PeerTrustable)
)]
genLocalRootPeers relays _relay = flip suchThat hasUpstream $ do
let size = length relays
peerAdvertise <- vectorOf size arbitrary
let relaysAdv = zip (makeRelayAccessPoint <$> relays) peerAdvertise
relayGroupsMap = Map.fromList relaysAdv
warmTarget = length relaysAdv
hotTarget <- choose (0 , warmTarget)
return [( HotValency hotTarget
, WarmValency warmTarget
, relayGroupsMap
)]
hasUpstream :: [( HotValency
, WarmValency
, Map RelayAccessPoint (PeerAdvertise, PeerTrustable)
)]
-> Bool
hasUpstream localRootPeers =
any id [ v > 0 && not (Map.null m)
| (HotValency v, _, m) <- localRootPeers
]
instance Arbitrary DiffusionScript where
arbitrary = (\(a,b,c) -> DiffusionScript a b c)
<$> frequency [ (1, arbitrary >>= genNonHotDiffusionScript)
, (1, arbitrary >>= genHotDiffusionScript)
]
-- TODO: shrink dns map
-- TODO: we should write more careful shrinking than recursively shrinking
-- `DiffusionScript`!
shrink (DiffusionScript _ _ []) = []
shrink (DiffusionScript sargs dnsMap ((nargs, cmds):s)) = do
shrinkedCmds <- fixupCommands <$> shrinkList shrinkCommand cmds
DiffusionScript sa dnsMap' ss <- shrink (DiffusionScript sargs dnsMap s)
return (DiffusionScript sa dnsMap' ((nargs, shrinkedCmds) : ss))
where
shrinkDelay = map fromRational . shrink . toRational
shrinkCommand :: Command -> [Command]
shrinkCommand (JoinNetwork d) = JoinNetwork <$> shrinkDelay d
shrinkCommand (Kill d) = Kill <$> shrinkDelay d
shrinkCommand (Reconfigure d lrp) = Reconfigure <$> shrinkDelay d
<*> pure lrp
-- | Multinode Hot Diffusion Simulator Script
--
-- List of 'SimArgs'. Each element of the list represents one running node.
--
data HotDiffusionScript = HotDiffusionScript
SimArgs
DomainMapScript
[(NodeArgs, [Command])]
deriving Show
instance Arbitrary HotDiffusionScript where
arbitrary = (\(a,b,c) -> HotDiffusionScript a b c) <$> (arbitrary >>= genHotDiffusionScript)
shrink (HotDiffusionScript sargs dnsMap hds) =
[ HotDiffusionScript sa dnsMap' ds
| DiffusionScript sa dnsMap' ds <- shrink (DiffusionScript sargs dnsMap hds) ]
-- Tests if the fixupCommand is idempotent.
-- Note that the generator for DiffusionScript already fixups the Command list.
--
prop_diffusionScript_fixupCommands :: DiffusionScript -> Property
prop_diffusionScript_fixupCommands (DiffusionScript _ _ []) = property True
prop_diffusionScript_fixupCommands (DiffusionScript sa dnsMap ((_, cmds): t)) =
counterexample ("Failed with cmds: " ++ show cmds ++ "\n"
++ "fixupCommands cmds = " ++ show (fixupCommands cmds)
) $
fixupCommands cmds == cmds
.&&. prop_diffusionScript_fixupCommands (DiffusionScript sa dnsMap t)
-- Tests if the fixupCommand outputs valid command scripts.
--
-- Note that the generator for DiffusionScript already fixups the Command list.
--
prop_diffusionScript_commandScript_valid :: DiffusionScript -> Property
prop_diffusionScript_commandScript_valid (DiffusionScript _ _ []) = property True
prop_diffusionScript_commandScript_valid (DiffusionScript sa dnsMap ((_, cmds): t)) =
counterexample ("Failed with cmds: " ++ show cmds) $
isValid cmds
.&&. prop_diffusionScript_commandScript_valid (DiffusionScript sa dnsMap t)
where
isValid :: [Command] -> Property
isValid [] = property True
isValid [_] = property True
isValid (x:y:xs) =
case (x, y) of
(JoinNetwork _, JoinNetwork _) ->
counterexample ("Invalid sequence: " ++ show x ++ " " ++ show y) $
property False
(Kill _, Kill _) ->
counterexample ("Invalid sequence: " ++ show x ++ " " ++ show y) $
property False
(Kill _, Reconfigure _ _) ->
counterexample ("Invalid sequence: " ++ show x ++ " " ++ show y) $
property False
(Reconfigure _ _, JoinNetwork _) ->
counterexample ("Invalid sequence: " ++ show x ++ " " ++ show y) $
property False
_ -> isValid (y:xs)
-- | Diffusion Simulation Trace so we know what command is concurrently
-- running
--
data DiffusionSimulationTrace
= TrJoiningNetwork
| TrKillingNode
| TrReconfiguringNode
| TrUpdatingDNS
| TrRunning
deriving (Show)
-- Warning: be careful with writing properties that rely
-- on trace events from multiple components environment.
-- These events typically occur in separate threads and
-- so are not casually ordered. It is ok to use them for
-- timeout/eventually properties, but not for properties
-- that check conditions synchronously.
--
data DiffusionTestTrace =
DiffusionLocalRootPeerTrace (TraceLocalRootPeers NtNAddr SomeException)
| DiffusionPublicRootPeerTrace TracePublicRootPeers
| DiffusionLedgerPeersTrace TraceLedgerPeers
| DiffusionPeerSelectionTrace (TracePeerSelection NtNAddr)
| DiffusionPeerSelectionActionsTrace (PeerSelectionActionsTrace NtNAddr NtNVersion)
| DiffusionDebugPeerSelectionTrace (DebugPeerSelection NtNAddr)
| DiffusionConnectionManagerTrace
(ConnectionManagerTrace NtNAddr
(ConnectionHandlerTrace NtNVersion NtNVersionData))
| DiffusionDiffusionSimulationTrace DiffusionSimulationTrace
| DiffusionConnectionManagerTransitionTrace
(AbstractTransitionTrace NtNAddr)
| DiffusionInboundGovernorTransitionTrace
(RemoteTransitionTrace NtNAddr)
| DiffusionInboundGovernorTrace (InboundGovernorTrace NtNAddr)
| DiffusionServerTrace (ServerTrace NtNAddr)
| DiffusionFetchTrace (TraceFetchClientState BlockHeader)
| DiffusionDebugTrace String
deriving (Show)
-- | A debug tracer which embeds events in DiffusionTestTrace.
--
iosimTracer :: forall s a.
( Show a
, Typeable a
)
=> Tracer (IOSim s) (WithTime (WithName NtNAddr a))
iosimTracer = Tracer traceM <> sayTracer
-- | Run an arbitrary topology
diffusionSimulation
:: forall m. ( Alternative (STM m)
, MonadAsync m
, MonadDelay m
, MonadFix m
, MonadFork m
, MonadSay m
, MonadST m
, MonadEvaluate m
, MonadLabelledSTM m
, MonadTraceSTM m
, MonadCatch m
, MonadMask m
, MonadTime m
, MonadTimer m
, MonadThrow (STM m)
, MonadMVar m
, Eq (Async m Void)
, forall a. Semigroup a => Semigroup (m a)
)
=> BearerInfo
-> DiffusionScript
-> Tracer m (WithTime (WithName NtNAddr DiffusionTestTrace))
-- ^ timed trace of nodes in the system
-> m Void
diffusionSimulation
defaultBearerInfo
(DiffusionScript simArgs dnsMapScript nodeArgs)
nodeTracer =
withSnocket netSimTracer defaultBearerInfo Map.empty
$ \ntnSnocket _ ->
withSnocket nullTracer defaultBearerInfo Map.empty
$ \ntcSnocket _ -> do
dnsMapVar <- fromLazyTVar <$> playTimedScript nullTracer dnsMapScript
withAsyncAll
(map (uncurry (runCommand Nothing ntnSnocket ntcSnocket dnsMapVar simArgs))
nodeArgs)
$ \nodes -> do
(_, x) <- waitAny nodes
return x
where
netSimTracer :: Tracer m (WithAddr NtNAddr (SnocketTrace m NtNAddr))
netSimTracer = (\(WithAddr l _ a) -> WithName (fromMaybe (TestAddress $ IPAddr (read "0.0.0.0") 0) l) (show a))
`contramap` tracerWithTime nullTracer
-- | Runs a single node according to a list of commands.
runCommand
:: Maybe ( Async m Void
, StrictTVar m [( HotValency
, WarmValency
, Map RelayAccessPoint (PeerAdvertise, PeerTrustable)
)])
-- ^ If the node is running and corresponding local root configuration
-- TVar.
-> Snocket m (FD m NtNAddr) NtNAddr
-- ^ Node to node Snocket
-> Snocket m (FD m NtCAddr) NtCAddr
-- ^ Node to client Snocket
-> StrictTVar m (Map Domain [(IP, TTL)])
-- ^ Map of domain map TVars to be updated in case a node changes its IP
-> SimArgs -- ^ Simulation arguments needed in order to run a simulation
-> NodeArgs -- ^ Simulation arguments needed in order to run a single node
-> [Command] -- ^ List of commands/actions to perform for a single node
-> m Void
runCommand Nothing ntnSnocket ntcSnocket dnsMapVar sArgs nArgs [] = do
threadDelay 3600
traceWith (diffSimTracer (naAddr nArgs)) TrRunning
runCommand Nothing ntnSnocket ntcSnocket dnsMapVar sArgs nArgs []