-
Notifications
You must be signed in to change notification settings - Fork 721
/
ProtocolParameters.hs
1828 lines (1659 loc) · 79.8 KB
/
ProtocolParameters.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 DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-- | The various Cardano protocol parameters, including:
--
-- * the current values of updatable protocol parameters: 'ProtocolParameters'
-- * updates to protocol parameters: 'ProtocolParametersUpdate'
-- * update proposals that can be embedded in transactions: 'UpdateProposal'
-- * parameters fixed in the genesis file: 'GenesisParameters'
--
module Cardano.Api.ProtocolParameters (
-- * The updatable protocol parameters
ProtocolParameters(..),
checkProtocolParameters,
ProtocolParametersError(..),
EpochNo,
-- * Updates to the protocol parameters
ProtocolParametersUpdate(..),
-- * PraosNonce
PraosNonce,
makePraosNonce,
-- * Execution units, prices and cost models,
ExecutionUnits(..),
ExecutionUnitPrices(..),
CostModel(..),
validateCostModel,
fromAlonzoCostModels,
-- * Update proposals to change the protocol parameters
UpdateProposal(..),
makeShelleyUpdateProposal,
-- * Internal conversion functions
toLedgerNonce,
toLedgerUpdate,
fromLedgerUpdate,
toLedgerProposedPPUpdates,
fromLedgerProposedPPUpdates,
toLedgerPParams,
fromLedgerPParams,
fromShelleyPParams,
toAlonzoPrices,
fromAlonzoPrices,
toAlonzoScriptLanguage,
fromAlonzoScriptLanguage,
toAlonzoCostModel,
fromAlonzoCostModel,
toAlonzoCostModels,
toAlonzoPParams,
toBabbagePParams,
-- * Data family instances
AsType(..)
) where
import Prelude
import Control.Monad
import Data.Aeson (FromJSON (..), ToJSON (..), object, withObject, (.!=), (.:), (.:?),
(.=))
import Data.Bifunctor (bimap, first)
import Data.ByteString (ByteString)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe, isJust, isNothing)
import Data.String (IsString)
import Data.Text (Text)
import GHC.Generics
import Numeric.Natural
import Cardano.Api.Json (toRationalJSON)
import qualified Cardano.Binary as CBOR
import qualified Cardano.Crypto.Hash.Class as Crypto
import Cardano.Slotting.Slot (EpochNo)
import Cardano.Ledger.BaseTypes (strictMaybeToMaybe)
import qualified Cardano.Ledger.BaseTypes as Ledger
import qualified Cardano.Ledger.Core as Ledger
import Cardano.Ledger.Crypto (StandardCrypto)
import qualified Cardano.Ledger.Era as Ledger
import qualified Cardano.Ledger.Keys as Ledger
import qualified Cardano.Ledger.Shelley.PParams as Ledger (ProposedPPUpdates (..), Update (..))
-- Some of the things from Cardano.Ledger.Shelley.PParams are generic across all
-- eras, and some are specific to the Shelley era (and other pre-Alonzo eras).
-- So we import in twice under different names.
import qualified Cardano.Ledger.Shelley.PParams as Shelley (PParams, PParams' (..), PParamsUpdate)
import qualified Cardano.Ledger.Alonzo.Language as Alonzo
import qualified Cardano.Ledger.Alonzo.PParams as Alonzo
import qualified Cardano.Ledger.Alonzo.Scripts as Alonzo
import qualified Cardano.Ledger.Babbage.PParams as Babbage
import Cardano.Ledger.Babbage.Translation (coinsPerUTxOWordToCoinsPerUTxOByte)
import Text.PrettyBy.Default (display)
import Cardano.Api.Address
import Cardano.Api.Eras
import Cardano.Api.Error
import Cardano.Api.HasTypeProxy
import Cardano.Api.Hash
import Cardano.Api.KeysByron
import Cardano.Api.KeysShelley
import Cardano.Api.Script
import Cardano.Api.SerialiseCBOR
import Cardano.Api.SerialiseRaw
import Cardano.Api.SerialiseTextEnvelope
import Cardano.Api.SerialiseUsing
import Cardano.Api.StakePoolMetadata
import Cardano.Api.TxMetadata
import Cardano.Api.Utils
import Cardano.Api.Value
-- | The values of the set of /updatable/ protocol parameters. At any
-- particular point on the chain there is a current set of parameters in use.
--
-- These parameters can be updated (at epoch boundaries) via an
-- 'UpdateProposal', which contains a 'ProtocolParametersUpdate'.
--
-- The 'ProtocolParametersUpdate' is essentially a diff for the
-- 'ProtocolParameters'.
--
-- There are also parameters fixed in the Genesis file. See 'GenesisParameters'.
--
data ProtocolParameters =
ProtocolParameters {
-- | Protocol version, major and minor. Updating the major version is
-- used to trigger hard forks.
-- (Major , Minor )
protocolParamProtocolVersion :: (Natural, Natural),
-- | The decentralization parameter. This is fraction of slots that
-- belong to the BFT overlay schedule, rather than the Praos schedule.
-- So 1 means fully centralised, while 0 means fully decentralised.
--
-- This is the \"d\" parameter from the design document.
--
-- /Deprecated in Babbage/
protocolParamDecentralization :: Maybe Rational,
-- | Extra entropy for the Praos per-epoch nonce.
--
-- This can be used to add extra entropy during the decentralisation
-- process. If the extra entropy can be demonstrated to be generated
-- randomly then this method can be used to show that the initial
-- federated operators did not subtly bias the initial schedule so that
-- they retain undue influence after decentralisation.
--
protocolParamExtraPraosEntropy :: Maybe PraosNonce,
-- | The maximum permitted size of a block header.
--
-- This must be at least as big as the largest legitimate block headers
-- but should not be too much larger, to help prevent DoS attacks.
--
-- Caution: setting this to be smaller than legitimate block headers is
-- a sure way to brick the system!
--
protocolParamMaxBlockHeaderSize :: Natural,
-- | The maximum permitted size of the block body (that is, the block
-- payload, without the block header).
--
-- This should be picked with the Praos network delta security parameter
-- in mind. Making this too large can severely weaken the Praos
-- consensus properties.
--
-- Caution: setting this to be smaller than a transaction that can
-- change the protocol parameters is a sure way to brick the system!
--
protocolParamMaxBlockBodySize :: Natural,
-- | The maximum permitted size of a transaction.
--
-- Typically this should not be too high a fraction of the block size,
-- otherwise wastage from block fragmentation becomes a problem, and
-- the current implementation does not use any sophisticated box packing
-- algorithm.
--
protocolParamMaxTxSize :: Natural,
-- | The constant factor for the minimum fee calculation.
--
protocolParamTxFeeFixed :: Natural,
-- | The linear factor for the minimum fee calculation.
--
protocolParamTxFeePerByte :: Natural,
-- | The minimum permitted value for new UTxO entries, ie for
-- transaction outputs.
--
protocolParamMinUTxOValue :: Maybe Lovelace,
-- | The deposit required to register a stake address.
--
protocolParamStakeAddressDeposit :: Lovelace,
-- | The deposit required to register a stake pool.
--
protocolParamStakePoolDeposit :: Lovelace,
-- | The minimum value that stake pools are permitted to declare for
-- their cost parameter.
--
protocolParamMinPoolCost :: Lovelace,
-- | The maximum number of epochs into the future that stake pools
-- are permitted to schedule a retirement.
--
protocolParamPoolRetireMaxEpoch :: EpochNo,
-- | The equilibrium target number of stake pools.
--
-- This is the \"k\" incentives parameter from the design document.
--
protocolParamStakePoolTargetNum :: Natural,
-- | The influence of the pledge in stake pool rewards.
--
-- This is the \"a_0\" incentives parameter from the design document.
--
protocolParamPoolPledgeInfluence :: Rational,
-- | The monetary expansion rate. This determines the fraction of the
-- reserves that are added to the fee pot each epoch.
--
-- This is the \"rho\" incentives parameter from the design document.
--
protocolParamMonetaryExpansion :: Rational,
-- | The fraction of the fee pot each epoch that goes to the treasury.
--
-- This is the \"tau\" incentives parameter from the design document.
--
protocolParamTreasuryCut :: Rational,
-- | Cost in ada per word of UTxO storage.
--
-- /Introduced in Alonzo/
protocolParamUTxOCostPerWord :: Maybe Lovelace,
-- | Cost models for script languages that use them.
--
-- /Introduced in Alonzo/
protocolParamCostModels :: Map AnyPlutusScriptVersion CostModel,
-- | Price of execution units for script languages that use them.
--
-- /Introduced in Alonzo/
protocolParamPrices :: Maybe ExecutionUnitPrices,
-- | Max total script execution resources units allowed per tx
--
-- /Introduced in Alonzo/
protocolParamMaxTxExUnits :: Maybe ExecutionUnits,
-- | Max total script execution resources units allowed per block
--
-- /Introduced in Alonzo/
protocolParamMaxBlockExUnits :: Maybe ExecutionUnits,
-- | Max size of a Value in a tx output.
--
-- /Introduced in Alonzo/
protocolParamMaxValueSize :: Maybe Natural,
-- | The percentage of the script contribution to the txfee that must be
-- provided as collateral inputs when including Plutus scripts.
--
-- /Introduced in Alonzo/
protocolParamCollateralPercent :: Maybe Natural,
-- | The maximum number of collateral inputs allowed in a transaction.
--
-- /Introduced in Alonzo/
protocolParamMaxCollateralInputs :: Maybe Natural
}
deriving (Eq, Generic, Show)
instance FromJSON ProtocolParameters where
parseJSON =
withObject "ProtocolParameters" $ \o -> do
v <- o .: "protocolVersion"
ProtocolParameters
<$> ((,) <$> v .: "major" <*> v .: "minor")
<*> o .:? "decentralization"
<*> o .: "extraPraosEntropy"
<*> o .: "maxBlockHeaderSize"
<*> o .: "maxBlockBodySize"
<*> o .: "maxTxSize"
<*> o .: "txFeeFixed"
<*> o .: "txFeePerByte"
<*> o .: "minUTxOValue"
<*> o .: "stakeAddressDeposit"
<*> o .: "stakePoolDeposit"
<*> o .: "minPoolCost"
<*> o .: "poolRetireMaxEpoch"
<*> o .: "stakePoolTargetNum"
<*> o .: "poolPledgeInfluence"
<*> o .: "monetaryExpansion"
<*> o .: "treasuryCut"
<*> o .:? "utxoCostPerWord"
<*> o .:? "costModels" .!= Map.empty
<*> o .:? "executionUnitPrices"
<*> o .:? "maxTxExecutionUnits"
<*> o .:? "maxBlockExecutionUnits"
<*> o .:? "maxValueSize"
<*> o .:? "collateralPercentage"
<*> o .:? "maxCollateralInputs"
instance ToJSON ProtocolParameters where
toJSON ProtocolParameters{..} =
object
[ "extraPraosEntropy" .= protocolParamExtraPraosEntropy
, "stakePoolTargetNum" .= protocolParamStakePoolTargetNum
, "minUTxOValue" .= protocolParamMinUTxOValue
, "poolRetireMaxEpoch" .= protocolParamPoolRetireMaxEpoch
, "decentralization" .= (toRationalJSON <$> protocolParamDecentralization)
, "stakePoolDeposit" .= protocolParamStakePoolDeposit
, "maxBlockHeaderSize" .= protocolParamMaxBlockHeaderSize
, "maxBlockBodySize" .= protocolParamMaxBlockBodySize
, "maxTxSize" .= protocolParamMaxTxSize
, "treasuryCut" .= toRationalJSON protocolParamTreasuryCut
, "minPoolCost" .= protocolParamMinPoolCost
, "monetaryExpansion" .= toRationalJSON protocolParamMonetaryExpansion
, "stakeAddressDeposit" .= protocolParamStakeAddressDeposit
, "poolPledgeInfluence" .= toRationalJSON protocolParamPoolPledgeInfluence
, "protocolVersion" .= let (major, minor) = protocolParamProtocolVersion
in object ["major" .= major, "minor" .= minor]
, "txFeeFixed" .= protocolParamTxFeeFixed
, "txFeePerByte" .= protocolParamTxFeePerByte
-- Alonzo era:
, "utxoCostPerWord" .= protocolParamUTxOCostPerWord
, "costModels" .= protocolParamCostModels
, "executionUnitPrices" .= protocolParamPrices
, "maxTxExecutionUnits" .= protocolParamMaxTxExUnits
, "maxBlockExecutionUnits" .= protocolParamMaxBlockExUnits
, "maxValueSize" .= protocolParamMaxValueSize
, "collateralPercentage" .= protocolParamCollateralPercent
, "maxCollateralInputs" .= protocolParamMaxCollateralInputs
]
-- ----------------------------------------------------------------------------
-- Updates to the protocol parameters
--
-- | The representation of a change in the 'ProtocolParameters'.
--
data ProtocolParametersUpdate =
ProtocolParametersUpdate {
-- | Protocol version, major and minor. Updating the major version is
-- used to trigger hard forks.
--
protocolUpdateProtocolVersion :: Maybe (Natural, Natural),
-- | The decentralization parameter. This is fraction of slots that
-- belong to the BFT overlay schedule, rather than the Praos schedule.
-- So 1 means fully centralised, while 0 means fully decentralised.
--
-- This is the \"d\" parameter from the design document.
--
protocolUpdateDecentralization :: Maybe Rational,
-- | Extra entropy for the Praos per-epoch nonce.
--
-- This can be used to add extra entropy during the decentralisation
-- process. If the extra entropy can be demonstrated to be generated
-- randomly then this method can be used to show that the initial
-- federated operators did not subtly bias the initial schedule so that
-- they retain undue influence after decentralisation.
--
protocolUpdateExtraPraosEntropy :: Maybe (Maybe PraosNonce),
-- | The maximum permitted size of a block header.
--
-- This must be at least as big as the largest legitimate block headers
-- but should not be too much larger, to help prevent DoS attacks.
--
-- Caution: setting this to be smaller than legitimate block headers is
-- a sure way to brick the system!
--
protocolUpdateMaxBlockHeaderSize :: Maybe Natural,
-- | The maximum permitted size of the block body (that is, the block
-- payload, without the block header).
--
-- This should be picked with the Praos network delta security parameter
-- in mind. Making this too large can severely weaken the Praos
-- consensus properties.
--
-- Caution: setting this to be smaller than a transaction that can
-- change the protocol parameters is a sure way to brick the system!
--
protocolUpdateMaxBlockBodySize :: Maybe Natural,
-- | The maximum permitted size of a transaction.
--
-- Typically this should not be too high a fraction of the block size,
-- otherwise wastage from block fragmentation becomes a problem, and
-- the current implementation does not use any sophisticated box packing
-- algorithm.
--
protocolUpdateMaxTxSize :: Maybe Natural,
-- | The constant factor for the minimum fee calculation.
--
protocolUpdateTxFeeFixed :: Maybe Natural,
-- | The linear factor for the minimum fee calculation.
--
protocolUpdateTxFeePerByte :: Maybe Natural,
-- | The minimum permitted value for new UTxO entries, ie for
-- transaction outputs.
--
protocolUpdateMinUTxOValue :: Maybe Lovelace,
-- | The deposit required to register a stake address.
--
protocolUpdateStakeAddressDeposit :: Maybe Lovelace,
-- | The deposit required to register a stake pool.
--
protocolUpdateStakePoolDeposit :: Maybe Lovelace,
-- | The minimum value that stake pools are permitted to declare for
-- their cost parameter.
--
protocolUpdateMinPoolCost :: Maybe Lovelace,
-- | The maximum number of epochs into the future that stake pools
-- are permitted to schedule a retirement.
--
protocolUpdatePoolRetireMaxEpoch :: Maybe EpochNo,
-- | The equilibrium target number of stake pools.
--
-- This is the \"k\" incentives parameter from the design document.
--
protocolUpdateStakePoolTargetNum :: Maybe Natural,
-- | The influence of the pledge in stake pool rewards.
--
-- This is the \"a_0\" incentives parameter from the design document.
--
protocolUpdatePoolPledgeInfluence :: Maybe Rational,
-- | The monetary expansion rate. This determines the fraction of the
-- reserves that are added to the fee pot each epoch.
--
-- This is the \"rho\" incentives parameter from the design document.
--
protocolUpdateMonetaryExpansion :: Maybe Rational,
-- | The fraction of the fee pot each epoch that goes to the treasury.
--
-- This is the \"tau\" incentives parameter from the design document.
--
protocolUpdateTreasuryCut :: Maybe Rational,
-- Introduced in Alonzo
-- | Cost in ada per word of UTxO storage.
--
-- /Introduced in Alonzo/
protocolUpdateUTxOCostPerWord :: Maybe Lovelace,
-- | Cost models for script languages that use them.
--
-- /Introduced in Alonzo/
protocolUpdateCostModels :: Map AnyPlutusScriptVersion CostModel,
-- | Price of execution units for script languages that use them.
--
-- /Introduced in Alonzo/
protocolUpdatePrices :: Maybe ExecutionUnitPrices,
-- | Max total script execution resources units allowed per tx
--
-- /Introduced in Alonzo/
protocolUpdateMaxTxExUnits :: Maybe ExecutionUnits,
-- | Max total script execution resources units allowed per block
--
-- /Introduced in Alonzo/
protocolUpdateMaxBlockExUnits :: Maybe ExecutionUnits,
-- | Max size of a 'Value' in a tx output.
--
-- /Introduced in Alonzo/
protocolUpdateMaxValueSize :: Maybe Natural,
-- | The percentage of the script contribution to the txfee that must be
-- provided as collateral inputs when including Plutus scripts.
--
-- /Introduced in Alonzo/
protocolUpdateCollateralPercent :: Maybe Natural,
-- | The maximum number of collateral inputs allowed in a transaction.
--
-- /Introduced in Alonzo/
protocolUpdateMaxCollateralInputs :: Maybe Natural
}
deriving (Eq, Show)
instance Semigroup ProtocolParametersUpdate where
ppu1 <> ppu2 =
ProtocolParametersUpdate {
protocolUpdateProtocolVersion = merge protocolUpdateProtocolVersion
, protocolUpdateDecentralization = merge protocolUpdateDecentralization
, protocolUpdateExtraPraosEntropy = merge protocolUpdateExtraPraosEntropy
, protocolUpdateMaxBlockHeaderSize = merge protocolUpdateMaxBlockHeaderSize
, protocolUpdateMaxBlockBodySize = merge protocolUpdateMaxBlockBodySize
, protocolUpdateMaxTxSize = merge protocolUpdateMaxTxSize
, protocolUpdateTxFeeFixed = merge protocolUpdateTxFeeFixed
, protocolUpdateTxFeePerByte = merge protocolUpdateTxFeePerByte
, protocolUpdateMinUTxOValue = merge protocolUpdateMinUTxOValue
, protocolUpdateStakeAddressDeposit = merge protocolUpdateStakeAddressDeposit
, protocolUpdateStakePoolDeposit = merge protocolUpdateStakePoolDeposit
, protocolUpdateMinPoolCost = merge protocolUpdateMinPoolCost
, protocolUpdatePoolRetireMaxEpoch = merge protocolUpdatePoolRetireMaxEpoch
, protocolUpdateStakePoolTargetNum = merge protocolUpdateStakePoolTargetNum
, protocolUpdatePoolPledgeInfluence = merge protocolUpdatePoolPledgeInfluence
, protocolUpdateMonetaryExpansion = merge protocolUpdateMonetaryExpansion
, protocolUpdateTreasuryCut = merge protocolUpdateTreasuryCut
-- Introduced in Alonzo below.
, protocolUpdateUTxOCostPerWord = merge protocolUpdateUTxOCostPerWord
, protocolUpdateCostModels = mergeMap protocolUpdateCostModels
, protocolUpdatePrices = merge protocolUpdatePrices
, protocolUpdateMaxTxExUnits = merge protocolUpdateMaxTxExUnits
, protocolUpdateMaxBlockExUnits = merge protocolUpdateMaxBlockExUnits
, protocolUpdateMaxValueSize = merge protocolUpdateMaxValueSize
, protocolUpdateCollateralPercent = merge protocolUpdateCollateralPercent
, protocolUpdateMaxCollateralInputs = merge protocolUpdateMaxCollateralInputs
}
where
-- prefer the right hand side:
merge :: (ProtocolParametersUpdate -> Maybe a) -> Maybe a
merge f = f ppu2 `mplus` f ppu1
-- prefer the right hand side:
mergeMap :: Ord k => (ProtocolParametersUpdate -> Map k a) -> Map k a
mergeMap f = f ppu2 `Map.union` f ppu1
instance Monoid ProtocolParametersUpdate where
mempty =
ProtocolParametersUpdate {
protocolUpdateProtocolVersion = Nothing
, protocolUpdateDecentralization = Nothing
, protocolUpdateExtraPraosEntropy = Nothing
, protocolUpdateMaxBlockHeaderSize = Nothing
, protocolUpdateMaxBlockBodySize = Nothing
, protocolUpdateMaxTxSize = Nothing
, protocolUpdateTxFeeFixed = Nothing
, protocolUpdateTxFeePerByte = Nothing
, protocolUpdateMinUTxOValue = Nothing
, protocolUpdateStakeAddressDeposit = Nothing
, protocolUpdateStakePoolDeposit = Nothing
, protocolUpdateMinPoolCost = Nothing
, protocolUpdatePoolRetireMaxEpoch = Nothing
, protocolUpdateStakePoolTargetNum = Nothing
, protocolUpdatePoolPledgeInfluence = Nothing
, protocolUpdateMonetaryExpansion = Nothing
, protocolUpdateTreasuryCut = Nothing
, protocolUpdateUTxOCostPerWord = Nothing
, protocolUpdateCostModels = mempty
, protocolUpdatePrices = Nothing
, protocolUpdateMaxTxExUnits = Nothing
, protocolUpdateMaxBlockExUnits = Nothing
, protocolUpdateMaxValueSize = Nothing
, protocolUpdateCollateralPercent = Nothing
, protocolUpdateMaxCollateralInputs = Nothing
}
instance ToCBOR ProtocolParametersUpdate where
toCBOR ProtocolParametersUpdate{..} =
CBOR.encodeListLen 25
<> toCBOR protocolUpdateProtocolVersion
<> toCBOR protocolUpdateDecentralization
<> toCBOR protocolUpdateExtraPraosEntropy
<> toCBOR protocolUpdateMaxBlockHeaderSize
<> toCBOR protocolUpdateMaxBlockBodySize
<> toCBOR protocolUpdateMaxTxSize
<> toCBOR protocolUpdateTxFeeFixed
<> toCBOR protocolUpdateTxFeePerByte
<> toCBOR protocolUpdateMinUTxOValue
<> toCBOR protocolUpdateStakeAddressDeposit
<> toCBOR protocolUpdateStakePoolDeposit
<> toCBOR protocolUpdateMinPoolCost
<> toCBOR protocolUpdatePoolRetireMaxEpoch
<> toCBOR protocolUpdateStakePoolTargetNum
<> toCBOR protocolUpdatePoolPledgeInfluence
<> toCBOR protocolUpdateMonetaryExpansion
<> toCBOR protocolUpdateTreasuryCut
<> toCBOR protocolUpdateUTxOCostPerWord
<> toCBOR protocolUpdateCostModels
<> toCBOR protocolUpdatePrices
<> toCBOR protocolUpdateMaxTxExUnits
<> toCBOR protocolUpdateMaxBlockExUnits
<> toCBOR protocolUpdateMaxValueSize
<> toCBOR protocolUpdateCollateralPercent
<> toCBOR protocolUpdateMaxCollateralInputs
instance FromCBOR ProtocolParametersUpdate where
fromCBOR = do
CBOR.enforceSize "ProtocolParametersUpdate" 25
ProtocolParametersUpdate
<$> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
<*> fromCBOR
-- ----------------------------------------------------------------------------
-- Praos nonce
--
newtype PraosNonce = PraosNonce (Ledger.Hash StandardCrypto ByteString)
deriving stock (Eq, Ord, Generic)
deriving (Show, IsString) via UsingRawBytesHex PraosNonce
deriving (ToJSON, FromJSON) via UsingRawBytesHex PraosNonce
deriving (ToCBOR, FromCBOR) via UsingRawBytes PraosNonce
instance HasTypeProxy PraosNonce where
data AsType PraosNonce = AsPraosNonce
proxyToAsType _ = AsPraosNonce
instance SerialiseAsRawBytes PraosNonce where
serialiseToRawBytes (PraosNonce h) =
Crypto.hashToBytes h
deserialiseFromRawBytes AsPraosNonce bs =
PraosNonce <$> Crypto.hashFromBytes bs
makePraosNonce :: ByteString -> PraosNonce
makePraosNonce = PraosNonce . Crypto.hashWith id
toLedgerNonce :: Maybe PraosNonce -> Ledger.Nonce
toLedgerNonce Nothing = Ledger.NeutralNonce
toLedgerNonce (Just (PraosNonce h)) = Ledger.Nonce (Crypto.castHash h)
fromLedgerNonce :: Ledger.Nonce -> Maybe PraosNonce
fromLedgerNonce Ledger.NeutralNonce = Nothing
fromLedgerNonce (Ledger.Nonce h) = Just (PraosNonce (Crypto.castHash h))
-- ----------------------------------------------------------------------------
-- Script execution unit prices and cost models
--
-- | The prices for 'ExecutionUnits' as a fraction of a 'Lovelace'.
--
-- These are used to determine the fee for the use of a script within a
-- transaction, based on the 'ExecutionUnits' needed by the use of the script.
--
data ExecutionUnitPrices =
ExecutionUnitPrices {
priceExecutionSteps :: Rational,
priceExecutionMemory :: Rational
}
deriving (Eq, Show)
instance ToCBOR ExecutionUnitPrices where
toCBOR ExecutionUnitPrices{priceExecutionSteps, priceExecutionMemory} =
CBOR.encodeListLen 2
<> toCBOR priceExecutionSteps
<> toCBOR priceExecutionMemory
instance FromCBOR ExecutionUnitPrices where
fromCBOR = do
CBOR.enforceSize "ExecutionUnitPrices" 2
ExecutionUnitPrices
<$> fromCBOR
<*> fromCBOR
instance ToJSON ExecutionUnitPrices where
toJSON ExecutionUnitPrices{priceExecutionSteps, priceExecutionMemory} =
object [ "priceSteps" .= toRationalJSON priceExecutionSteps
, "priceMemory" .= toRationalJSON priceExecutionMemory
]
instance FromJSON ExecutionUnitPrices where
parseJSON =
withObject "ExecutionUnitPrices" $ \o ->
ExecutionUnitPrices
<$> o .: "priceSteps"
<*> o .: "priceMemory"
toAlonzoPrices :: ExecutionUnitPrices -> Maybe Alonzo.Prices
toAlonzoPrices ExecutionUnitPrices {
priceExecutionSteps,
priceExecutionMemory
} = do
prSteps <- Ledger.boundRational priceExecutionSteps
prMem <- Ledger.boundRational priceExecutionMemory
return Alonzo.Prices {
Alonzo.prSteps,
Alonzo.prMem
}
fromAlonzoPrices :: Alonzo.Prices -> ExecutionUnitPrices
fromAlonzoPrices Alonzo.Prices{Alonzo.prSteps, Alonzo.prMem} =
ExecutionUnitPrices {
priceExecutionSteps = Ledger.unboundRational prSteps,
priceExecutionMemory = Ledger.unboundRational prMem
}
-- ----------------------------------------------------------------------------
-- Script cost models
--
newtype CostModel = CostModel (Map Text Integer)
deriving (Eq, Show)
deriving newtype (ToJSON, FromJSON)
deriving newtype (ToCBOR, FromCBOR)
validateCostModel :: PlutusScriptVersion lang
-> CostModel
-> Either InvalidCostModel ()
validateCostModel PlutusScriptV1 (CostModel m) =
first (InvalidCostModel (CostModel m))
$ Alonzo.assertWellFormedCostModelParams m
validateCostModel PlutusScriptV2 (CostModel m) =
first (InvalidCostModel (CostModel m))
$ Alonzo.assertWellFormedCostModelParams m
-- TODO alonzo: it'd be nice if the library told us what was wrong
data InvalidCostModel = InvalidCostModel CostModel Alonzo.CostModelApplyError
deriving Show
instance Error InvalidCostModel where
displayError (InvalidCostModel cm err) =
"Invalid cost model: " ++ display err ++
" Cost model: " ++ show cm
toAlonzoCostModels
:: Map AnyPlutusScriptVersion CostModel
-> Either String Alonzo.CostModels
toAlonzoCostModels m = do
f <- mapM conv $ Map.toList m
Right . Alonzo.CostModels $ Map.fromList f
where
conv :: (AnyPlutusScriptVersion, CostModel) -> Either String (Alonzo.Language, Alonzo.CostModel)
conv (anySVer, cModel )= do
-- TODO: Propagate InvalidCostModel further
alonzoCostModel <- first displayError $ toAlonzoCostModel cModel (toAlonzoScriptLanguage anySVer)
Right (toAlonzoScriptLanguage anySVer, alonzoCostModel)
fromAlonzoCostModels
:: Alonzo.CostModels
-> Map AnyPlutusScriptVersion CostModel
fromAlonzoCostModels (Alonzo.CostModels m)=
Map.fromList
. map (bimap fromAlonzoScriptLanguage fromAlonzoCostModel)
$ Map.toList m
toAlonzoScriptLanguage :: AnyPlutusScriptVersion -> Alonzo.Language
toAlonzoScriptLanguage (AnyPlutusScriptVersion PlutusScriptV1) = Alonzo.PlutusV1
toAlonzoScriptLanguage (AnyPlutusScriptVersion PlutusScriptV2) = Alonzo.PlutusV2
fromAlonzoScriptLanguage :: Alonzo.Language -> AnyPlutusScriptVersion
fromAlonzoScriptLanguage Alonzo.PlutusV1 = AnyPlutusScriptVersion PlutusScriptV1
fromAlonzoScriptLanguage Alonzo.PlutusV2 = AnyPlutusScriptVersion PlutusScriptV2
toAlonzoCostModel :: CostModel -> Alonzo.Language -> Either InvalidCostModel Alonzo.CostModel
toAlonzoCostModel (CostModel m) l = first (InvalidCostModel (CostModel m)) $ Alonzo.mkCostModel l m
fromAlonzoCostModel :: Alonzo.CostModel -> CostModel
fromAlonzoCostModel m = CostModel $ Alonzo.getCostModelParams m
-- ----------------------------------------------------------------------------
-- Proposals embedded in transactions to update protocol parameters
--
data UpdateProposal =
UpdateProposal
!(Map (Hash GenesisKey) ProtocolParametersUpdate)
!EpochNo
deriving stock (Eq, Show)
deriving anyclass SerialiseAsCBOR
instance HasTypeProxy UpdateProposal where
data AsType UpdateProposal = AsUpdateProposal
proxyToAsType _ = AsUpdateProposal
instance HasTextEnvelope UpdateProposal where
textEnvelopeType _ = "UpdateProposalShelley"
instance ToCBOR UpdateProposal where
toCBOR (UpdateProposal ppup epochno) =
CBOR.encodeListLen 2
<> toCBOR ppup
<> toCBOR epochno
instance FromCBOR UpdateProposal where
fromCBOR = do
CBOR.enforceSize "ProtocolParametersUpdate" 2
UpdateProposal
<$> fromCBOR
<*> fromCBOR
makeShelleyUpdateProposal :: ProtocolParametersUpdate
-> [Hash GenesisKey]
-> EpochNo
-> UpdateProposal
makeShelleyUpdateProposal params genesisKeyHashes =
--TODO decide how to handle parameter validation
-- for example we need to validate the Rational values can convert
-- into the UnitInterval type ok.
UpdateProposal (Map.fromList [ (kh, params) | kh <- genesisKeyHashes ])
-- ----------------------------------------------------------------------------
-- Conversion functions: updates to ledger types
--
toLedgerUpdate :: forall era ledgerera.
ShelleyLedgerEra era ~ ledgerera
=> Ledger.Crypto ledgerera ~ StandardCrypto
=> ShelleyBasedEra era
-> UpdateProposal
-> Ledger.Update ledgerera
toLedgerUpdate era (UpdateProposal ppup epochno) =
Ledger.Update (toLedgerProposedPPUpdates era ppup) epochno
toLedgerProposedPPUpdates :: forall era ledgerera.
ShelleyLedgerEra era ~ ledgerera
=> Ledger.Crypto ledgerera ~ StandardCrypto
=> ShelleyBasedEra era
-> Map (Hash GenesisKey) ProtocolParametersUpdate
-> Ledger.ProposedPPUpdates ledgerera
toLedgerProposedPPUpdates era =
Ledger.ProposedPPUpdates
. Map.mapKeysMonotonic (\(GenesisKeyHash kh) -> kh)
. Map.map (toLedgerPParamsDelta era)
toLedgerPParamsDelta :: ShelleyBasedEra era
-> ProtocolParametersUpdate
-> Ledger.PParamsDelta (ShelleyLedgerEra era)
toLedgerPParamsDelta ShelleyBasedEraShelley = toShelleyPParamsUpdate
toLedgerPParamsDelta ShelleyBasedEraAllegra = toShelleyPParamsUpdate
toLedgerPParamsDelta ShelleyBasedEraMary = toShelleyPParamsUpdate
toLedgerPParamsDelta ShelleyBasedEraAlonzo = toAlonzoPParamsUpdate
toLedgerPParamsDelta ShelleyBasedEraBabbage = toBabbagePParamsUpdate
--TODO: we should do validation somewhere, not just silently drop changes that
-- are not valid. Specifically, see Ledger.boundRational below.
toShelleyPParamsUpdate :: ProtocolParametersUpdate
-> Shelley.PParamsUpdate ledgerera
toShelleyPParamsUpdate
ProtocolParametersUpdate {
protocolUpdateProtocolVersion
, protocolUpdateDecentralization
, protocolUpdateExtraPraosEntropy
, protocolUpdateMaxBlockHeaderSize
, protocolUpdateMaxBlockBodySize
, protocolUpdateMaxTxSize
, protocolUpdateTxFeeFixed
, protocolUpdateTxFeePerByte
, protocolUpdateMinUTxOValue
, protocolUpdateStakeAddressDeposit
, protocolUpdateStakePoolDeposit
, protocolUpdateMinPoolCost
, protocolUpdatePoolRetireMaxEpoch
, protocolUpdateStakePoolTargetNum
, protocolUpdatePoolPledgeInfluence
, protocolUpdateMonetaryExpansion
, protocolUpdateTreasuryCut
} =
Shelley.PParams {
Shelley._minfeeA = noInlineMaybeToStrictMaybe protocolUpdateTxFeePerByte
, Shelley._minfeeB = noInlineMaybeToStrictMaybe protocolUpdateTxFeeFixed
, Shelley._maxBBSize = noInlineMaybeToStrictMaybe protocolUpdateMaxBlockBodySize
, Shelley._maxTxSize = noInlineMaybeToStrictMaybe protocolUpdateMaxTxSize
, Shelley._maxBHSize = noInlineMaybeToStrictMaybe protocolUpdateMaxBlockHeaderSize
, Shelley._keyDeposit = toShelleyLovelace <$>
noInlineMaybeToStrictMaybe protocolUpdateStakeAddressDeposit
, Shelley._poolDeposit = toShelleyLovelace <$>
noInlineMaybeToStrictMaybe protocolUpdateStakePoolDeposit
, Shelley._eMax = noInlineMaybeToStrictMaybe protocolUpdatePoolRetireMaxEpoch
, Shelley._nOpt = noInlineMaybeToStrictMaybe protocolUpdateStakePoolTargetNum
, Shelley._a0 = noInlineMaybeToStrictMaybe $ Ledger.boundRational =<<
protocolUpdatePoolPledgeInfluence
, Shelley._rho = noInlineMaybeToStrictMaybe $ Ledger.boundRational =<<
protocolUpdateMonetaryExpansion
, Shelley._tau = noInlineMaybeToStrictMaybe $ Ledger.boundRational =<<
protocolUpdateTreasuryCut
, Shelley._d = noInlineMaybeToStrictMaybe $ Ledger.boundRational =<<
protocolUpdateDecentralization
, Shelley._extraEntropy = toLedgerNonce <$>
noInlineMaybeToStrictMaybe protocolUpdateExtraPraosEntropy
, Shelley._protocolVersion = uncurry Ledger.ProtVer <$>
noInlineMaybeToStrictMaybe protocolUpdateProtocolVersion
, Shelley._minUTxOValue = toShelleyLovelace <$>
noInlineMaybeToStrictMaybe protocolUpdateMinUTxOValue
, Shelley._minPoolCost = toShelleyLovelace <$>
noInlineMaybeToStrictMaybe protocolUpdateMinPoolCost
}
toAlonzoPParamsUpdate :: ProtocolParametersUpdate
-> Alonzo.PParamsUpdate ledgerera
toAlonzoPParamsUpdate
ProtocolParametersUpdate {
protocolUpdateProtocolVersion
, protocolUpdateDecentralization
, protocolUpdateExtraPraosEntropy
, protocolUpdateMaxBlockHeaderSize
, protocolUpdateMaxBlockBodySize
, protocolUpdateMaxTxSize
, protocolUpdateTxFeeFixed
, protocolUpdateTxFeePerByte
, protocolUpdateStakeAddressDeposit
, protocolUpdateStakePoolDeposit
, protocolUpdateMinPoolCost
, protocolUpdatePoolRetireMaxEpoch
, protocolUpdateStakePoolTargetNum
, protocolUpdatePoolPledgeInfluence
, protocolUpdateMonetaryExpansion
, protocolUpdateTreasuryCut
, protocolUpdateUTxOCostPerWord
, protocolUpdateCostModels
, protocolUpdatePrices
, protocolUpdateMaxTxExUnits
, protocolUpdateMaxBlockExUnits
, protocolUpdateMaxValueSize
, protocolUpdateCollateralPercent
, protocolUpdateMaxCollateralInputs
} =
Alonzo.PParams {
Alonzo._minfeeA = noInlineMaybeToStrictMaybe protocolUpdateTxFeePerByte
, Alonzo._minfeeB = noInlineMaybeToStrictMaybe protocolUpdateTxFeeFixed
, Alonzo._maxBBSize = noInlineMaybeToStrictMaybe protocolUpdateMaxBlockBodySize
, Alonzo._maxTxSize = noInlineMaybeToStrictMaybe protocolUpdateMaxTxSize
, Alonzo._maxBHSize = noInlineMaybeToStrictMaybe protocolUpdateMaxBlockHeaderSize
, Alonzo._keyDeposit = toShelleyLovelace <$>
noInlineMaybeToStrictMaybe protocolUpdateStakeAddressDeposit
, Alonzo._poolDeposit = toShelleyLovelace <$>
noInlineMaybeToStrictMaybe protocolUpdateStakePoolDeposit
, Alonzo._eMax = noInlineMaybeToStrictMaybe protocolUpdatePoolRetireMaxEpoch
, Alonzo._nOpt = noInlineMaybeToStrictMaybe protocolUpdateStakePoolTargetNum
, Alonzo._a0 = noInlineMaybeToStrictMaybe $ Ledger.boundRational =<<
protocolUpdatePoolPledgeInfluence
, Alonzo._rho = noInlineMaybeToStrictMaybe $ Ledger.boundRational =<<
protocolUpdateMonetaryExpansion
, Alonzo._tau = noInlineMaybeToStrictMaybe $ Ledger.boundRational =<<
protocolUpdateTreasuryCut
, Alonzo._d = noInlineMaybeToStrictMaybe $ Ledger.boundRational =<<
protocolUpdateDecentralization
, Alonzo._extraEntropy = toLedgerNonce <$>
noInlineMaybeToStrictMaybe protocolUpdateExtraPraosEntropy
, Alonzo._protocolVersion = uncurry Ledger.ProtVer <$>
noInlineMaybeToStrictMaybe protocolUpdateProtocolVersion
, Alonzo._minPoolCost = toShelleyLovelace <$>
noInlineMaybeToStrictMaybe protocolUpdateMinPoolCost
, Alonzo._coinsPerUTxOWord = toShelleyLovelace <$>