-
Notifications
You must be signed in to change notification settings - Fork 731
/
Copy pathLedgerState.hs
1563 lines (1410 loc) · 70.3 KB
/
LedgerState.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 DataKinds #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
module Cardano.Api.LedgerState
( -- * Initialization / Accumulation
Env(..)
, envSecurityParam
, LedgerState
( ..
, LedgerStateByron
, LedgerStateShelley
, LedgerStateAllegra
, LedgerStateMary
, LedgerStateAlonzo
)
, initialLedgerState
, applyBlock
, ValidationMode(..)
, applyBlockWithEvents
-- * Traversing the block chain
, foldBlocks
, chainSyncClientWithLedgerState
, chainSyncClientPipelinedWithLedgerState
-- * Errors
, LedgerStateError(..)
, FoldBlocksError(..)
, GenesisConfigError(..)
, InitialLedgerStateError(..)
, renderLedgerStateError
, renderFoldBlocksError
, renderGenesisConfigError
, renderInitialLedgerStateError
-- * Leadership schedule
, LeadershipError(..)
, constructGlobals
, currentEpochEligibleLeadershipSlots
, nextEpochEligibleLeadershipSlots
)
where
import Control.Exception
import Control.Monad (when)
import Control.Monad.Trans.Class
import Control.Monad.Trans.Except
import Control.Monad.Trans.Except.Extra (firstExceptT, handleIOExceptT, hoistEither, left)
import Control.State.Transition
import Data.Aeson as Aeson
import Data.Aeson.Types (Parser)
import Data.Bifunctor
import Data.ByteArray (ByteArrayAccess)
import qualified Data.ByteArray
import Data.ByteString as BS
import qualified Data.ByteString.Base16 as Base16
import qualified Data.ByteString.Lazy as LB
import Data.ByteString.Short as BSS
import Data.Foldable
import Data.IORef
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (mapMaybe)
import Data.Proxy (Proxy (Proxy))
import Data.Sequence (Seq)
import qualified Data.Sequence as Seq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Sharing (FromSharedCBOR, Interns, Share)
import Data.SOP.Strict (NP (..))
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text
import qualified Data.Text.Lazy as LT
import Data.Text.Lazy.Builder (toLazyText)
import Data.Word
import qualified Data.Yaml as Yaml
import Formatting.Buildable (build)
import GHC.Records (HasField (..))
import Network.TypedProtocol.Pipelined (Nat (..))
import System.FilePath
import Cardano.Api.Block
import Cardano.Api.Certificate
import Cardano.Api.Eras
import Cardano.Api.Error
import Cardano.Api.IPC (ConsensusModeParams (..),
LocalChainSyncClient (LocalChainSyncClientPipelined),
LocalNodeClientProtocols (..), LocalNodeClientProtocolsInMode,
LocalNodeConnectInfo (..), connectToLocalNode)
import Cardano.Api.Keys.Praos
import Cardano.Api.LedgerEvent (LedgerEvent, toLedgerEvent)
import Cardano.Api.Modes (CardanoMode, EpochSlots (..))
import qualified Cardano.Api.Modes as Api
import Cardano.Api.NetworkId (NetworkId (..), NetworkMagic (NetworkMagic))
import Cardano.Api.ProtocolParameters
import Cardano.Api.Query (CurrentEpochState (..), PoolDistribution (unPoolDistr),
ProtocolState, SerialisedCurrentEpochState (..), SerialisedPoolDistribution,
decodeCurrentEpochState, decodePoolDistribution, decodeProtocolState)
import Cardano.Api.Utils (textShow)
import Cardano.Binary (DecoderError, FromCBOR)
import qualified Cardano.Chain.Genesis
import qualified Cardano.Chain.Update
import Cardano.Crypto (ProtocolMagicId (unProtocolMagicId), RequiresNetworkMagic (..))
import qualified Cardano.Crypto.Hash.Blake2b
import qualified Cardano.Crypto.Hash.Class
import qualified Cardano.Crypto.Hashing
import qualified Cardano.Crypto.ProtocolMagic
import qualified Cardano.Crypto.VRF as Crypto
import qualified Cardano.Crypto.VRF.Class as VRF
import Cardano.Ledger.Alonzo.Genesis (AlonzoGenesis (..))
import Cardano.Ledger.BaseTypes (Globals (..), Nonce, UnitInterval, (⭒))
import qualified Cardano.Ledger.BaseTypes as Shelley.Spec
import qualified Cardano.Ledger.BHeaderView as Ledger
import qualified Cardano.Ledger.Core as Core
import qualified Cardano.Ledger.Credential as Shelley.Spec
import qualified Cardano.Ledger.Era
import qualified Cardano.Ledger.Era as Ledger
import qualified Cardano.Ledger.Keys as Shelley.Spec
import qualified Cardano.Ledger.Keys as SL
import qualified Cardano.Ledger.PoolDistr as SL
import Cardano.Ledger.SafeHash (HashAnnotated)
import qualified Cardano.Ledger.Shelley.API as ShelleyAPI
import qualified Cardano.Ledger.Shelley.Genesis as Shelley.Spec
import qualified Cardano.Protocol.TPraos.API as TPraos
import Cardano.Protocol.TPraos.BHeader (checkLeaderNatValue)
import qualified Cardano.Protocol.TPraos.BHeader as TPraos
import Cardano.Slotting.EpochInfo (EpochInfo)
import qualified Cardano.Slotting.EpochInfo.API as Slot
import Cardano.Slotting.Slot (WithOrigin (At, Origin))
import qualified Cardano.Slotting.Slot as Slot
import qualified Ouroboros.Consensus.Block.Abstract as Consensus
import qualified Ouroboros.Consensus.Byron.Ledger.Block as Byron
import qualified Ouroboros.Consensus.Cardano as Consensus
import qualified Ouroboros.Consensus.Cardano.Block as Consensus
import qualified Ouroboros.Consensus.Cardano.CanHardFork as Consensus
import qualified Ouroboros.Consensus.Cardano.Node as Consensus
import qualified Ouroboros.Consensus.Config as Consensus
import qualified Ouroboros.Consensus.HardFork.Combinator as Consensus
import qualified Ouroboros.Consensus.HardFork.Combinator.AcrossEras as HFC
import qualified Ouroboros.Consensus.HardFork.Combinator.Basics as HFC
import qualified Ouroboros.Consensus.Ledger.Abstract as Ledger
import Ouroboros.Consensus.Ledger.Basics (LedgerResult (lrEvents), lrResult)
import qualified Ouroboros.Consensus.Ledger.Extended as Ledger
import qualified Ouroboros.Consensus.Mempool.TxLimits as TxLimits
import qualified Ouroboros.Consensus.Node.ProtocolInfo as Consensus
import Ouroboros.Consensus.Protocol.Abstract (ChainDepState, ConsensusProtocol (..))
import qualified Ouroboros.Consensus.Protocol.Abstract as Consensus
import qualified Ouroboros.Consensus.Protocol.Praos.Common as Consensus
import Ouroboros.Consensus.Protocol.Praos.VRF (mkInputVRF, vrfLeaderValue)
import qualified Ouroboros.Consensus.Protocol.TPraos as TPraos
import qualified Ouroboros.Consensus.Shelley.Eras as Shelley
import qualified Ouroboros.Consensus.Shelley.Ledger.Block as Shelley
import qualified Ouroboros.Consensus.Shelley.Ledger.Ledger as Shelley
import Ouroboros.Consensus.Shelley.Node (ShelleyGenesis (..))
import qualified Ouroboros.Consensus.Shelley.Node.Praos as Consensus
import Ouroboros.Consensus.TypeFamilyWrappers (WrapLedgerEvent (WrapLedgerEvent))
import qualified Ouroboros.Network.Block
import qualified Ouroboros.Network.Protocol.ChainSync.Client as CS
import qualified Ouroboros.Network.Protocol.ChainSync.ClientPipelined as CSP
import Ouroboros.Network.Protocol.ChainSync.PipelineDecision
data InitialLedgerStateError
= ILSEConfigFile Text
-- ^ Failed to read or parse the network config file.
| ILSEGenesisFile GenesisConfigError
-- ^ Failed to read or parse a genesis file linked from the network config file.
| ILSELedgerConsensusConfig GenesisConfigError
-- ^ Failed to derive the Ledger or Consensus config.
renderInitialLedgerStateError :: InitialLedgerStateError -> Text
renderInitialLedgerStateError ilse = case ilse of
ILSEConfigFile err ->
"Failed to read or parse the network config file: " <> err
ILSEGenesisFile err ->
"Failed to read or parse a genesis file linked from the network config file: "
<> renderGenesisConfigError err
ILSELedgerConsensusConfig err ->
"Failed to derive the Ledger or Consensus config: "
<> renderGenesisConfigError err
data LedgerStateError
= ApplyBlockHashMismatch Text
-- ^ When using QuickValidation, the block hash did not match the expected
-- block hash after applying a new block to the current ledger state.
| ApplyBlockError (Consensus.HardForkLedgerError (Consensus.CardanoEras Consensus.StandardCrypto))
-- ^ When using FullValidation, an error occurred when applying a new block
-- to the current ledger state.
| InvalidRollback
-- ^ Encountered a rollback larger than the security parameter.
SlotNo -- ^ Oldest known slot number that we can roll back to.
ChainPoint -- ^ Rollback was attempted to this point.
deriving (Show)
renderLedgerStateError :: LedgerStateError -> Text
renderLedgerStateError = \case
ApplyBlockHashMismatch err -> "Applying a block did not result in the expected block hash: " <> err
ApplyBlockError hardForkLedgerError -> "Applying a block resulted in an error: " <> textShow hardForkLedgerError
InvalidRollback oldestSupported rollbackPoint ->
"Encountered a rollback larger than the security parameter. Attempted to roll back to "
<> textShow rollbackPoint
<> ", but oldest supported slot is "
<> textShow oldestSupported
-- | Get the environment and initial ledger state.
initialLedgerState
:: FilePath
-- ^ Path to the cardano-node config file (e.g. <path to cardano-node project>/configuration/cardano/mainnet-config.json)
-> ExceptT InitialLedgerStateError IO (Env, LedgerState)
-- ^ The environment and initial ledger state
initialLedgerState networkConfigFile = do
-- TODO Once support for querying the ledger config is added to the node, we
-- can remove the networkConfigFile argument and much of the code in this
-- module.
config <- withExceptT ILSEConfigFile
(readNetworkConfig (NetworkConfigFile networkConfigFile))
genesisConfig <- withExceptT ILSEGenesisFile (readCardanoGenesisConfig config)
env <- withExceptT ILSELedgerConsensusConfig (except (genesisConfigToEnv genesisConfig))
let ledgerState = initLedgerStateVar genesisConfig
return (env, ledgerState)
-- | Apply a single block to the current ledger state.
applyBlock
:: Env
-- ^ The environment returned by @initialLedgerState@
-> LedgerState
-- ^ The current ledger state
-> ValidationMode
-> Block era
-- ^ Some block to apply
-> Either LedgerStateError (LedgerState, [LedgerEvent])
-- ^ The new ledger state (or an error).
applyBlock env oldState validationMode block
= applyBlock' env oldState validationMode $ case block of
ByronBlock byronBlock -> Consensus.BlockByron byronBlock
ShelleyBlock blockEra shelleyBlock -> case blockEra of
ShelleyBasedEraShelley -> Consensus.BlockShelley shelleyBlock
ShelleyBasedEraAllegra -> Consensus.BlockAllegra shelleyBlock
ShelleyBasedEraMary -> Consensus.BlockMary shelleyBlock
ShelleyBasedEraAlonzo -> Consensus.BlockAlonzo shelleyBlock
ShelleyBasedEraBabbage -> Consensus.BlockBabbage shelleyBlock
pattern LedgerStateByron
:: Ledger.LedgerState Byron.ByronBlock
-> LedgerState
pattern LedgerStateByron st <- LedgerState (Consensus.LedgerStateByron st)
pattern LedgerStateShelley
:: Ledger.LedgerState (Shelley.ShelleyBlock protocol (Shelley.ShelleyEra Shelley.StandardCrypto))
-> LedgerState
pattern LedgerStateShelley st <- LedgerState (Consensus.LedgerStateShelley st)
pattern LedgerStateAllegra
:: Ledger.LedgerState (Shelley.ShelleyBlock protocol (Shelley.AllegraEra Shelley.StandardCrypto))
-> LedgerState
pattern LedgerStateAllegra st <- LedgerState (Consensus.LedgerStateAllegra st)
pattern LedgerStateMary
:: Ledger.LedgerState (Shelley.ShelleyBlock protocol (Shelley.MaryEra Shelley.StandardCrypto))
-> LedgerState
pattern LedgerStateMary st <- LedgerState (Consensus.LedgerStateMary st)
pattern LedgerStateAlonzo
:: Ledger.LedgerState (Shelley.ShelleyBlock protocol (Shelley.AlonzoEra Shelley.StandardCrypto))
-> LedgerState
pattern LedgerStateAlonzo st <- LedgerState (Consensus.LedgerStateAlonzo st)
{-# COMPLETE LedgerStateByron
, LedgerStateShelley
, LedgerStateAllegra
, LedgerStateMary
, LedgerStateAlonzo #-}
data FoldBlocksError
= FoldBlocksInitialLedgerStateError InitialLedgerStateError
| FoldBlocksApplyBlockError LedgerStateError
renderFoldBlocksError :: FoldBlocksError -> Text
renderFoldBlocksError fbe = case fbe of
FoldBlocksInitialLedgerStateError err -> renderInitialLedgerStateError err
FoldBlocksApplyBlockError err -> "Failed when applying a block: " <> renderLedgerStateError err
-- | Monadic fold over all blocks and ledger states. Stopping @k@ blocks before
-- the node's tip where @k@ is the security parameter.
foldBlocks
:: forall a.
FilePath
-- ^ Path to the cardano-node config file (e.g. <path to cardano-node project>/configuration/cardano/mainnet-config.json)
-> FilePath
-- ^ Path to local cardano-node socket. This is the path specified by the @--socket-path@ command line option when running the node.
-> ValidationMode
-> a
-- ^ The initial accumulator state.
-> (Env -> LedgerState -> [LedgerEvent] -> BlockInMode CardanoMode -> a -> IO a)
-- ^ Accumulator function Takes:
--
-- * Environment (this is a constant over the whole fold).
-- * The Ledger state (with block @i@ applied) at block @i@.
-- * The Ledger events resulting from applying block @i@.
-- * Block @i@.
-- * The accumulator state at block @i - 1@.
--
-- And returns:
--
-- * The accumulator state at block @i@
--
-- Note: This function can safely assume no rollback will occur even though
-- internally this is implemented with a client protocol that may require
-- rollback. This is achieved by only calling the accumulator on states/blocks
-- that are older than the security parameter, k. This has the side effect of
-- truncating the last k blocks before the node's tip.
-> ExceptT FoldBlocksError IO a
-- ^ The final state
foldBlocks nodeConfigFilePath socketPath validationMode state0 accumulate = do
-- NOTE this was originally implemented with a non-pipelined client then
-- changed to a pipelined client for a modest speedup:
-- * Non-pipelined: 1h 0m 19s
-- * Pipelined: 46m 23s
(env, ledgerState) <- withExceptT FoldBlocksInitialLedgerStateError
(initialLedgerState nodeConfigFilePath)
-- Place to store the accumulated state
-- This is a bit ugly, but easy.
errorIORef <- lift $ newIORef Nothing
stateIORef <- lift $ newIORef state0
-- Derive the NetworkId as described in network-magic.md from the
-- cardano-ledger-specs repo.
let byronConfig
= (\(Consensus.WrapPartialLedgerConfig (Consensus.ByronPartialLedgerConfig bc _) :* _) -> bc)
. HFC.getPerEraLedgerConfig
. HFC.hardForkLedgerConfigPerEra
$ envLedgerConfig env
networkMagic
= NetworkMagic
$ unProtocolMagicId
$ Cardano.Chain.Genesis.gdProtocolMagicId
$ Cardano.Chain.Genesis.configGenesisData byronConfig
networkId' = case Cardano.Chain.Genesis.configReqNetMagic byronConfig of
RequiresNoMagic -> Mainnet
RequiresMagic -> Testnet networkMagic
cardanoModeParams = CardanoModeParams . EpochSlots $ 10 * envSecurityParam env
-- Connect to the node.
let connectInfo :: LocalNodeConnectInfo CardanoMode
connectInfo =
LocalNodeConnectInfo {
localConsensusModeParams = cardanoModeParams,
localNodeNetworkId = networkId',
localNodeSocketPath = socketPath
}
lift $ connectToLocalNode
connectInfo
(protocols stateIORef errorIORef env ledgerState)
lift (readIORef errorIORef) >>= \case
Just err -> throwE (FoldBlocksApplyBlockError err)
Nothing -> lift $ readIORef stateIORef
where
protocols :: IORef a -> IORef (Maybe LedgerStateError) -> Env -> LedgerState -> LocalNodeClientProtocolsInMode CardanoMode
protocols stateIORef errorIORef env ledgerState =
LocalNodeClientProtocols {
localChainSyncClient = LocalChainSyncClientPipelined (chainSyncClient 50 stateIORef errorIORef env ledgerState),
localTxSubmissionClient = Nothing,
localStateQueryClient = Nothing,
localTxMonitoringClient = Nothing
}
-- | Defines the client side of the chain sync protocol.
chainSyncClient :: Word32
-- ^ The maximum number of concurrent requests.
-> IORef a
-> IORef (Maybe LedgerStateError)
-- ^ Resulting error if any. Written to once on protocol
-- completion.
-> Env
-> LedgerState
-> CSP.ChainSyncClientPipelined
(BlockInMode CardanoMode)
ChainPoint
ChainTip
IO ()
-- ^ Client returns maybe an error.
chainSyncClient pipelineSize stateIORef errorIORef env ledgerState0
= CSP.ChainSyncClientPipelined $ pure $ clientIdle_RequestMoreN Origin Origin Zero initialLedgerStateHistory
where
initialLedgerStateHistory = Seq.singleton (0, (ledgerState0, []), Origin)
clientIdle_RequestMoreN
:: WithOrigin BlockNo
-> WithOrigin BlockNo
-> Nat n -- Number of requests inflight.
-> LedgerStateHistory
-> CSP.ClientPipelinedStIdle n (BlockInMode CardanoMode) ChainPoint ChainTip IO ()
clientIdle_RequestMoreN clientTip serverTip n knownLedgerStates
= case pipelineDecisionMax pipelineSize n clientTip serverTip of
Collect -> case n of
Succ predN -> CSP.CollectResponse Nothing (clientNextN predN knownLedgerStates)
_ -> CSP.SendMsgRequestNextPipelined (clientIdle_RequestMoreN clientTip serverTip (Succ n) knownLedgerStates)
clientNextN
:: Nat n -- Number of requests inflight.
-> LedgerStateHistory
-> CSP.ClientStNext n (BlockInMode CardanoMode) ChainPoint ChainTip IO ()
clientNextN n knownLedgerStates =
CSP.ClientStNext {
CSP.recvMsgRollForward = \blockInMode@(BlockInMode block@(Block (BlockHeader slotNo _ currBlockNo) _) _era) serverChainTip -> do
let newLedgerStateE = applyBlock
env
(maybe
(error "Impossible! Missing Ledger state")
(\(_,(ledgerState, _),_) -> ledgerState)
(Seq.lookup 0 knownLedgerStates)
)
validationMode
block
case newLedgerStateE of
Left err -> clientIdle_DoneN n (Just err)
Right newLedgerState -> do
let (knownLedgerStates', committedStates) = pushLedgerState env knownLedgerStates slotNo newLedgerState blockInMode
newClientTip = At currBlockNo
newServerTip = fromChainTip serverChainTip
forM_ committedStates $ \(_, (ledgerState, ledgerEvents), currBlockMay) -> case currBlockMay of
Origin -> return ()
At currBlock -> do
newState <- accumulate
env
ledgerState
ledgerEvents
currBlock
=<< readIORef stateIORef
writeIORef stateIORef newState
if newClientTip == newServerTip
then clientIdle_DoneN n Nothing
else return (clientIdle_RequestMoreN newClientTip newServerTip n knownLedgerStates')
, CSP.recvMsgRollBackward = \chainPoint serverChainTip -> do
let newClientTip = Origin -- We don't actually keep track of blocks so we temporarily "forget" the tip.
newServerTip = fromChainTip serverChainTip
truncatedKnownLedgerStates = case chainPoint of
ChainPointAtGenesis -> initialLedgerStateHistory
ChainPoint slotNo _ -> rollBackLedgerStateHist knownLedgerStates slotNo
return (clientIdle_RequestMoreN newClientTip newServerTip n truncatedKnownLedgerStates)
}
clientIdle_DoneN
:: Nat n -- Number of requests inflight.
-> Maybe LedgerStateError -- Return value (maybe an error)
-> IO (CSP.ClientPipelinedStIdle n (BlockInMode CardanoMode) ChainPoint ChainTip IO ())
clientIdle_DoneN n errorMay = case n of
Succ predN -> return (CSP.CollectResponse Nothing (clientNext_DoneN predN errorMay)) -- Ignore remaining message responses
Zero -> do
writeIORef errorIORef errorMay
return (CSP.SendMsgDone ())
clientNext_DoneN
:: Nat n -- Number of requests inflight.
-> Maybe LedgerStateError -- Return value (maybe an error)
-> CSP.ClientStNext n (BlockInMode CardanoMode) ChainPoint ChainTip IO ()
clientNext_DoneN n errorMay =
CSP.ClientStNext {
CSP.recvMsgRollForward = \_ _ -> clientIdle_DoneN n errorMay
, CSP.recvMsgRollBackward = \_ _ -> clientIdle_DoneN n errorMay
}
fromChainTip :: ChainTip -> WithOrigin BlockNo
fromChainTip ct = case ct of
ChainTipAtGenesis -> Origin
ChainTip _ _ bno -> At bno
-- | Wrap a 'ChainSyncClient' with logic that tracks the ledger state.
chainSyncClientWithLedgerState
:: forall m a.
Monad m
=> Env
-> LedgerState
-- ^ Initial ledger state
-> ValidationMode
-> CS.ChainSyncClient (BlockInMode CardanoMode, Either LedgerStateError (LedgerState, [LedgerEvent]))
ChainPoint
ChainTip
m
a
-- ^ A client to wrap. The block is annotated with a 'Either LedgerStateError
-- LedgerState'. This is either an error from validating a block or
-- the current 'LedgerState' from applying the current block. If we
-- trust the node, then we generally expect blocks to validate. Also note that
-- after a block fails to validate we may still roll back to a validated
-- block, in which case the valid 'LedgerState' will be passed here again.
-> CS.ChainSyncClient (BlockInMode CardanoMode)
ChainPoint
ChainTip
m
a
-- ^ A client that acts just like the wrapped client but doesn't require the
-- 'LedgerState' annotation on the block type.
chainSyncClientWithLedgerState env ledgerState0 validationMode (CS.ChainSyncClient clientTop)
= CS.ChainSyncClient (goClientStIdle (Right initialLedgerStateHistory) <$> clientTop)
where
goClientStIdle
:: Either LedgerStateError (History (Either LedgerStateError LedgerStateEvents))
-> CS.ClientStIdle (BlockInMode CardanoMode, Either LedgerStateError (LedgerState, [LedgerEvent])) ChainPoint ChainTip m a
-> CS.ClientStIdle (BlockInMode CardanoMode ) ChainPoint ChainTip m a
goClientStIdle history client = case client of
CS.SendMsgRequestNext a b -> CS.SendMsgRequestNext (goClientStNext history a) (goClientStNext history <$> b)
CS.SendMsgFindIntersect ps a -> CS.SendMsgFindIntersect ps (goClientStIntersect history a)
CS.SendMsgDone a -> CS.SendMsgDone a
-- This is where the magic happens. We intercept the blocks and rollbacks
-- and use it to maintain the correct ledger state.
goClientStNext
:: Either LedgerStateError (History (Either LedgerStateError LedgerStateEvents))
-> CS.ClientStNext (BlockInMode CardanoMode, Either LedgerStateError (LedgerState, [LedgerEvent])) ChainPoint ChainTip m a
-> CS.ClientStNext (BlockInMode CardanoMode ) ChainPoint ChainTip m a
goClientStNext (Left err) (CS.ClientStNext recvMsgRollForward recvMsgRollBackward) = CS.ClientStNext
(\blkInMode tip -> CS.ChainSyncClient $
goClientStIdle (Left err) <$> CS.runChainSyncClient
(recvMsgRollForward (blkInMode, Left err) tip)
)
(\point tip -> CS.ChainSyncClient $
goClientStIdle (Left err) <$> CS.runChainSyncClient (recvMsgRollBackward point tip)
)
goClientStNext (Right history) (CS.ClientStNext recvMsgRollForward recvMsgRollBackward) = CS.ClientStNext
(\blkInMode@(BlockInMode blk@(Block (BlockHeader slotNo _ _) _) _) tip -> CS.ChainSyncClient $ let
newLedgerStateE = case Seq.lookup 0 history of
Nothing -> error "Impossible! History should always be non-empty"
Just (_, Left err, _) -> Left err
Just (_, Right (oldLedgerState, _), _) -> applyBlock
env
oldLedgerState
validationMode
blk
(history', _) = pushLedgerState env history slotNo newLedgerStateE blkInMode
in goClientStIdle (Right history') <$> CS.runChainSyncClient
(recvMsgRollForward (blkInMode, newLedgerStateE) tip)
)
(\point tip -> let
oldestSlot = case history of
_ Seq.:|> (s, _, _) -> s
Seq.Empty -> error "Impossible! History should always be non-empty"
history' = (\h -> if Seq.null h
then Left (InvalidRollback oldestSlot point)
else Right h)
$ case point of
ChainPointAtGenesis -> initialLedgerStateHistory
ChainPoint slotNo _ -> rollBackLedgerStateHist history slotNo
in CS.ChainSyncClient $ goClientStIdle history' <$> CS.runChainSyncClient (recvMsgRollBackward point tip)
)
goClientStIntersect
:: Either LedgerStateError (History (Either LedgerStateError LedgerStateEvents))
-> CS.ClientStIntersect (BlockInMode CardanoMode, Either LedgerStateError (LedgerState, [LedgerEvent])) ChainPoint ChainTip m a
-> CS.ClientStIntersect (BlockInMode CardanoMode ) ChainPoint ChainTip m a
goClientStIntersect history (CS.ClientStIntersect recvMsgIntersectFound recvMsgIntersectNotFound) = CS.ClientStIntersect
(\point tip -> CS.ChainSyncClient (goClientStIdle history <$> CS.runChainSyncClient (recvMsgIntersectFound point tip)))
(\tip -> CS.ChainSyncClient (goClientStIdle history <$> CS.runChainSyncClient (recvMsgIntersectNotFound tip)))
initialLedgerStateHistory :: History (Either LedgerStateError LedgerStateEvents)
initialLedgerStateHistory = Seq.singleton (0, Right (ledgerState0, []), Origin)
-- | See 'chainSyncClientWithLedgerState'.
chainSyncClientPipelinedWithLedgerState
:: forall m a.
Monad m
=> Env
-> LedgerState
-> ValidationMode
-> CSP.ChainSyncClientPipelined
(BlockInMode CardanoMode, Either LedgerStateError (LedgerState, [LedgerEvent]))
ChainPoint
ChainTip
m
a
-> CSP.ChainSyncClientPipelined
(BlockInMode CardanoMode)
ChainPoint
ChainTip
m
a
chainSyncClientPipelinedWithLedgerState env ledgerState0 validationMode (CSP.ChainSyncClientPipelined clientTop)
= CSP.ChainSyncClientPipelined (goClientPipelinedStIdle (Right initialLedgerStateHistory) Zero <$> clientTop)
where
goClientPipelinedStIdle
:: Either LedgerStateError (History (Either LedgerStateError LedgerStateEvents))
-> Nat n
-> CSP.ClientPipelinedStIdle n (BlockInMode CardanoMode, Either LedgerStateError (LedgerState, [LedgerEvent])) ChainPoint ChainTip m a
-> CSP.ClientPipelinedStIdle n (BlockInMode CardanoMode ) ChainPoint ChainTip m a
goClientPipelinedStIdle history n client = case client of
CSP.SendMsgRequestNext a b -> CSP.SendMsgRequestNext (goClientStNext history n a) (goClientStNext history n <$> b)
CSP.SendMsgRequestNextPipelined a -> CSP.SendMsgRequestNextPipelined (goClientPipelinedStIdle history (Succ n) a)
CSP.SendMsgFindIntersect ps a -> CSP.SendMsgFindIntersect ps (goClientPipelinedStIntersect history n a)
CSP.CollectResponse a b -> case n of
Succ nPrev -> CSP.CollectResponse ((fmap . fmap) (goClientPipelinedStIdle history n) a) (goClientStNext history nPrev b)
CSP.SendMsgDone a -> CSP.SendMsgDone a
-- This is where the magic happens. We intercept the blocks and rollbacks
-- and use it to maintain the correct ledger state.
goClientStNext
:: Either LedgerStateError (History (Either LedgerStateError LedgerStateEvents))
-> Nat n
-> CSP.ClientStNext n (BlockInMode CardanoMode, Either LedgerStateError (LedgerState, [LedgerEvent])) ChainPoint ChainTip m a
-> CSP.ClientStNext n (BlockInMode CardanoMode ) ChainPoint ChainTip m a
goClientStNext (Left err) n (CSP.ClientStNext recvMsgRollForward recvMsgRollBackward) = CSP.ClientStNext
(\blkInMode tip ->
goClientPipelinedStIdle (Left err) n <$> recvMsgRollForward
(blkInMode, Left err) tip
)
(\point tip ->
goClientPipelinedStIdle (Left err) n <$> recvMsgRollBackward point tip
)
goClientStNext (Right history) n (CSP.ClientStNext recvMsgRollForward recvMsgRollBackward) = CSP.ClientStNext
(\blkInMode@(BlockInMode blk@(Block (BlockHeader slotNo _ _) _) _) tip -> let
newLedgerStateE = case Seq.lookup 0 history of
Nothing -> error "Impossible! History should always be non-empty"
Just (_, Left err, _) -> Left err
Just (_, Right (oldLedgerState, _), _) -> applyBlock
env
oldLedgerState
validationMode
blk
(history', _) = pushLedgerState env history slotNo newLedgerStateE blkInMode
in goClientPipelinedStIdle (Right history') n <$> recvMsgRollForward
(blkInMode, newLedgerStateE) tip
)
(\point tip -> let
oldestSlot = case history of
_ Seq.:|> (s, _, _) -> s
Seq.Empty -> error "Impossible! History should always be non-empty"
history' = (\h -> if Seq.null h
then Left (InvalidRollback oldestSlot point)
else Right h)
$ case point of
ChainPointAtGenesis -> initialLedgerStateHistory
ChainPoint slotNo _ -> rollBackLedgerStateHist history slotNo
in goClientPipelinedStIdle history' n <$> recvMsgRollBackward point tip
)
goClientPipelinedStIntersect
:: Either LedgerStateError (History (Either LedgerStateError LedgerStateEvents))
-> Nat n
-> CSP.ClientPipelinedStIntersect (BlockInMode CardanoMode, Either LedgerStateError (LedgerState, [LedgerEvent])) ChainPoint ChainTip m a
-> CSP.ClientPipelinedStIntersect (BlockInMode CardanoMode ) ChainPoint ChainTip m a
goClientPipelinedStIntersect history _ (CSP.ClientPipelinedStIntersect recvMsgIntersectFound recvMsgIntersectNotFound) = CSP.ClientPipelinedStIntersect
(\point tip -> goClientPipelinedStIdle history Zero <$> recvMsgIntersectFound point tip)
(\tip -> goClientPipelinedStIdle history Zero <$> recvMsgIntersectNotFound tip)
initialLedgerStateHistory :: History (Either LedgerStateError LedgerStateEvents)
initialLedgerStateHistory = Seq.singleton (0, Right (ledgerState0, []), Origin)
{- HLINT ignore chainSyncClientPipelinedWithLedgerState "Use fmap" -}
-- | A history of k (security parameter) recent ledger states. The head is the
-- most recent item. Elements are:
--
-- * Slot number that a new block occurred
-- * The ledger state and events after applying the new block
-- * The new block
--
type LedgerStateHistory = History LedgerStateEvents
type History a = Seq (SlotNo, a, WithOrigin (BlockInMode CardanoMode))
-- | Add a new ledger state to the history
pushLedgerState
:: Env -- ^ Environment used to get the security param, k.
-> History a -- ^ History of k items.
-> SlotNo -- ^ Slot number of the new item.
-> a -- ^ New item to add to the history
-> BlockInMode CardanoMode
-- ^ The block that (when applied to the previous
-- item) resulted in the new item.
-> (History a, History a)
-- ^ ( The new history with the new item appended
-- , Any existing items that are now past the security parameter
-- and hence can no longer be rolled back.
-- )
pushLedgerState env hist ix st block
= Seq.splitAt
(fromIntegral $ envSecurityParam env + 1)
((ix, st, At block) Seq.:<| hist)
rollBackLedgerStateHist :: History a -> SlotNo -> History a
rollBackLedgerStateHist hist maxInc = Seq.dropWhileL ((> maxInc) . (\(x,_,_) -> x)) hist
--------------------------------------------------------------------------------
-- Everything below was copied/adapted from db-sync --
--------------------------------------------------------------------------------
genesisConfigToEnv
:: GenesisConfig
-> Either GenesisConfigError Env
genesisConfigToEnv
-- enp
genCfg =
case genCfg of
GenesisCardano _ bCfg sCfg _
| Cardano.Crypto.ProtocolMagic.unProtocolMagicId (Cardano.Chain.Genesis.configProtocolMagicId bCfg) /= Shelley.Spec.sgNetworkMagic (scConfig sCfg) ->
Left . NECardanoConfig $
mconcat
[ "ProtocolMagicId ", textShow (Cardano.Crypto.ProtocolMagic.unProtocolMagicId $ Cardano.Chain.Genesis.configProtocolMagicId bCfg)
, " /= ", textShow (Shelley.Spec.sgNetworkMagic $ scConfig sCfg)
]
| Cardano.Chain.Genesis.gdStartTime (Cardano.Chain.Genesis.configGenesisData bCfg) /= Shelley.Spec.sgSystemStart (scConfig sCfg) ->
Left . NECardanoConfig $
mconcat
[ "SystemStart ", textShow (Cardano.Chain.Genesis.gdStartTime $ Cardano.Chain.Genesis.configGenesisData bCfg)
, " /= ", textShow (Shelley.Spec.sgSystemStart $ scConfig sCfg)
]
| otherwise ->
let
topLevelConfig = Consensus.pInfoConfig (mkProtocolInfoCardano genCfg)
in
Right $ Env
{ envLedgerConfig = Consensus.topLevelConfigLedger topLevelConfig
, envProtocolConfig = Consensus.topLevelConfigProtocol topLevelConfig
}
readNetworkConfig :: NetworkConfigFile -> ExceptT Text IO NodeConfig
readNetworkConfig (NetworkConfigFile ncf) = do
ncfg <- (except . parseNodeConfig) =<< readByteString ncf "node"
return ncfg
{ ncByronGenesisFile = adjustGenesisFilePath (mkAdjustPath ncf) (ncByronGenesisFile ncfg)
, ncShelleyGenesisFile = adjustGenesisFilePath (mkAdjustPath ncf) (ncShelleyGenesisFile ncfg)
, ncAlonzoGenesisFile = adjustGenesisFilePath (mkAdjustPath ncf) (ncAlonzoGenesisFile ncfg)
}
data NodeConfig = NodeConfig
{ ncPBftSignatureThreshold :: !(Maybe Double)
, ncByronGenesisFile :: !GenesisFile
, ncByronGenesisHash :: !GenesisHashByron
, ncShelleyGenesisFile :: !GenesisFile
, ncShelleyGenesisHash :: !GenesisHashShelley
, ncAlonzoGenesisFile :: !GenesisFile
, ncAlonzoGenesisHash :: !GenesisHashAlonzo
, ncRequiresNetworkMagic :: !Cardano.Crypto.RequiresNetworkMagic
, ncByronSoftwareVersion :: !Cardano.Chain.Update.SoftwareVersion
, ncByronProtocolVersion :: !Cardano.Chain.Update.ProtocolVersion
-- Per-era parameters for the hardfok transitions:
, ncByronToShelley :: !(Consensus.ProtocolTransitionParamsShelleyBased
Shelley.StandardShelley)
, ncShelleyToAllegra :: !(Consensus.ProtocolTransitionParamsShelleyBased
Shelley.StandardAllegra)
, ncAllegraToMary :: !(Consensus.ProtocolTransitionParamsShelleyBased
Shelley.StandardMary)
, ncMaryToAlonzo :: !Consensus.TriggerHardFork
, ncAlonzoToBabbage :: !Consensus.TriggerHardFork
}
instance FromJSON NodeConfig where
parseJSON v =
Aeson.withObject "NodeConfig" parse v
where
parse :: Object -> Parser NodeConfig
parse o =
NodeConfig
<$> o .:? "PBftSignatureThreshold"
<*> fmap GenesisFile (o .: "ByronGenesisFile")
<*> fmap GenesisHashByron (o .: "ByronGenesisHash")
<*> fmap GenesisFile (o .: "ShelleyGenesisFile")
<*> fmap GenesisHashShelley (o .: "ShelleyGenesisHash")
<*> fmap GenesisFile (o .: "AlonzoGenesisFile")
<*> fmap GenesisHashAlonzo (o .: "AlonzoGenesisHash")
<*> o .: "RequiresNetworkMagic"
<*> parseByronSoftwareVersion o
<*> parseByronProtocolVersion o
<*> (Consensus.ProtocolTransitionParamsShelleyBased ()
<$> parseShelleyHardForkEpoch o)
<*> (Consensus.ProtocolTransitionParamsShelleyBased ()
<$> parseAllegraHardForkEpoch o)
<*> (Consensus.ProtocolTransitionParamsShelleyBased ()
<$> parseMaryHardForkEpoch o)
<*> parseAlonzoHardForkEpoch o
<*> parseBabbageHardForkEpoch o
parseByronProtocolVersion :: Object -> Parser Cardano.Chain.Update.ProtocolVersion
parseByronProtocolVersion o =
Cardano.Chain.Update.ProtocolVersion
<$> o .: "LastKnownBlockVersion-Major"
<*> o .: "LastKnownBlockVersion-Minor"
<*> o .: "LastKnownBlockVersion-Alt"
parseByronSoftwareVersion :: Object -> Parser Cardano.Chain.Update.SoftwareVersion
parseByronSoftwareVersion o =
Cardano.Chain.Update.SoftwareVersion
<$> fmap Cardano.Chain.Update.ApplicationName (o .: "ApplicationName")
<*> o .: "ApplicationVersion"
parseShelleyHardForkEpoch :: Object -> Parser Consensus.TriggerHardFork
parseShelleyHardForkEpoch o =
asum
[ Consensus.TriggerHardForkAtEpoch <$> o .: "TestShelleyHardForkAtEpoch"
, pure $ Consensus.TriggerHardForkAtVersion 2 -- Mainnet default
]
parseAllegraHardForkEpoch :: Object -> Parser Consensus.TriggerHardFork
parseAllegraHardForkEpoch o =
asum
[ Consensus.TriggerHardForkAtEpoch <$> o .: "TestAllegraHardForkAtEpoch"
, pure $ Consensus.TriggerHardForkAtVersion 3 -- Mainnet default
]
parseMaryHardForkEpoch :: Object -> Parser Consensus.TriggerHardFork
parseMaryHardForkEpoch o =
asum
[ Consensus.TriggerHardForkAtEpoch <$> o .: "TestMaryHardForkAtEpoch"
, pure $ Consensus.TriggerHardForkAtVersion 4 -- Mainnet default
]
parseAlonzoHardForkEpoch :: Object -> Parser Consensus.TriggerHardFork
parseAlonzoHardForkEpoch o =
asum
[ Consensus.TriggerHardForkAtEpoch <$> o .: "TestAlonzoHardForkAtEpoch"
, pure $ Consensus.TriggerHardForkAtVersion 5 -- Mainnet default
]
parseBabbageHardForkEpoch :: Object -> Parser Consensus.TriggerHardFork
parseBabbageHardForkEpoch o =
asum
[ Consensus.TriggerHardForkAtEpoch <$> o .: "TestBabbageHardForkAtEpoch"
, pure $ Consensus.TriggerHardForkAtVersion 7 -- Mainnet default
]
parseNodeConfig :: ByteString -> Either Text NodeConfig
parseNodeConfig bs =
case Yaml.decodeEither' bs of
Left err -> Left $ "Error parsing node config: " <> textShow err
Right nc -> Right nc
adjustGenesisFilePath :: (FilePath -> FilePath) -> GenesisFile -> GenesisFile
adjustGenesisFilePath f (GenesisFile p) = GenesisFile (f p)
mkAdjustPath :: FilePath -> (FilePath -> FilePath)
mkAdjustPath nodeConfigFilePath fp = takeDirectory nodeConfigFilePath </> fp
readByteString :: FilePath -> Text -> ExceptT Text IO ByteString
readByteString fp cfgType = ExceptT $
catch (Right <$> BS.readFile fp) $ \(_ :: IOException) ->
return $ Left $ mconcat
[ "Cannot read the ", cfgType, " configuration file at : ", Text.pack fp ]
initLedgerStateVar :: GenesisConfig -> LedgerState
initLedgerStateVar genesisConfig = LedgerState
{ clsState = Ledger.ledgerState $ Consensus.pInfoInitLedger protocolInfo
}
where
protocolInfo = mkProtocolInfoCardano genesisConfig
newtype LedgerState = LedgerState
{ clsState :: Ledger.LedgerState
(HFC.HardForkBlock
(Consensus.CardanoEras Consensus.StandardCrypto))
}
type LedgerStateEvents = (LedgerState, [LedgerEvent])
toLedgerStateEvents ::
LedgerResult
( Shelley.LedgerState
(HFC.HardForkBlock (Consensus.CardanoEras Shelley.StandardCrypto))
)
( Shelley.LedgerState
(HFC.HardForkBlock (Consensus.CardanoEras Shelley.StandardCrypto))
) ->
LedgerStateEvents
toLedgerStateEvents lr = (ledgerState, ledgerEvents)
where
ledgerState = LedgerState (lrResult lr)
ledgerEvents = mapMaybe (toLedgerEvent
. WrapLedgerEvent @(HFC.HardForkBlock (Consensus.CardanoEras Shelley.StandardCrypto)))
$ lrEvents lr
-- Usually only one constructor, but may have two when we are preparing for a HFC event.
data GenesisConfig
= GenesisCardano
!NodeConfig
!Cardano.Chain.Genesis.Config
!ShelleyConfig
!AlonzoGenesis
data ShelleyConfig = ShelleyConfig
{ scConfig :: !(Shelley.Spec.ShelleyGenesis Shelley.StandardShelley)
, scGenesisHash :: !GenesisHashShelley
}
newtype GenesisFile = GenesisFile
{ unGenesisFile :: FilePath
} deriving Show
newtype GenesisHashByron = GenesisHashByron
{ unGenesisHashByron :: Text
} deriving newtype (Eq, Show)
newtype GenesisHashShelley = GenesisHashShelley
{ unGenesisHashShelley :: Cardano.Crypto.Hash.Class.Hash Cardano.Crypto.Hash.Blake2b.Blake2b_256 ByteString
} deriving newtype (Eq, Show)
newtype GenesisHashAlonzo = GenesisHashAlonzo
{ unGenesisHashAlonzo :: Cardano.Crypto.Hash.Class.Hash Cardano.Crypto.Hash.Blake2b.Blake2b_256 ByteString
} deriving newtype (Eq, Show)
newtype LedgerStateDir = LedgerStateDir
{ unLedgerStateDir :: FilePath
} deriving Show
newtype NetworkName = NetworkName
{ unNetworkName :: Text
} deriving Show
newtype NetworkConfigFile = NetworkConfigFile
{ unNetworkConfigFile :: FilePath
} deriving Show
newtype SocketPath = SocketPath
{ unSocketPath :: FilePath
} deriving Show
mkProtocolInfoCardano ::
GenesisConfig ->
Consensus.ProtocolInfo
IO
(HFC.HardForkBlock
(Consensus.CardanoEras Consensus.StandardCrypto))
mkProtocolInfoCardano (GenesisCardano dnc byronGenesis shelleyGenesis alonzoGenesis)
= Consensus.protocolInfoCardano
Consensus.ProtocolParamsByron
{ Consensus.byronGenesis = byronGenesis
, Consensus.byronPbftSignatureThreshold = Consensus.PBftSignatureThreshold <$> ncPBftSignatureThreshold dnc
, Consensus.byronProtocolVersion = ncByronProtocolVersion dnc
, Consensus.byronSoftwareVersion = ncByronSoftwareVersion dnc
, Consensus.byronLeaderCredentials = Nothing
, Consensus.byronMaxTxCapacityOverrides = TxLimits.mkOverrides TxLimits.noOverridesMeasure
}
Consensus.ProtocolParamsShelleyBased
{ Consensus.shelleyBasedGenesis = scConfig shelleyGenesis
, Consensus.shelleyBasedInitialNonce = shelleyPraosNonce shelleyGenesis
, Consensus.shelleyBasedLeaderCredentials = []
}
Consensus.ProtocolParamsShelley
{ Consensus.shelleyProtVer = shelleyProtVer dnc
, Consensus.shelleyMaxTxCapacityOverrides = TxLimits.mkOverrides TxLimits.noOverridesMeasure
}
Consensus.ProtocolParamsAllegra
{ Consensus.allegraProtVer = shelleyProtVer dnc
, Consensus.allegraMaxTxCapacityOverrides = TxLimits.mkOverrides TxLimits.noOverridesMeasure
}
Consensus.ProtocolParamsMary
{ Consensus.maryProtVer = shelleyProtVer dnc
, Consensus.maryMaxTxCapacityOverrides = TxLimits.mkOverrides TxLimits.noOverridesMeasure
}
Consensus.ProtocolParamsAlonzo
{ Consensus.alonzoProtVer = shelleyProtVer dnc
, Consensus.alonzoMaxTxCapacityOverrides = TxLimits.mkOverrides TxLimits.noOverridesMeasure
}
Consensus.ProtocolParamsBabbage
{ Consensus.babbageProtVer = shelleyProtVer dnc
, Consensus.babbageMaxTxCapacityOverrides = TxLimits.mkOverrides TxLimits.noOverridesMeasure
}
(ncByronToShelley dnc)
(ncShelleyToAllegra dnc)
(ncAllegraToMary dnc)
(Consensus.ProtocolTransitionParamsShelleyBased alonzoGenesis (ncMaryToAlonzo dnc))
(Consensus.ProtocolTransitionParamsShelleyBased alonzoGenesis (ncAlonzoToBabbage dnc))
shelleyPraosNonce :: ShelleyConfig -> Shelley.Spec.Nonce
shelleyPraosNonce sCfg = Shelley.Spec.Nonce (Cardano.Crypto.Hash.Class.castHash . unGenesisHashShelley $ scGenesisHash sCfg)
shelleyProtVer :: NodeConfig -> Shelley.Spec.ProtVer
shelleyProtVer dnc =
let bver = ncByronProtocolVersion dnc in
Shelley.Spec.ProtVer
(fromIntegral $ Cardano.Chain.Update.pvMajor bver)
(fromIntegral $ Cardano.Chain.Update.pvMinor bver)
readCardanoGenesisConfig
:: NodeConfig
-> ExceptT GenesisConfigError IO GenesisConfig
readCardanoGenesisConfig enc =
GenesisCardano enc
<$> readByronGenesisConfig enc
<*> readShelleyGenesisConfig enc
<*> readAlonzoGenesisConfig enc
data GenesisConfigError
= NEError !Text
| NEByronConfig !FilePath !Cardano.Chain.Genesis.ConfigurationError
| NEShelleyConfig !FilePath !Text