-
Notifications
You must be signed in to change notification settings - Fork 86
/
Types.hs
1404 lines (1204 loc) · 59.1 KB
/
Types.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 BangPatterns #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE ViewPatterns #-}
module Ouroboros.Network.PeerSelection.Governor.Types
( -- * P2P governor policies
PeerSelectionPolicy (..)
, PeerSelectionTargets (..)
, nullPeerSelectionTargets
, sanePeerSelectionTargets
, PickPolicy
, pickPeers
-- * P2P governor low level API
-- These records are needed to run the peer selection.
, PeerStateActions (..)
, PeerSelectionActions (..)
, ChurnMode (..)
-- * P2P governor internals
, PeerSelectionState (..)
, emptyPeerSelectionState
, DebugPeerSelectionState (..)
, makeDebugPeerSelectionState
, assertPeerSelectionState
, establishedPeersStatus
, PublicPeerSelectionState (..)
, makePublicPeerSelectionStateVar
, toPublicState
, Guarded (GuardedSkip, Guarded)
, Decision (..)
, TimedDecision
, MkGuardedDecision
, Completion (..)
, PeerSelectionCounters (.., PeerSelectionCountersHWC, numberOfColdPeers, numberOfWarmPeers, numberOfHotPeers, numberOfColdBigLedgerPeers, numberOfWarmBigLedgerPeers, numberOfHotBigLedgerPeers, numberOfColdLocalRootPeers, numberOfWarmLocalRootPeers, numberOfHotLocalRootPeers)
, emptyPeerSelectionCounters
, peerSelectionStateToCounters
-- * Peer Sharing Auxiliary data type
, PeerSharingResult (..)
-- * Traces
, TracePeerSelection (..)
, ChurnAction (..)
, DebugPeerSelection (..)
-- * Error types
, BootstrapPeersCriticalTimeoutError (..)
) where
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Maybe (fromMaybe)
import Data.Monoid.Synchronisation (FirstToFinish (..))
import Data.OrdPSQ qualified as PSQ
import Data.Semigroup (Min (..))
import Data.Set (Set)
import Data.Set qualified as Set
import Control.Applicative (Alternative)
import Control.Concurrent.JobPool (Job)
import Control.Exception (Exception (..), SomeException, assert)
import Control.Monad.Class.MonadSTM
import Control.Monad.Class.MonadTime.SI
import System.Random (StdGen)
import Control.Concurrent.Class.MonadSTM.Strict
import Ouroboros.Network.ExitPolicy
import Ouroboros.Network.PeerSelection.Bootstrap (UseBootstrapPeers (..))
import Ouroboros.Network.PeerSelection.LedgerPeers (IsBigLedgerPeer,
LedgerPeersKind)
import Ouroboros.Network.PeerSelection.LedgerPeers.Type
(LedgerStateJudgement (..))
import Ouroboros.Network.PeerSelection.PeerAdvertise (PeerAdvertise)
import Ouroboros.Network.PeerSelection.PeerSharing (PeerSharing)
import Ouroboros.Network.PeerSelection.PeerTrustable (PeerTrustable)
import Ouroboros.Network.PeerSelection.PublicRootPeers (PublicRootPeers)
import Ouroboros.Network.PeerSelection.PublicRootPeers qualified as PublicRootPeers
import Ouroboros.Network.PeerSelection.State.EstablishedPeers (EstablishedPeers)
import Ouroboros.Network.PeerSelection.State.EstablishedPeers qualified as EstablishedPeers
import Ouroboros.Network.PeerSelection.State.KnownPeers (KnownPeers)
import Ouroboros.Network.PeerSelection.State.KnownPeers qualified as KnownPeers
import Ouroboros.Network.PeerSelection.State.LocalRootPeers (HotValency (..),
LocalRootPeers, WarmValency (..))
import Ouroboros.Network.PeerSelection.State.LocalRootPeers qualified as LocalRootPeers
import Ouroboros.Network.PeerSelection.Types (PeerSource (..),
PeerStatus (PeerHot, PeerWarm))
import Ouroboros.Network.Protocol.PeerSharing.Type (PeerSharingAmount,
PeerSharingResult (..))
-- | A peer pick policy is an action that picks a subset of elements from a
-- map of peers.
--
-- The pre-condition is that the map of available choices will be non-empty,
-- and the requested number to pick will be strictly positive.
--
-- The post-condition is that the picked set is non-empty but must not be
-- bigger than the requested number.
--
-- Peer selection API is using `STM m` monad, internally it is using `m`.
--
type PickPolicy peeraddr m =
-- Extra peer attributes available to use in the picking policy.
-- As more attributes are needed, extend this with more such functions.
(peeraddr -> PeerSource) -- Where the peer is known from
-> (peeraddr -> Int) -- Connection failure count
-> (peeraddr -> Bool) -- Found to be tepid flag
-> Set peeraddr -- The set to pick from
-> Int -- Max number to choose, fewer is ok.
-> m (Set peeraddr) -- The set picked.
data PeerSelectionPolicy peeraddr m = PeerSelectionPolicy {
policyPickKnownPeersForPeerShare :: PickPolicy peeraddr (STM m),
policyPickColdPeersToPromote :: PickPolicy peeraddr (STM m),
policyPickWarmPeersToPromote :: PickPolicy peeraddr (STM m),
policyPickHotPeersToDemote :: PickPolicy peeraddr (STM m),
policyPickWarmPeersToDemote :: PickPolicy peeraddr (STM m),
policyPickColdPeersToForget :: PickPolicy peeraddr (STM m),
policyFindPublicRootTimeout :: !DiffTime,
policyMaxInProgressPeerShareReqs :: !Int,
-- ^ Maximum number of peer sharing requests that can be in progress
policyPeerShareRetryTime :: !DiffTime,
-- ^ Amount of time a node has to wait before issuing a new peer sharing
-- request
policyPeerShareBatchWaitTime :: !DiffTime,
-- ^ Amount of time a batch of peer sharing requests is allowed to take
policyPeerShareOverallTimeout :: !DiffTime,
-- ^ Amount of time the overall batches of peer sharing requests are
-- allowed to take
policyPeerShareActivationDelay :: !DiffTime,
-- ^ Delay until we consider a peer suitable for peer sharing
-- | Re-promote delay, passed from `ExitPolicy`.
--
policyErrorDelay :: !DiffTime
}
-- | Adjustable targets for the peer selection mechanism.
--
-- These are used by the peer selection governor as targets. They are used by
-- the peer churn governor loop as knobs to adjust, to influence the peer
-- selection governor.
--
-- The /known/, /established/ and /active/ peer targets are targets both from
-- below and from above: the governor will attempt to grow or shrink the sets
-- to hit these targets.
--
-- Unlike the other targets, the /root/ peer target is \"one sided\", it is
-- only a target from below. The governor does not try to shrink the root set
-- to hit it, it simply stops looking for more.
--
-- There is also an implicit target that enough local root peers are selected
-- as active. This comes from the configuration for local roots, and is not an
-- independently adjustable target.
--
data PeerSelectionTargets = PeerSelectionTargets {
targetNumberOfRootPeers :: !Int,
-- | The target number of all known peers. This includes ledger,
-- big ledger peers.
targetNumberOfKnownPeers :: !Int,
-- | The target number of established peers (does not include big ledger
-- peers).
--
-- The target includes root peers, local root peers, ledger peers and big
-- ledger peers.
--
targetNumberOfEstablishedPeers :: !Int,
-- | The target number of active peers (does not include big ledger
-- peers).
--
-- The
targetNumberOfActivePeers :: !Int,
-- | Target number of known big ledger peers.
--
-- This target is independent of `targetNumberOfKnownPeers`. The total
-- number of known peers will be sum of the two targets.
--
targetNumberOfKnownBigLedgerPeers :: !Int,
-- | Target number of established big ledger peers.
--
-- This target is independent of `targetNumberOfEstablishedPeers`. The
-- total number of established peers will be sum of the two targets and
-- local root peers.
--
targetNumberOfEstablishedBigLedgerPeers :: !Int,
-- | Target number of active big ledger peers.
--
-- This target is independent of `targetNumberOfActivePeers`. The total
-- number of active peers will be sum of the two targets and active local
-- root peers.
--
targetNumberOfActiveBigLedgerPeers :: !Int
-- Expressed as intervals rather than frequencies
-- targetChurnIntervalKnownPeers :: !DiffTime,
-- targetChurnIntervalEstablishedPeers :: !DiffTime,
-- targetChurnIntervalActivePeers :: !DiffTime
}
deriving (Eq, Show)
nullPeerSelectionTargets :: PeerSelectionTargets
nullPeerSelectionTargets =
PeerSelectionTargets {
targetNumberOfRootPeers = 0,
targetNumberOfKnownPeers = 0,
targetNumberOfEstablishedPeers = 0,
targetNumberOfActivePeers = 0,
targetNumberOfKnownBigLedgerPeers = 0,
targetNumberOfEstablishedBigLedgerPeers = 0,
targetNumberOfActiveBigLedgerPeers = 0
-- targetChurnIntervalKnownPeers = 0,
-- targetChurnIntervalEstablishedPeers = 0,
-- targetChurnIntervalActivePeers = 0
}
sanePeerSelectionTargets :: PeerSelectionTargets -> Bool
sanePeerSelectionTargets PeerSelectionTargets{..} =
0 <= targetNumberOfActivePeers
&& targetNumberOfActivePeers <= targetNumberOfEstablishedPeers
&& targetNumberOfEstablishedPeers <= targetNumberOfKnownPeers
&& targetNumberOfRootPeers <= targetNumberOfKnownPeers
&& 0 <= targetNumberOfRootPeers
&& 0 <= targetNumberOfActiveBigLedgerPeers
&& targetNumberOfActiveBigLedgerPeers <= targetNumberOfEstablishedBigLedgerPeers
&& targetNumberOfEstablishedBigLedgerPeers <= targetNumberOfKnownBigLedgerPeers
&& targetNumberOfActivePeers <= 100
&& targetNumberOfEstablishedPeers <= 1000
&& targetNumberOfKnownPeers <= 10000
&& targetNumberOfActiveBigLedgerPeers <= 100
&& targetNumberOfEstablishedBigLedgerPeers <= 1000
&& targetNumberOfKnownBigLedgerPeers <= 10000
-- | Actions performed by the peer selection governor.
--
-- These being pluggable allows:
--
-- * choice of known peer root sets
-- * running both in simulation and for real
--
data PeerSelectionActions peeraddr peerconn m = PeerSelectionActions {
readPeerSelectionTargets :: STM m PeerSelectionTargets,
-- | Read the current set of locally or privately known root peers.
--
-- In general this is expected to be updated asynchronously by some
-- other thread. It is intended to cover the use case of peers from
-- local configuration. It could be dynamic due to DNS resolution, or
-- due to dynamic configuration updates.
--
-- It is structured as a collection of (non-overlapping) groups of peers
-- where we are supposed to select n from each group.
--
readLocalRootPeers :: STM m [( HotValency
, WarmValency
, Map peeraddr ( PeerAdvertise
, PeerTrustable))],
readNewInboundConnection :: STM m (peeraddr, PeerSharing),
-- | Read the current Peer Sharing willingness value
--
-- This value comes from the Node's configuration file.
--
peerSharing :: PeerSharing,
-- | Get the remote's side PeerSharing value from 'peerconn'
--
-- 'peerconn' ideally comes from a call to 'establishPeerConnection'.
-- This will establish a connection and perform handshake. The returned
-- 'peerconn' has all the versionData negotiated in the handshake,
-- including the remote peer's 'PeerSharing' willingness information.
--
peerConnToPeerSharing :: peerconn -> PeerSharing,
-- | Request a sample of public root peers.
--
-- It is intended to cover use cases including:
--
-- * federated relays from a DNS pool
-- * Official bootstrap peers from a trusted source
-- * stake pool relays published in the blockchain
-- * a pre-distributed snapshot of stake pool relays from the blockchain
--
-- It also makes a distinction between normal and big ledger peers to be
-- fetched.
--
requestPublicRootPeers :: LedgerPeersKind -> Int -> m (PublicRootPeers peeraddr, DiffTime),
-- | The action to contact a known peer and request a sample of its
-- known peers.
--
requestPeerShare :: PeerSharingAmount -> peeraddr -> m (PeerSharingResult peeraddr),
-- | Core actions run by the governor to change 'PeerStatus'.
--
peerStateActions :: PeerStateActions peeraddr peerconn m,
-- | Read the current bootstrap peers flag
readUseBootstrapPeers :: STM m UseBootstrapPeers,
-- | Read the current ledger state judgement
--
readLedgerStateJudgement :: STM m LedgerStateJudgement
}
-- | Callbacks which are performed to change peer state.
--
data PeerStateActions peeraddr peerconn m = PeerStateActions {
-- | Monitor peer state. Must be non-blocking.
--
monitorPeerConnection :: peerconn -> STM m (PeerStatus, Maybe RepromoteDelay),
-- | Establish new connection: cold to warm.
--
-- 'IsBigLedgerPeer' is passed from the outbound governor to the
-- mini-protocol callbacks.
--
establishPeerConnection :: IsBigLedgerPeer
-> peeraddr -> m peerconn,
-- | Activate a connection: warm to hot promotion.
--
-- 'IsBigLedgerPeer' is passed from the outbound governor to the
-- mini-protocol callbacks.
--
activatePeerConnection :: IsBigLedgerPeer
-> peerconn -> m (),
-- | Deactive a peer: hot to warm demotion.
--
deactivatePeerConnection :: peerconn -> m (),
-- | Close a connection: warm to cold transition.
--
closePeerConnection :: peerconn -> m ()
}
-----------------------
-- Peer Selection State
--
-- | The internal state used by the 'peerSelectionGovernor'.
--
-- The local and public root sets are disjoint, and their union is the
-- overall root set.
--
-- Documentation of individual fields describes some of the invariants these
-- structures should maintain. For the entire picture, see
-- 'assertPeerSelectionState'.
--
data PeerSelectionState peeraddr peerconn = PeerSelectionState {
targets :: !PeerSelectionTargets,
-- | The current set of local root peers. This is structured as a
-- bunch of groups, with a target for each group. This gives us a set of
-- n-of-m choices, e.g. \"pick 2 from this group and 1 from this group\".
--
-- The targets must of course be achievable, and to keep things simple,
-- the groups must be disjoint.
--
localRootPeers :: !(LocalRootPeers peeraddr),
-- | This set holds the public root peers (i.e. Ledger (small and big),
-- Bootstrap peers and locally configured public root peers).
--
publicRootPeers :: !(PublicRootPeers peeraddr),
-- | Known peers.
--
knownPeers :: !(KnownPeers peeraddr),
-- | Established peers.
--
establishedPeers :: !(EstablishedPeers peeraddr peerconn),
-- | Active peers.
--
activePeers :: !(Set peeraddr),
-- | A counter to manage the exponential backoff strategy for when to
-- retry querying for more public root peers. It is negative for retry
-- counts after failure, and positive for retry counts that are
-- successful but make no progress.
--
publicRootBackoffs :: !Int,
-- | The earliest time we would be prepared to request more public root
-- peers. This is used with the 'publicRootBackoffs' to manage the
-- exponential backoff.
--
publicRootRetryTime :: !Time,
-- | Whether a request for more public root peers is in progress.
--
inProgressPublicRootsReq :: !Bool,
-- | A counter to manage the exponential backoff strategy for when to
-- retry querying for more public root peers. It is negative for retry
-- counts after failure, and positive for retry counts that are
-- successful but make no progress.
--
bigLedgerPeerBackoffs :: !Int,
-- | The earliest time we would be prepared to request more big ledger
-- peers. This is used with the 'bigLedgerPeerBackoffs' to manage the
-- exponential backoff.
--
bigLedgerPeerRetryTime :: !Time,
-- | Whether a request for more big ledger peers is in progress.
--
inProgressBigLedgerPeersReq :: !Bool,
inProgressPeerShareReqs :: !Int,
inProgressPromoteCold :: !(Set peeraddr),
inProgressPromoteWarm :: !(Set peeraddr),
inProgressDemoteWarm :: !(Set peeraddr),
inProgressDemoteHot :: !(Set peeraddr),
-- | Peers that had an async demotion and their connections are still
-- being closed
inProgressDemoteToCold :: !(Set peeraddr),
-- | Rng for fuzzy delay
fuzzRng :: !StdGen,
-- | Current ledger state judgement
--
ledgerStateJudgement :: !LedgerStateJudgement,
-- | Current value of 'UseBootstrapPeers'.
--
bootstrapPeersFlag :: !UseBootstrapPeers,
-- | Has the governor fully reset its state
--
hasOnlyBootstrapPeers :: !Bool,
-- | Has the governor fully reset its state
--
bootstrapPeersTimeout :: !(Maybe Time)
-- TODO: need something like this to distinguish between lots of bad peers
-- and us getting disconnected from the network locally. We don't want a
-- network disconnect to cause us to flush our full known peer set by
-- considering them all to have bad connectivity.
-- Should also take account of DNS failures for root peer set.
-- lastSuccessfulNetworkEvent :: Time
}
deriving Show
-----------------------
-- Debug copy of Peer Selection State
--
-- Used for dumping the peer selection state upon getting a USR1 signal.
--
data DebugPeerSelectionState peeraddr = DebugPeerSelectionState {
dpssTargets :: !PeerSelectionTargets,
dpssLocalRootPeers :: !(LocalRootPeers peeraddr),
dpssPublicRootPeers :: !(PublicRootPeers peeraddr),
dpssKnownPeers :: !(KnownPeers peeraddr),
dpssEstablishedPeers :: !(Set peeraddr),
dpssActivePeers :: !(Set peeraddr),
dpssPublicRootBackoffs :: !Int,
dpssPublicRootRetryTime :: !Time,
dpssInProgressPublicRootsReq :: !Bool,
dpssBigLedgerPeerBackoffs :: !Int,
dpssBigLedgerPeerRetryTime :: !Time,
dpssInProgressBigLedgerPeersReq :: !Bool,
dpssInProgressPeerShareReqs :: !Int,
dpssInProgressPromoteCold :: !(Set peeraddr),
dpssInProgressPromoteWarm :: !(Set peeraddr),
dpssInProgressDemoteWarm :: !(Set peeraddr),
dpssInProgressDemoteHot :: !(Set peeraddr),
dpssInProgressDemoteToCold :: !(Set peeraddr),
dpssUpstreamyness :: !(Map peeraddr Int),
dpssFetchynessBlocks :: !(Map peeraddr Int)
} deriving Show
makeDebugPeerSelectionState :: PeerSelectionState peeraddr peerconn
-> Map peeraddr Int
-> Map peeraddr Int
-> DebugPeerSelectionState peeraddr
makeDebugPeerSelectionState PeerSelectionState {..} up bp =
DebugPeerSelectionState {
dpssTargets = targets
, dpssLocalRootPeers = localRootPeers
, dpssPublicRootPeers = publicRootPeers
, dpssKnownPeers = knownPeers
, dpssEstablishedPeers = EstablishedPeers.toSet establishedPeers
, dpssActivePeers = activePeers
, dpssPublicRootBackoffs = publicRootBackoffs
, dpssPublicRootRetryTime = publicRootRetryTime
, dpssInProgressPublicRootsReq = inProgressPublicRootsReq
, dpssBigLedgerPeerBackoffs = bigLedgerPeerBackoffs
, dpssBigLedgerPeerRetryTime = bigLedgerPeerRetryTime
, dpssInProgressBigLedgerPeersReq = inProgressBigLedgerPeersReq
, dpssInProgressPeerShareReqs = inProgressPeerShareReqs
, dpssInProgressPromoteCold = inProgressPromoteCold
, dpssInProgressPromoteWarm = inProgressPromoteWarm
, dpssInProgressDemoteWarm = inProgressDemoteWarm
, dpssInProgressDemoteHot = inProgressDemoteHot
, dpssInProgressDemoteToCold = inProgressDemoteToCold
, dpssUpstreamyness = up
, dpssFetchynessBlocks = bp
}
-- | Public 'PeerSelectionState' that can be accessed by Peer Sharing
-- mechanisms without any problem.
--
-- This data type should not expose too much information and keep only
-- essential data needed for computing the peer sharing request result
--
newtype PublicPeerSelectionState peeraddr =
PublicPeerSelectionState {
availableToShare :: Set peeraddr
}
emptyPublicPeerSelectionState :: Ord peeraddr
=> PublicPeerSelectionState peeraddr
emptyPublicPeerSelectionState =
PublicPeerSelectionState {
availableToShare = mempty
}
makePublicPeerSelectionStateVar
:: (MonadSTM m, Ord peeraddr)
=> m (StrictTVar m (PublicPeerSelectionState peeraddr))
makePublicPeerSelectionStateVar = newTVarIO emptyPublicPeerSelectionState
-- | Convert a 'PeerSelectionState' into a public record accessible by the
-- Peer Sharing mechanisms so we can know about which peers are available and
-- possibly other needed context.
--
toPublicState :: PeerSelectionState peeraddr peerconn
-> PublicPeerSelectionState peeraddr
toPublicState PeerSelectionState { knownPeers
} =
PublicPeerSelectionState {
availableToShare =
KnownPeers.getPeerSharingResponsePeers knownPeers
}
-- Peer selection counters.
--
data PeerSelectionCounters = PeerSelectionCounters {
numberOfRootPeers :: Int,
--
-- Non Big Ledger Peers
--
numberOfKnownPeers :: Int,
-- ^ number of known peers excluding big ledger peers
numberOfColdPeersPromotions :: Int,
-- ^ number of known peers (excluding big ledger peers) being promoted to
-- warm
numberOfEstablishedPeers :: Int,
-- ^ number of established peers excluding big ledger peers
numberOfWarmPeersDemotions :: Int,
-- ^ number of warm peers (excluding big ledger peers) being demoted to
-- cold
numberOfWarmPeersPromotions :: Int,
-- ^ number of warm peers (excluding big ledger peers) being promote to
-- hot
numberOfActivePeers :: Int,
-- ^ number of active peers excluding big ledger peers
numberOfActivePeersDemotions :: Int,
-- ^ number of active peers (excluding big ledger peers) being demoted to
-- warm
--
-- Big Ledger Peers
--
numberOfKnownBigLedgerPeers :: Int,
-- ^ number of known big ledger peers
numberOfColdBigLedgerPeersPromotions :: Int,
-- ^ number of cold big ledger peers being promoted to warm
numberOfEstablishedBigLedgerPeers :: Int,
-- ^ number of established big ledger peers
numberOfWarmBigLedgerPeersDemotions :: Int,
-- ^ number of warm big ledger peers being demoted to cold
numberOfWarmBigLedgerPeersPromotions :: Int,
-- ^ number of warm big ledger peers being promote to hot
numberOfActiveBigLedgerPeers :: Int,
-- ^ number of active big ledger peers
numberOfActiveBigLedgerPeersDemotions :: Int,
-- ^ number of active big ledger peers being demoted to warm
--
-- Local Roots
--
numberOfKnownLocalRootPeers :: Int,
-- ^ number of known local root peers should always be equal to the sum
-- of established & active local roots.
numberOfEstablishedLocalRootPeers :: Int,
numberOfWarmLocalRootPeersPromotions :: Int,
numberOfActiveLocalRootPeers :: Int,
numberOfActiveLocalRootPeersDemotions :: Int,
--
-- Share Peers
-- (peers received through peer sharing)
--
numberOfKnownSharedPeers :: Int,
numberOfColdSharedPeersPromotions :: Int,
numberOfEstablishedSharedPeers :: Int,
numberOfWarmSharedPeersDemotions :: Int,
numberOfWarmSharedPeersPromotions :: Int,
numberOfActiveSharedPeers :: Int,
numberOfActiveSharedPeersDemotions :: Int,
--
-- Bootstrap Peers
--
numberOfKnownBootstrapPeers :: Int,
numberOfColdBootstrapPeersPromotions :: Int,
numberOfEstablishedBootstrapPeers :: Int,
numberOfWarmBootstrapPeersDemotions :: Int,
numberOfWarmBootstrapPeersPromotions :: Int,
numberOfActiveBootstrapPeers :: Int,
numberOfActiveBootstrapPeersDemotions :: Int
} deriving (Eq, Show)
-- | A Pattern synonym which computes `hot`, `warm`, `cold` counters from
-- `PeerSelectionCounters`.
--
pattern PeerSelectionCountersHWC :: Int -> Int -> Int -- peers
-> Int -> Int -> Int -- big ledger peers
-> Int -> Int -> Int -- local roots
-> PeerSelectionCounters
pattern PeerSelectionCountersHWC { numberOfColdPeers,
numberOfWarmPeers,
numberOfHotPeers,
numberOfColdBigLedgerPeers,
numberOfWarmBigLedgerPeers,
numberOfHotBigLedgerPeers,
numberOfColdLocalRootPeers,
numberOfWarmLocalRootPeers,
numberOfHotLocalRootPeers }
<- (peerSelectionCountersHWC ->
PeerSelectionCounters { numberOfKnownPeers = numberOfColdPeers,
numberOfEstablishedPeers = numberOfWarmPeers,
numberOfActivePeers = numberOfHotPeers,
numberOfKnownBigLedgerPeers = numberOfColdBigLedgerPeers,
numberOfEstablishedBigLedgerPeers = numberOfWarmBigLedgerPeers,
numberOfActiveBigLedgerPeers = numberOfHotBigLedgerPeers,
numberOfKnownLocalRootPeers = numberOfColdLocalRootPeers,
numberOfEstablishedLocalRootPeers = numberOfWarmLocalRootPeers,
numberOfActiveLocalRootPeers = numberOfHotLocalRootPeers
})
{-# COMPLETE PeerSelectionCountersHWC #-}
-- | Internal function; used to implement `PeerSelectionCountersHWC` pattern synonym.
--
peerSelectionCountersHWC :: PeerSelectionCounters -> PeerSelectionCounters
peerSelectionCountersHWC PeerSelectionCounters {..} =
PeerSelectionCounters {
numberOfRootPeers,
numberOfKnownPeers = numberOfKnownPeers
- numberOfEstablishedPeers,
numberOfColdPeersPromotions,
numberOfEstablishedPeers = numberOfEstablishedPeers
- numberOfActivePeers,
numberOfWarmPeersDemotions,
numberOfWarmPeersPromotions,
numberOfActivePeers,
numberOfActivePeersDemotions,
numberOfKnownBigLedgerPeers = numberOfKnownBigLedgerPeers
- numberOfEstablishedBigLedgerPeers,
numberOfColdBigLedgerPeersPromotions,
numberOfEstablishedBigLedgerPeers = numberOfEstablishedBigLedgerPeers
- numberOfActiveBigLedgerPeers,
numberOfWarmBigLedgerPeersDemotions,
numberOfWarmBigLedgerPeersPromotions,
numberOfActiveBigLedgerPeers,
numberOfActiveBigLedgerPeersDemotions,
numberOfKnownLocalRootPeers = numberOfKnownLocalRootPeers
- numberOfEstablishedLocalRootPeers,
numberOfEstablishedLocalRootPeers = numberOfEstablishedLocalRootPeers
- numberOfActiveLocalRootPeers,
numberOfWarmLocalRootPeersPromotions,
numberOfActiveLocalRootPeers,
numberOfActiveLocalRootPeersDemotions,
numberOfKnownSharedPeers = numberOfKnownSharedPeers
- numberOfEstablishedSharedPeers,
numberOfColdSharedPeersPromotions,
numberOfEstablishedSharedPeers = numberOfEstablishedSharedPeers
- numberOfActiveSharedPeers,
numberOfWarmSharedPeersDemotions,
numberOfWarmSharedPeersPromotions,
numberOfActiveSharedPeers,
numberOfActiveSharedPeersDemotions,
numberOfKnownBootstrapPeers = numberOfKnownBootstrapPeers
- numberOfEstablishedBootstrapPeers,
numberOfColdBootstrapPeersPromotions,
numberOfEstablishedBootstrapPeers = numberOfEstablishedBootstrapPeers
- numberOfActiveBootstrapPeers,
numberOfWarmBootstrapPeersDemotions,
numberOfWarmBootstrapPeersPromotions,
numberOfActiveBootstrapPeers,
numberOfActiveBootstrapPeersDemotions
}
peerSelectionStateToCounters :: Ord peeraddr => PeerSelectionState peeraddr peerconn -> PeerSelectionCounters
peerSelectionStateToCounters
PeerSelectionState {
knownPeers,
establishedPeers,
activePeers,
publicRootPeers,
localRootPeers,
inProgressPromoteCold,
inProgressPromoteWarm,
inProgressDemoteWarm,
inProgressDemoteHot
}
=
PeerSelectionCounters {
numberOfRootPeers = Set.size rootPeersSet,
numberOfKnownPeers = Set.size knownPeersSet,
numberOfColdPeersPromotions = Set.size $ inProgressPromoteCold Set.\\ bigLedgerSet,
numberOfEstablishedPeers = Set.size establishedPeersSet,
numberOfWarmPeersDemotions = Set.size $ inProgressDemoteWarm Set.\\ bigLedgerSet,
numberOfWarmPeersPromotions = Set.size $ inProgressPromoteWarm Set.\\ bigLedgerSet,
numberOfActivePeers = Set.size activePeersSet,
numberOfActivePeersDemotions = Set.size $ activePeersSet `Set.intersection` inProgressDemoteHot,
numberOfKnownBigLedgerPeers = Set.size bigLedgerSet,
numberOfColdBigLedgerPeersPromotions = Set.size $ bigLedgerSet `Set.intersection` inProgressPromoteCold,
numberOfEstablishedBigLedgerPeers = Set.size establishedBigLedgerPeersSet,
numberOfWarmBigLedgerPeersDemotions = Set.size $ inProgressDemoteWarm `Set.intersection` bigLedgerSet,
numberOfWarmBigLedgerPeersPromotions = Set.size $ inProgressPromoteWarm `Set.intersection` bigLedgerSet,
numberOfActiveBigLedgerPeers = Set.size activeBigLedgerPeersSet,
numberOfActiveBigLedgerPeersDemotions = Set.size $ bigLedgerSet `Set.intersection` inProgressDemoteHot,
numberOfKnownBootstrapPeers = Set.size knownBootstrapPeersSet,
numberOfColdBootstrapPeersPromotions = Set.size $ knownBootstrapPeersSet `Set.intersection` inProgressPromoteCold,
numberOfEstablishedBootstrapPeers = Set.size establishedBootstrapPeersSet,
numberOfWarmBootstrapPeersDemotions = Set.size $ establishedBootstrapPeersSet `Set.intersection` inProgressDemoteWarm,
numberOfWarmBootstrapPeersPromotions = Set.size $ establishedBootstrapPeersSet `Set.intersection` inProgressPromoteWarm,
numberOfActiveBootstrapPeers = Set.size activeBootstrapPeersSet,
numberOfActiveBootstrapPeersDemotions = Set.size $ activeBootstrapPeersSet `Set.intersection` inProgressDemoteHot,
numberOfKnownLocalRootPeers = Set.size knownLocalRootPeersSet,
numberOfEstablishedLocalRootPeers = Set.size $ establishedLocalRootsPeersSet,
numberOfWarmLocalRootPeersPromotions = Set.size $ establishedLocalRootsPeersSet `Set.intersection` inProgressPromoteWarm,
numberOfActiveLocalRootPeers = Set.size activeLocalRootsPeersSet,
numberOfActiveLocalRootPeersDemotions = Set.size $ activeLocalRootsPeersSet `Set.intersection` inProgressDemoteHot,
numberOfKnownSharedPeers = Set.size knownSharedPeersSet,
numberOfColdSharedPeersPromotions = Set.size $ knownSharedPeersSet `Set.intersection` inProgressPromoteCold,
numberOfEstablishedSharedPeers = Set.size establishedSharedPeersSet,
numberOfWarmSharedPeersDemotions = Set.size $ establishedSharedPeersSet `Set.intersection` inProgressDemoteWarm,
numberOfWarmSharedPeersPromotions = Set.size $ establishedSharedPeersSet `Set.intersection` inProgressPromoteWarm,
numberOfActiveSharedPeers = Set.size activeSharedPeersSet,
numberOfActiveSharedPeersDemotions = Set.size $ activeSharedPeersSet `Set.intersection` inProgressDemoteHot
}
where
-- convention: only `{known,established,active}.*PeersSet` and
-- `inProgress{Promote,Demote}{Cold,Warm,Hot}` identifiers are used in the
-- calculations above ↑
-- common sets
knownSet = KnownPeers.toSet knownPeers
establishedSet = EstablishedPeers.toSet establishedPeers
bigLedgerSet = PublicRootPeers.getBigLedgerPeers publicRootPeers
-- root peers
rootPeersSet = PublicRootPeers.toSet publicRootPeers
<> localRootSet
-- non big ledger peers
knownPeersSet = knownSet Set.\\ bigLedgerSet
establishedPeersSet = establishedSet Set.\\ bigLedgerSet
activePeersSet = activePeers Set.\\ bigLedgerSet
-- big ledger peers
establishedBigLedgerPeersSet = establishedSet `Set.intersection` bigLedgerSet
activeBigLedgerPeersSet = activePeers `Set.intersection` bigLedgerSet
-- local roots
localRootSet = LocalRootPeers.keysSet localRootPeers
-- local roots and big ledger peers are disjoint, hence we can use
-- `knownPeersSet`, `establishedPeersSet` and `activePeersSet` below.
knownLocalRootPeersSet = localRootSet
establishedLocalRootsPeersSet = establishedPeersSet `Set.intersection` localRootSet
activeLocalRootsPeersSet = activePeersSet `Set.intersection` localRootSet
-- bootstrap peers
bootstrapSet = PublicRootPeers.getBootstrapPeers publicRootPeers
-- bootstrap peers and big ledger peers are disjoint, hence we can use
-- `knownPeersSet`, `establishedPeersSet` and `activePeersSet` below.
knownBootstrapPeersSet = bootstrapSet
establishedBootstrapPeersSet = establishedPeersSet `Set.intersection` bootstrapSet
activeBootstrapPeersSet = activePeersSet `Set.intersection` bootstrapSet
-- shared peers
-- shared peers are not big ledger peers, hence we can use `knownPeersSet`,
-- `establishedPeersSet` and `activePeersSet` below.
knownSharedPeersSet = knownPeersSet Set.\\ rootPeersSet
establishedSharedPeersSet = establishedPeersSet Set.\\ rootPeersSet
activeSharedPeersSet = activePeersSet Set.\\ rootPeersSet
emptyPeerSelectionCounters :: PeerSelectionCounters
emptyPeerSelectionCounters =
PeerSelectionCounters {
numberOfRootPeers = 0,
numberOfKnownPeers = 0,
numberOfColdPeersPromotions = 0,
numberOfEstablishedPeers = 0,
numberOfWarmPeersDemotions = 0,
numberOfWarmPeersPromotions = 0,
numberOfActivePeers = 0,
numberOfActivePeersDemotions = 0,
numberOfKnownBigLedgerPeers = 0,
numberOfColdBigLedgerPeersPromotions = 0,
numberOfEstablishedBigLedgerPeers = 0,
numberOfWarmBigLedgerPeersDemotions = 0,
numberOfWarmBigLedgerPeersPromotions = 0,
numberOfActiveBigLedgerPeers = 0,
numberOfActiveBigLedgerPeersDemotions = 0,
numberOfKnownBootstrapPeers = 0,
numberOfColdBootstrapPeersPromotions = 0,
numberOfEstablishedBootstrapPeers = 0,
numberOfWarmBootstrapPeersDemotions = 0,
numberOfWarmBootstrapPeersPromotions = 0,
numberOfActiveBootstrapPeers = 0,
numberOfActiveBootstrapPeersDemotions = 0,
numberOfKnownLocalRootPeers = 0,
numberOfEstablishedLocalRootPeers = 0,
numberOfWarmLocalRootPeersPromotions = 0,
numberOfActiveLocalRootPeers = 0,
numberOfActiveLocalRootPeersDemotions = 0,
numberOfKnownSharedPeers = 0,
numberOfColdSharedPeersPromotions = 0,
numberOfEstablishedSharedPeers = 0,
numberOfWarmSharedPeersDemotions = 0,
numberOfWarmSharedPeersPromotions = 0,
numberOfActiveSharedPeers = 0,
numberOfActiveSharedPeersDemotions = 0
}
emptyPeerSelectionState :: StdGen
-> PeerSelectionState peeraddr peerconn
emptyPeerSelectionState rng =
PeerSelectionState {
targets = nullPeerSelectionTargets,
localRootPeers = LocalRootPeers.empty,
publicRootPeers = PublicRootPeers.empty,
knownPeers = KnownPeers.empty,
establishedPeers = EstablishedPeers.empty,
activePeers = Set.empty,
publicRootBackoffs = 0,
publicRootRetryTime = Time 0,
inProgressPublicRootsReq = False,
bigLedgerPeerBackoffs = 0,
bigLedgerPeerRetryTime = Time 0,
inProgressBigLedgerPeersReq = False,
inProgressPeerShareReqs = 0,
inProgressPromoteCold = Set.empty,
inProgressPromoteWarm = Set.empty,
inProgressDemoteWarm = Set.empty,
inProgressDemoteHot = Set.empty,
inProgressDemoteToCold = Set.empty,
fuzzRng = rng,
ledgerStateJudgement = TooOld,
bootstrapPeersFlag = DontUseBootstrapPeers,
hasOnlyBootstrapPeers = False,
bootstrapPeersTimeout = Nothing
}
assertPeerSelectionState :: Ord peeraddr
=> PeerSelectionState peeraddr peerconn
-> a -> a
assertPeerSelectionState PeerSelectionState{..} =
assert (KnownPeers.invariant knownPeers)
. assert (EstablishedPeers.invariant establishedPeers)
. assert (LocalRootPeers.invariant localRootPeers)
. assert (PublicRootPeers.invariant publicRootPeers)
-- The activePeers is a subset of the establishedPeers
-- which is a subset of the known peers
. assert (Set.isSubsetOf activePeersSet establishedReadySet)
. assert (Set.isSubsetOf establishedPeersSet knownPeersSet)
-- The localRootPeers and publicRootPeers must not overlap.
. assert (Set.null (Set.intersection localRootPeersSet publicRootPeersSet))
-- The localRootPeers are a subset of the knownPeers,
-- and with correct source info in the knownPeers (either
-- 'PeerSourcePublicRoot' or 'PeerSourceLocalRoot', as local and public
-- root peers might overlap).
. assert (Set.isSubsetOf localRootPeersSet knownPeersSet)
-- The publicRootPeers are a subset of the knownPeers,
. assert (Set.isSubsetOf publicRootPeersSet knownPeersSet)
-- The targets should respect the containment relationships of the root,
-- known, established and active peers
. assert (sanePeerSelectionTargets targets)
-- All the local root peers are always a subset of the known peers. The
-- target for known peers is a target from both below and above. Thus the
-- number of local root peers must be less than or equal to the known peers
-- target, otherwise we could get stuck.
. assert (LocalRootPeers.size localRootPeers <= targetNumberOfKnownPeers targets)
-- Interestingly, although the local root peers are also a subset of the
-- root peers, the equivalent constraint does not apply to the target
-- number of root peers. The reason is that the root peers target is only
-- a target from below, not from above. It is ok to have more than the
-- target number of root peers.
--
--That is, we do /not/ need or want this invariant:
-- LocalRootPeers.size localRootPeers <= targetNumberOfRootPeers
--
-- It is also not necessary for all the targets to be achievable. It is
-- just necessary that we do not get stuck. So although we have an implicit
-- target that all local root peers become established, and a certain
-- number of them become active, these targets do not need to be achievable.
--
--That is, we do /not/ need or want this invariant:
-- LocalRootPeers.size localRootPeers <= targetNumberOfEstablishedPeers
-- LocalRootPeers.target localRootPeers <= targetNumberOfActivePeers
--
-- All currently established peers are in the availableToConnect set since
-- the alternative is a record of failure, but these are not (yet) failed.
. assert (Set.isSubsetOf establishedPeersSet (KnownPeers.availableToConnect knownPeers))
-- The following aren't hard invariants but rather eventually consistent
-- invariants that are checked via testing:
-- 1. If node is not in sensitive state then it can't have only BootstrapPeers
--
-- 2. If hasOnlyBootstrapPeers is true and bootstrap peers are enabled then known
-- peers set is a subset of the bootstrap peers + trusted local roots.
-- Unless the TargetKnownRootPeers is 0, in that case there can be a delay
-- where the node forgets the local roots.
-- No constraint for publicRootBackoffs, publicRootRetryTime
-- or inProgressPublicRootsReq
. assert (inProgressPeerShareReqs >= 0)
. assert (Set.isSubsetOf inProgressPromoteCold coldPeersSet)
. assert (Set.isSubsetOf inProgressPromoteWarm warmPeersSet)
. assert (Set.isSubsetOf inProgressDemoteWarm warmPeersSet)
. assert (Set.isSubsetOf inProgressDemoteHot hotPeersSet)
. assert (Set.null (Set.intersection inProgressPromoteWarm inProgressDemoteWarm))
. assert (Set.isSubsetOf inProgressDemoteToCold establishedPeersSet)
. assert (Set.null (Set.intersection inProgressDemoteToCold inProgressPromoteWarm))
. assert (Set.null (Set.intersection inProgressDemoteToCold inProgressPromoteCold))
. assert (Set.null (Set.intersection inProgressDemoteToCold inProgressDemoteHot))