-
Notifications
You must be signed in to change notification settings - Fork 155
/
LedgerState.hs
1123 lines (1005 loc) · 31.8 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 DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
-- |
-- Module : LedgerState
-- Description : Operational Rules
--
-- This module implements the operation rules for treating UTxO transactions ('Tx')
-- as state transformations on a ledger state ('LedgerState'),
-- as specified in /A Simplified Formal Specification of a UTxO Ledger/.
module Shelley.Spec.Ledger.LedgerState
( LedgerState (..),
Ix,
DPState (..),
DState (..),
AccountState (..),
RewardUpdate (..),
RewardAccounts,
InstantaneousRewards (..),
emptyInstantaneousRewards,
totalInstantaneousReservesRewards,
totalInstantaneousTreasuryRewards,
emptyRewardUpdate,
FutureGenDeleg (..),
EpochState (..),
emptyEpochState,
emptyLedgerState,
emptyPPUPState,
emptyUTxOState,
updatePpup,
PState (..),
KeyPairs,
PPUPState (..),
pvCanFollow,
UTxOState (..),
OBftSlot (..),
emptyAccount,
emptyPState,
emptyDState,
emptyDPState,
-- * state transitions
emptyDelegation,
applyTxBody,
-- * Genesis State
genesisId,
genesisCoins,
genesisState,
-- * Validation
WitHashes (..),
nullWitHashes,
diffWitHashes,
minfee,
txsize,
produced,
consumed,
verifiedWits,
witsVKeyNeeded,
witsFromWitnessSet,
-- DelegationState
-- refunds
keyRefunds,
-- epoch boundary
stakeDistr,
applyRUpd,
createRUpd,
--
NewEpochState (..),
NewEpochEnv (..),
overlaySchedule,
getGKeys,
updateNES,
)
where
import Cardano.Binary
( FromCBOR (..),
ToCBOR (..),
TokenType (TypeNull),
decodeNull,
encodeListLen,
encodeNull,
enforceSize,
peekTokenType,
)
import Cardano.Crypto.Hash (hashWithSerialiser)
import Cardano.Prelude (NFData, NoUnexpectedThunks (..))
import Control.Monad.Trans.Reader (asks)
import qualified Data.ByteString.Lazy as BSL (length)
import Data.Foldable (toList)
import Data.List.NonEmpty (NonEmpty)
import qualified Data.List.NonEmpty as NonEmpty
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromMaybe)
import qualified Data.Sequence.Strict as StrictSeq
import Data.Set (Set)
import qualified Data.Set as Set
import GHC.Generics (Generic)
import Shelley.Spec.Ledger.Address (Addr (..), bootstrapKeyHash)
import Shelley.Spec.Ledger.Address.Bootstrap (bootstrapWitKeyHash)
import Shelley.Spec.Ledger.BaseTypes
( Globals (..),
ShelleyBase,
StrictMaybe (..),
activeSlotVal,
intervalValue,
)
import Shelley.Spec.Ledger.Coin (Coin (..))
import Shelley.Spec.Ledger.Core (dom, (∪), (∪+), (⋪), (▷), (◁))
import Shelley.Spec.Ledger.Credential (Credential (..))
import Shelley.Spec.Ledger.Crypto (Crypto)
import Shelley.Spec.Ledger.Delegation.Certificates
( DCert (..),
PoolDistr (..),
StakeCreds (..),
StakePools (..),
delegCWitness,
genesisCWitness,
isDeRegKey,
poolCWitness,
requiresVKeyWitness,
)
import Shelley.Spec.Ledger.EpochBoundary
( BlocksMade (..),
SnapShot (..),
SnapShots (..),
Stake (..),
aggregateOuts,
baseStake,
emptySnapShots,
ptrStake,
rewardStake,
)
import Shelley.Spec.Ledger.Keys
( DSignable,
GenDelegPair (..),
GenDelegs (..),
Hash,
KeyHash (..),
KeyPair,
KeyRole (..),
VKey,
asWitness,
hash,
)
import Shelley.Spec.Ledger.PParams
( PParams,
PParams' (..),
ProposedPPUpdates (..),
ProtVer (..),
Update (..),
emptyPPPUpdates,
emptyPParams,
)
import Shelley.Spec.Ledger.Rewards
( Likelihood,
NonMyopic (..),
emptyNonMyopic,
reward,
)
import Shelley.Spec.Ledger.Serialization (mapFromCBOR, mapToCBOR)
import Shelley.Spec.Ledger.Slot
( Duration (..),
EpochNo (..),
SlotNo (..),
epochInfoFirst,
epochInfoSize,
(+*),
)
import Shelley.Spec.Ledger.Tx
( Tx (..),
WitnessSet,
WitnessSetHKD (..),
addrWits,
extractKeyHashWitnessSet,
)
import Shelley.Spec.Ledger.TxData
( Ix,
PoolCert (..),
PoolParams (..),
Ptr (..),
RewardAcnt (..),
TxBody (..),
TxId (..),
TxIn (..),
TxOut (..),
Wdrl (..),
WitVKey (..),
getRwdCred,
witKeyHash,
)
import Shelley.Spec.Ledger.UTxO
( UTxO (..),
balance,
totalDeposits,
txinLookup,
txins,
txouts,
txup,
verifyWitVKey,
)
-- | Representation of a list of pairs of key pairs, e.g., pay and stake keys
type KeyPairs crypto = [(KeyPair 'Payment crypto, KeyPair 'Staking crypto)]
type RewardAccounts crypto =
Map (RewardAcnt crypto) Coin
data FutureGenDeleg crypto = FutureGenDeleg
{ fGenDelegSlot :: !SlotNo,
fGenDelegGenKeyHash :: !(KeyHash 'Genesis crypto)
}
deriving (Show, Eq, Ord, Generic)
instance NoUnexpectedThunks (FutureGenDeleg crypto)
instance NFData (FutureGenDeleg crypto)
instance Crypto crypto => ToCBOR (FutureGenDeleg crypto) where
toCBOR (FutureGenDeleg a b) =
encodeListLen 2 <> toCBOR a <> toCBOR b
instance Crypto crypto => FromCBOR (FutureGenDeleg crypto) where
fromCBOR = do
enforceSize "FutureGenDeleg" 2
a <- fromCBOR
b <- fromCBOR
pure $ FutureGenDeleg a b
data InstantaneousRewards crypto = InstantaneousRewards
{ iRReserves :: !(Map (Credential 'Staking crypto) Coin),
iRTreasury :: !(Map (Credential 'Staking crypto) Coin)
}
deriving (Show, Eq, Generic)
totalInstantaneousReservesRewards :: InstantaneousRewards crypto -> Coin
totalInstantaneousReservesRewards (InstantaneousRewards irR _) = sum irR
totalInstantaneousTreasuryRewards :: InstantaneousRewards crypto -> Coin
totalInstantaneousTreasuryRewards (InstantaneousRewards _ irT) = sum irT
instance NoUnexpectedThunks (InstantaneousRewards crypto)
instance NFData (InstantaneousRewards crypto)
instance Crypto crypto => ToCBOR (InstantaneousRewards crypto) where
toCBOR (InstantaneousRewards irR irT) =
encodeListLen 2 <> mapToCBOR irR <> mapToCBOR irT
instance Crypto crypto => FromCBOR (InstantaneousRewards crypto) where
fromCBOR = do
enforceSize "InstantaneousRewards" 2
irR <- mapFromCBOR
irT <- mapFromCBOR
pure $ InstantaneousRewards irR irT
-- | State of staking pool delegations and rewards
data DState crypto = DState
{ -- | The active stake keys.
_stkCreds :: !(StakeCreds crypto),
-- | The active reward accounts.
_rewards :: !(RewardAccounts crypto),
-- | The current delegations.
_delegations :: !(Map (Credential 'Staking crypto) (KeyHash 'StakePool crypto)),
-- | The pointed to hash keys.
_ptrs :: !(Map Ptr (Credential 'Staking crypto)),
-- | future genesis key delegations
_fGenDelegs :: !(Map (FutureGenDeleg crypto) (GenDelegPair crypto)),
-- | Genesis key delegations
_genDelegs :: !(GenDelegs crypto),
-- | Instantaneous Rewards
_irwd :: !(InstantaneousRewards crypto)
}
deriving (Show, Eq, Generic)
instance NoUnexpectedThunks (DState crypto)
instance NFData (DState crypto)
instance Crypto crypto => ToCBOR (DState crypto) where
toCBOR (DState sc rw dlg p fgs gs ir) =
encodeListLen 7
<> toCBOR sc
<> toCBOR rw
<> toCBOR dlg
<> toCBOR p
<> toCBOR fgs
<> toCBOR gs
<> toCBOR ir
instance Crypto crypto => FromCBOR (DState crypto) where
fromCBOR = do
enforceSize "DState" 7
sc <- fromCBOR
rw <- fromCBOR
dlg <- fromCBOR
p <- fromCBOR
fgs <- fromCBOR
gs <- fromCBOR
ir <- fromCBOR
pure $ DState sc rw dlg p fgs gs ir
-- | Current state of staking pools and their certificate counters.
data PState crypto = PState
{ -- | The active stake pools.
_stPools :: !(StakePools crypto),
-- | The pool parameters.
_pParams :: !(Map (KeyHash 'StakePool crypto) (PoolParams crypto)),
-- | The future pool parameters.
_fPParams :: !(Map (KeyHash 'StakePool crypto) (PoolParams crypto)),
-- | A map of retiring stake pools to the epoch when they retire.
_retiring :: !(Map (KeyHash 'StakePool crypto) EpochNo)
}
deriving (Show, Eq, Generic)
instance NoUnexpectedThunks (PState crypto)
instance NFData (PState crypto)
instance Crypto crypto => ToCBOR (PState crypto) where
toCBOR (PState a b c d) =
encodeListLen 4 <> toCBOR a <> toCBOR b <> toCBOR c <> toCBOR d
instance Crypto crypto => FromCBOR (PState crypto) where
fromCBOR = do
enforceSize "PState" 4
a <- fromCBOR
b <- fromCBOR
c <- fromCBOR
d <- fromCBOR
pure $ PState a b c d
-- | The state associated with the current stake delegation.
data DPState crypto = DPState
{ _dstate :: !(DState crypto),
_pstate :: !(PState crypto)
}
deriving (Show, Eq, Generic)
instance NoUnexpectedThunks (DPState crypto)
instance NFData (DPState crypto)
instance Crypto crypto => ToCBOR (DPState crypto) where
toCBOR (DPState ds ps) =
encodeListLen 2 <> toCBOR ds <> toCBOR ps
instance Crypto crypto => FromCBOR (DPState crypto) where
fromCBOR = do
enforceSize "DPState" 2
ds <- fromCBOR
ps <- fromCBOR
pure $ DPState ds ps
data RewardUpdate crypto = RewardUpdate
{ deltaT :: !Coin,
deltaR :: !Coin,
rs :: !(Map (RewardAcnt crypto) Coin),
deltaF :: !Coin,
nonMyopic :: !(NonMyopic crypto)
}
deriving (Show, Eq, Generic)
instance NoUnexpectedThunks (RewardUpdate crypto)
instance NFData (RewardUpdate crypto)
instance Crypto crypto => ToCBOR (RewardUpdate crypto) where
toCBOR (RewardUpdate dt dr rw df nm) =
encodeListLen 5
<> toCBOR dt
<> toCBOR (- dr) -- TODO change Coin serialization to use integers?
<> toCBOR rw
<> toCBOR (- df) -- TODO change Coin serialization to use integers?
<> toCBOR nm
instance Crypto crypto => FromCBOR (RewardUpdate crypto) where
fromCBOR = do
enforceSize "RewardUpdate" 5
dt <- fromCBOR
dr <- fromCBOR -- TODO change Coin serialization to use integers?
rw <- fromCBOR
df <- fromCBOR -- TODO change Coin serialization to use integers?
nm <- fromCBOR
pure $ RewardUpdate dt (- dr) rw (- df) nm
emptyRewardUpdate :: RewardUpdate crypto
emptyRewardUpdate = RewardUpdate (Coin 0) (Coin 0) Map.empty (Coin 0) emptyNonMyopic
data AccountState = AccountState
{ _treasury :: !Coin,
_reserves :: !Coin
}
deriving (Show, Eq, Generic)
instance ToCBOR AccountState where
toCBOR (AccountState t r) =
encodeListLen 2 <> toCBOR t <> toCBOR r
instance FromCBOR AccountState where
fromCBOR = do
enforceSize "AccountState" 2
t <- fromCBOR
r <- fromCBOR
pure $ AccountState t r
instance NoUnexpectedThunks AccountState
instance NFData AccountState
data EpochState crypto = EpochState
{ esAccountState :: !AccountState,
esSnapshots :: !(SnapShots crypto),
esLState :: !(LedgerState crypto),
esPrevPp :: !PParams,
esPp :: !PParams,
esNonMyopic :: !(NonMyopic crypto)
}
deriving (Show, Eq, Generic)
instance NoUnexpectedThunks (EpochState crypto)
instance NFData (EpochState crypto)
instance Crypto crypto => ToCBOR (EpochState crypto) where
toCBOR (EpochState a s l r p n) =
encodeListLen 6 <> toCBOR a <> toCBOR s <> toCBOR l <> toCBOR r <> toCBOR p <> toCBOR n
instance Crypto crypto => FromCBOR (EpochState crypto) where
fromCBOR = do
enforceSize "EpochState" 6
a <- fromCBOR
s <- fromCBOR
l <- fromCBOR
r <- fromCBOR
p <- fromCBOR
n <- fromCBOR
pure $ EpochState a s l r p n
emptyPPUPState :: PPUPState crypto
emptyPPUPState = PPUPState emptyPPPUpdates emptyPPPUpdates
emptyUTxOState :: UTxOState crypto
emptyUTxOState = UTxOState (UTxO Map.empty) (Coin 0) (Coin 0) emptyPPUPState
emptyEpochState :: EpochState crypto
emptyEpochState =
EpochState emptyAccount emptySnapShots emptyLedgerState emptyPParams emptyPParams emptyNonMyopic
emptyLedgerState :: LedgerState crypto
emptyLedgerState =
LedgerState
emptyUTxOState
emptyDelegation
emptyAccount :: AccountState
emptyAccount = AccountState (Coin 0) (Coin 0)
emptyDelegation :: DPState crypto
emptyDelegation =
DPState emptyDState emptyPState
emptyInstantaneousRewards :: InstantaneousRewards crypto
emptyInstantaneousRewards = InstantaneousRewards Map.empty Map.empty
emptyDState :: DState crypto
emptyDState =
DState
(StakeCreds Map.empty)
Map.empty
Map.empty
Map.empty
Map.empty
(GenDelegs Map.empty)
emptyInstantaneousRewards
emptyPState :: PState crypto
emptyPState =
PState (StakePools Map.empty) Map.empty Map.empty Map.empty
emptyDPState :: DPState crypto
emptyDPState = DPState emptyDState emptyPState
data PPUPState crypto = PPUPState
{ proposals :: ProposedPPUpdates crypto,
futureProposals :: ProposedPPUpdates crypto
}
deriving (Show, Eq, Generic, NFData, NoUnexpectedThunks)
instance Crypto crypto => ToCBOR (PPUPState crypto) where
toCBOR (PPUPState ppup fppup) =
encodeListLen 2 <> toCBOR ppup <> toCBOR fppup
instance Crypto crypto => FromCBOR (PPUPState crypto) where
fromCBOR = do
enforceSize "PPUPState" 2
ppup <- fromCBOR
fppup <- fromCBOR
pure $ PPUPState ppup fppup
pvCanFollow :: ProtVer -> StrictMaybe ProtVer -> Bool
pvCanFollow _ SNothing = True
pvCanFollow (ProtVer m n) (SJust (ProtVer m' n')) =
(m + 1, 0) == (m', n') || (m, n + 1) == (m', n')
-- | Update the protocol parameter updates by clearing out the proposals
-- and making the future proposals become the new proposals,
-- provided the new proposals can follow (otherwise reset them).
updatePpup :: UTxOState crypto -> PParams -> UTxOState crypto
updatePpup utxoSt pp = utxoSt {_ppups = PPUPState ps emptyPPPUpdates}
where
(ProposedPPUpdates newProposals) = futureProposals . _ppups $ utxoSt
goodPV = pvCanFollow (_protocolVersion pp) . _protocolVersion
ps = if all goodPV newProposals then ProposedPPUpdates newProposals else emptyPPPUpdates
data UTxOState crypto = UTxOState
{ _utxo :: !(UTxO crypto),
_deposited :: !Coin,
_fees :: !Coin,
_ppups :: !(PPUPState crypto)
}
deriving (Show, Eq, Generic, NFData)
instance NoUnexpectedThunks (UTxOState crypto)
instance Crypto crypto => ToCBOR (UTxOState crypto) where
toCBOR (UTxOState ut dp fs us) =
encodeListLen 4 <> toCBOR ut <> toCBOR dp <> toCBOR fs <> toCBOR us
instance Crypto crypto => FromCBOR (UTxOState crypto) where
fromCBOR = do
enforceSize "UTxOState" 4
ut <- fromCBOR
dp <- fromCBOR
fs <- fromCBOR
us <- fromCBOR
pure $ UTxOState ut dp fs us
data OBftSlot crypto
= NonActiveSlot
| ActiveSlot !(KeyHash 'Genesis crypto)
deriving (Show, Eq, Ord, Generic)
instance
Crypto crypto =>
ToCBOR (OBftSlot crypto)
where
toCBOR NonActiveSlot = encodeNull
toCBOR (ActiveSlot k) = toCBOR k
instance
Crypto crypto =>
FromCBOR (OBftSlot crypto)
where
fromCBOR = do
peekTokenType >>= \case
TypeNull -> do
decodeNull
pure NonActiveSlot
_ -> ActiveSlot <$> fromCBOR
instance NoUnexpectedThunks (OBftSlot crypto)
instance NFData (OBftSlot crypto)
-- | New Epoch state and environment
data NewEpochState crypto = NewEpochState
{ -- | Last epoch
nesEL :: !EpochNo,
-- | Blocks made before current epoch
nesBprev :: !(BlocksMade crypto),
-- | Blocks made in current epoch
nesBcur :: !(BlocksMade crypto),
-- | Epoch state before current
nesEs :: !(EpochState crypto),
-- | Possible reward update
nesRu :: !(StrictMaybe (RewardUpdate crypto)),
-- | Stake distribution within the stake pool
nesPd :: !(PoolDistr crypto),
-- | Overlay schedule for PBFT vs Praos
nesOsched :: !(Map SlotNo (OBftSlot crypto))
}
deriving (Show, Eq, Generic)
instance NFData (NewEpochState crypto)
instance NoUnexpectedThunks (NewEpochState crypto)
instance Crypto crypto => ToCBOR (NewEpochState crypto) where
toCBOR (NewEpochState e bp bc es ru pd os) =
encodeListLen 7 <> toCBOR e <> toCBOR bp <> toCBOR bc <> toCBOR es
<> toCBOR ru
<> toCBOR pd
<> toCBOR (compactOverlaySchedule os)
instance Crypto crypto => FromCBOR (NewEpochState crypto) where
fromCBOR = do
enforceSize "NewEpochState" 7
e <- fromCBOR
bp <- fromCBOR
bc <- fromCBOR
es <- fromCBOR
ru <- fromCBOR
pd <- fromCBOR
os <- decompactOverlaySchedule <$> fromCBOR
pure $ NewEpochState e bp bc es ru pd os
-- | Convert the overlay schedule to a representation that is more compact
-- when serialised to a bytestring, but less efficient for lookups.
--
-- Each genesis key hash will only be stored once, instead of each time it is
-- assigned to a slot.
compactOverlaySchedule ::
Map SlotNo (OBftSlot crypto) ->
Map (OBftSlot crypto) (NonEmpty SlotNo)
compactOverlaySchedule =
Map.foldrWithKey'
( \slot obftSlot ->
Map.insertWith (<>) obftSlot (pure slot)
)
Map.empty
-- | Inverse of 'compactOverlaySchedule'
decompactOverlaySchedule ::
Map (OBftSlot crypto) (NonEmpty SlotNo) ->
Map SlotNo (OBftSlot crypto)
decompactOverlaySchedule compact =
Map.fromList
[ (slot, obftSlot)
| (obftSlot, slots) <- Map.toList compact,
slot <- NonEmpty.toList slots
]
getGKeys ::
NewEpochState crypto ->
Set (KeyHash 'Genesis crypto)
getGKeys nes = Map.keysSet genDelegs
where
NewEpochState _ _ _ es _ _ _ = nes
EpochState _ _ ls _ _ _ = es
LedgerState _ (DPState (DState _ _ _ _ _ (GenDelegs genDelegs) _) _) = ls
data NewEpochEnv crypto = NewEpochEnv
{ neeS :: SlotNo,
neeGkeys :: Set (KeyHash 'Genesis crypto)
}
deriving (Show, Eq, Generic)
instance NoUnexpectedThunks (NewEpochEnv crypto)
-- | The state associated with a 'Ledger'.
data LedgerState crypto = LedgerState
{ -- | The current unspent transaction outputs.
_utxoState :: !(UTxOState crypto),
-- | The current delegation state
_delegationState :: !(DPState crypto)
}
deriving (Show, Eq, Generic)
instance NoUnexpectedThunks (LedgerState crypto)
instance NFData (LedgerState crypto)
instance Crypto crypto => ToCBOR (LedgerState crypto) where
toCBOR (LedgerState u dp) =
encodeListLen 2 <> toCBOR u <> toCBOR dp
instance Crypto crypto => FromCBOR (LedgerState crypto) where
fromCBOR = do
enforceSize "LedgerState" 2
u <- fromCBOR
dp <- fromCBOR
pure $ LedgerState u dp
-- | The transaction Id for 'UTxO' included at the beginning of a new ledger.
genesisId ::
(Crypto crypto) =>
TxId crypto
genesisId =
TxId $
hash
( TxBody
Set.empty
StrictSeq.Empty
StrictSeq.Empty
(Wdrl Map.empty)
(Coin 0)
(SlotNo 0)
SNothing
SNothing
)
-- | Creates the UTxO for a new ledger with the specified transaction outputs.
genesisCoins ::
(Crypto crypto) =>
[TxOut crypto] ->
UTxO crypto
genesisCoins outs =
UTxO $
Map.fromList [(TxIn genesisId idx, out) | (idx, out) <- zip [0 ..] outs]
-- | Creates the ledger state for an empty ledger which
-- contains the specified transaction outputs.
genesisState ::
Map (KeyHash 'Genesis crypto) (GenDelegPair crypto) ->
UTxO crypto ->
LedgerState crypto
genesisState genDelegs0 utxo0 =
LedgerState
( UTxOState
utxo0
(Coin 0)
(Coin 0)
emptyPPUPState
)
(DPState dState emptyPState)
where
dState = emptyDState {_genDelegs = GenDelegs genDelegs0}
-- | Implementation of abstract transaction size
txsize :: forall crypto. (Crypto crypto) => Tx crypto -> Integer
txsize tx = numInputs * inputSize + numOutputs * outputSize + rest
where
uint = 5
smallArray = 1
hashLen = 32
hashObj = 2 + hashLen
addrHashLen = 28
addrHeader = 1
address = 2 + addrHeader + 2 * addrHashLen
txbody = _body tx
numInputs = toInteger . length . _inputs $ txbody
inputSize = smallArray + uint + hashObj
numOutputs = toInteger . length . _outputs $ txbody
outputSize = smallArray + uint + address
rest = fromIntegral $ BSL.length (txFullBytes tx) - extraSize txbody
-- | Minimum fee calculation
minfee :: forall crypto. (Crypto crypto) => PParams -> Tx crypto -> Coin
minfee pp tx = Coin $ fromIntegral (_minfeeA pp) * txsize tx + fromIntegral (_minfeeB pp)
-- | Compute the lovelace which are created by the transaction
produced ::
(Crypto crypto) =>
PParams ->
StakePools crypto ->
TxBody crypto ->
Coin
produced pp stakePools tx =
balance (txouts tx) + _txfee tx + totalDeposits pp stakePools (toList $ _certs tx)
-- | Compute the key deregistration refunds in a transaction
keyRefunds ::
Crypto crypto =>
PParams ->
TxBody crypto ->
Coin
keyRefunds pp tx = (_keyDeposit pp) * (fromIntegral $ length deregistrations)
where
deregistrations = filter isDeRegKey (toList $ _certs tx)
-- | Compute the lovelace which are destroyed by the transaction
consumed ::
Crypto crypto =>
PParams ->
UTxO crypto ->
TxBody crypto ->
Coin
consumed pp u tx =
balance (txins tx ◁ u) + refunds + withdrawals
where
-- balance (UTxO (Map.restrictKeys v (txins tx))) + refunds + withdrawals
refunds = keyRefunds pp tx
withdrawals = sum . unWdrl $ _wdrls tx
newtype WitHashes crypto
= WitHashes
(Set (KeyHash 'Witness crypto))
deriving (Eq, Generic, Show)
instance Crypto crypto => NoUnexpectedThunks (WitHashes crypto)
-- | Check if a set of witness hashes is empty.
nullWitHashes :: WitHashes crypto -> Bool
nullWitHashes (WitHashes a) = Set.null a
-- | Extract the difference between two sets of witness hashes.
diffWitHashes :: WitHashes crypto -> WitHashes crypto -> WitHashes crypto
diffWitHashes (WitHashes x) (WitHashes x') =
WitHashes (x `Set.difference` x')
-- | Extract the witness hashes from the Witness set.
witsFromWitnessSet ::
Crypto crypto => WitnessSet crypto -> WitHashes crypto
witsFromWitnessSet (WitnessSet aWits _ bsWits) =
WitHashes $
Set.map witKeyHash aWits
`Set.union` Set.map bootstrapWitKeyHash bsWits
-- | Collect the set of hashes of keys that needs to sign a
-- given transaction. This set consists of the txin owners,
-- certificate authors, and withdrawal reward accounts.
witsVKeyNeeded ::
forall crypto.
Crypto crypto =>
UTxO crypto ->
Tx crypto ->
GenDelegs crypto ->
WitHashes crypto
witsVKeyNeeded utxo' tx@(Tx txbody _ _) genDelegs =
WitHashes $
certAuthors
`Set.union` inputAuthors
`Set.union` owners
`Set.union` wdrlAuthors
`Set.union` updateKeys
where
inputAuthors :: Set (KeyHash 'Witness crypto)
inputAuthors = foldr accum Set.empty (_inputs txbody)
where
accum txin ans =
case txinLookup txin utxo' of
Just (TxOut (Addr _ (KeyHashObj pay) _) _) -> Set.insert (asWitness pay) ans
Just (TxOut (AddrBootstrap bootAddr) _) -> Set.insert (asWitness (bootstrapKeyHash bootAddr)) ans
_other -> ans
wdrlAuthors :: Set (KeyHash 'Witness crypto)
wdrlAuthors = Map.foldrWithKey accum Set.empty (unWdrl (_wdrls txbody))
where
accum key _ ans = Set.union (extractKeyHashWitnessSet [getRwdCred key]) ans
owners :: Set (KeyHash 'Witness crypto)
owners = foldr accum Set.empty (_certs txbody)
where
accum (DCertPool (RegPool pool)) ans = Set.union (Set.map asWitness (_poolOwners pool)) ans
accum _cert ans = ans
cwitness (DCertDeleg dc) = extractKeyHashWitnessSet [delegCWitness dc]
cwitness (DCertPool pc) = extractKeyHashWitnessSet [poolCWitness pc]
cwitness (DCertGenesis gc) = Set.singleton (asWitness $ genesisCWitness gc)
cwitness c = error $ show c ++ " does not have a witness"
-- key reg requires no witness but this is already filtered outby requiresVKeyWitness
-- before the call to `cwitness`, so this error should never be reached.
certAuthors :: Set (KeyHash 'Witness crypto)
certAuthors = foldr accum Set.empty (_certs txbody)
where
accum cert ans | requiresVKeyWitness cert = Set.union (cwitness cert) ans
accum _cert ans = ans
updateKeys :: Set (KeyHash 'Witness crypto)
updateKeys = asWitness `Set.map` propWits (txup tx) genDelegs
-- | Given a ledger state, determine if the UTxO witnesses in a given
-- transaction are correct.
verifiedWits ::
( Crypto crypto,
DSignable crypto (Hash crypto (TxBody crypto))
) =>
Tx crypto ->
Either [VKey 'Witness crypto] ()
verifiedWits (Tx txbody wits _) =
case null failed of
True -> Right ()
False ->
Left $
fmap (\(WitVKey vk _) -> vk) failed
where
failed =
filter
(not . verifyWitVKey (hashWithSerialiser toCBOR txbody))
(Set.toList $ addrWits wits)
-- | Calculate the set of hash keys of the required witnesses for update
-- proposals.
propWits ::
Maybe (Update crypto) ->
GenDelegs crypto ->
Set (KeyHash 'Witness crypto)
propWits Nothing _ = Set.empty
propWits (Just (Update (ProposedPPUpdates pup) _)) (GenDelegs genDelegs) =
Set.map asWitness . Set.fromList $ Map.elems updateKeys
where
updateKeys' = Map.keysSet pup ◁ genDelegs
updateKeys = Map.map genDelegKeyHash updateKeys'
-- Functions for stake delegation model
-- | Calculate the change to the deposit pool for a given transaction.
depositPoolChange ::
Crypto crypto =>
LedgerState crypto ->
PParams ->
TxBody crypto ->
Coin
depositPoolChange ls pp tx = (currentPool + txDeposits) - txRefunds
where
-- Note that while (currentPool + txDeposits) >= txRefunds,
-- it could be that txDeposits < txRefunds. We keep the parenthesis above
-- to emphasize this point.
currentPool = (_deposited . _utxoState) ls
txDeposits =
totalDeposits pp ((_stPools . _pstate . _delegationState) ls) (toList $ _certs tx)
txRefunds = keyRefunds pp tx
-- | Apply a transaction body as a state transition function on the ledger state.
--
-- TODO this function is only used in testing, and should be moved accordingly.
applyTxBody ::
(Crypto crypto) =>
LedgerState crypto ->
PParams ->
TxBody crypto ->
LedgerState crypto
applyTxBody ls pp tx =
ls
{ _utxoState =
us
{ _utxo = txins tx ⋪ (_utxo us) ∪ txouts tx,
_deposited = depositPoolChange ls pp tx,
_fees = (_txfee tx) + (_fees . _utxoState $ ls)
},
_delegationState =
dels
{ _dstate = dst {_rewards = newAccounts}
}
}
where
dels = _delegationState ls
dst = _dstate dels
us = _utxoState ls
newAccounts =
reapRewards
((_rewards . _dstate . _delegationState) ls)
(unWdrl $ _wdrls tx)
reapRewards ::
RewardAccounts crypto ->
RewardAccounts crypto ->
RewardAccounts crypto
reapRewards dStateRewards withdrawals =
Map.mapWithKey removeRewards dStateRewards
where
removeRewards k v = if k `Map.member` withdrawals then Coin 0 else v
---------------------------------
-- epoch boundary calculations --
---------------------------------
-- | Stake distribution
stakeDistr ::
forall crypto.
UTxO crypto ->
DState crypto ->
PState crypto ->
SnapShot crypto
stakeDistr u ds ps =
SnapShot
(Stake $ dom activeDelegs ◁ aggregatePlus stakeRelation)
delegs
poolParams
where
DState (StakeCreds stkcreds) rewards' delegs ptrs' _ _ _ = ds
PState (StakePools stpools) poolParams _ _ = ps
outs = aggregateOuts u
stakeRelation :: [(Credential 'Staking crypto, Coin)]
stakeRelation = baseStake outs ∪ ptrStake outs ptrs' ∪ rewardStake rewards'
activeDelegs = dom stkcreds ◁ delegs ▷ dom stpools
aggregatePlus = Map.fromListWith (+)
-- | Apply a reward update
applyRUpd ::
RewardUpdate crypto ->
EpochState crypto ->
EpochState crypto
applyRUpd ru (EpochState as ss ls pr pp _nm) = EpochState as' ss ls' pr pp nm'
where
utxoState_ = _utxoState ls
delegState = _delegationState ls
dState = _dstate delegState
as' =
as
{ _treasury = _treasury as + deltaT ru,
_reserves = _reserves as + deltaR ru
}
ls' =