/
Consensus.hs
525 lines (474 loc) · 17.4 KB
/
Consensus.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
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# OPTIONS_GHC -Wno-orphans #-}
-- | Generic Consensus examples
module Test.Cardano.Ledger.Generic.Consensus where
import Cardano.Binary
import Cardano.Crypto.DSIGN as DSIGN
import Cardano.Crypto.Hash as Hash
import Cardano.Crypto.Seed as Seed
import Cardano.Crypto.VRF as VRF
import Cardano.Ledger.AuxiliaryData
import Cardano.Ledger.BaseTypes
import Cardano.Ledger.Coin
import qualified Cardano.Ledger.Core as Core
import Cardano.Ledger.Crypto as CC
import Cardano.Ledger.Era
import qualified Cardano.Ledger.Era as Era (Crypto)
import Cardano.Ledger.Keys
import Cardano.Ledger.PoolDistr
import Cardano.Ledger.SafeHash
import Cardano.Ledger.Shelley (ShelleyEra)
import Cardano.Ledger.Shelley.API
import Cardano.Ledger.Shelley.EpochBoundary
import Cardano.Ledger.Shelley.LedgerState
import Cardano.Ledger.Shelley.PParams
import Cardano.Ledger.Shelley.Rules.Delegs
import Cardano.Ledger.Shelley.Rules.Ledger
import Cardano.Ledger.Shelley.Tx
import Cardano.Ledger.Shelley.UTxO
import Cardano.Protocol.TPraos.API
import Cardano.Protocol.TPraos.BHeader
import Cardano.Protocol.TPraos.OCert
import Cardano.Protocol.TPraos.Rules.Prtcl
import Cardano.Protocol.TPraos.Rules.Tickn
import Cardano.Slotting.Block
import Cardano.Slotting.EpochInfo
import Cardano.Slotting.Slot
import qualified Data.ByteString as Strict
import Data.Coerce (coerce)
import Data.Default.Class
import Data.Functor.Identity (Identity (..))
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe (fromJust)
import Data.Proxy
import Data.Sequence.Strict (StrictSeq)
import qualified Data.Sequence.Strict as StrictSeq
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Time
import Data.Word (Word64, Word8)
import GHC.Records (HasField)
import Numeric.Natural (Natural)
import Test.Cardano.Ledger.Shelley.Generator.Core
import Test.Cardano.Ledger.Shelley.Orphans ()
import Test.Cardano.Ledger.Shelley.Utils hiding (mkVRFKeyPair)
import Test.Cardano.Ledger.Generic.Proof
import Cardano.Ledger.Shelley.Rules.EraMapping ()
import Cardano.Crypto.KES.Class(ContextKES)
import qualified Cardano.Ledger.Shelley.PParams as ShelleyPP
import qualified Cardano.Ledger.Alonzo.PParams as AlonzoPP
import qualified Cardano.Ledger.Babbage.PParams as BabbagePP
import qualified Cardano.Ledger.Conway.PParams as ConwayPP
import Cardano.Protocol.TPraos.API(PraosCrypto)
type KeyPairWits era = [KeyPair 'Witness (Cardano.Ledger.Era.Crypto era)]
emptyPPUpdate :: Proof era -> Core.PParamsUpdate era
emptyPPUpdate (Shelley _) = ShelleyPP.emptyPParamsUpdate
emptyPPUpdate (Allegra _) = ShelleyPP.emptyPParamsUpdate
emptyPPUpdate (Mary _) = ShelleyPP.emptyPParamsUpdate
emptyPPUpdate (Alonzo _) = AlonzoPP.emptyPParamsUpdate
emptyPPUpdate (Babbage _) = BabbagePP.emptyPParamsUpdate
emptyPPUpdate (Conway _) = ConwayPP.emptyPParamsUpdate
emptyPP :: Proof era -> Core.PParams era
emptyPP (Shelley _) = ShelleyPP.emptyPParams
emptyPP (Allegra _) = ShelleyPP.emptyPParams
emptyPP (Mary _) = ShelleyPP.emptyPParams
emptyPP (Alonzo _) = AlonzoPP.emptyPParams
emptyPP (Babbage _) = BabbagePP.emptyPParams
emptyPP (Conway _) = ConwayPP.emptyPParams
{-------------------------------------------------------------------------------
ShelleyLedgerExamples
-------------------------------------------------------------------------------}
data ResultExamples era = ResultExamples
{ sreProof :: Proof era,
srePParams :: Core.PParams era,
sreProposedPPUpdates :: ProposedPPUpdates era,
srePoolDistr :: PoolDistr (Cardano.Ledger.Era.Crypto era),
sreNonMyopicRewards ::
Map
(Either Coin (Credential 'Staking (Cardano.Ledger.Era.Crypto era)))
(Map (KeyHash 'StakePool (Cardano.Ledger.Era.Crypto era)) Coin),
sreShelleyGenesis :: ShelleyGenesis era
}
data LedgerExamples era = LedgerExamples
{ sleProof :: Proof era,
sleBlock :: Block (BHeader (Era.Crypto era)) era,
sleHashHeader :: HashHeader (Cardano.Ledger.Era.Crypto era),
sleTx :: Core.Tx era,
sleApplyTxError :: ApplyTxError era,
sleRewardsCredentials :: Set (Either Coin (Credential 'Staking (Cardano.Ledger.Era.Crypto era))),
sleResultExamples :: ResultExamples era,
sleNewEpochState :: NewEpochState era,
sleChainDepState :: ChainDepState (Cardano.Ledger.Era.Crypto era),
sleTranslationContext :: TranslationContext era
}
-- ============================================================
defaultLedgerExamples :: forall era.
( Reflect era,
Default (StashedAVVMAddresses era),
Default (State (Core.EraRule "PPUP" era))
) =>
Proof era ->
(Core.TxBody era -> KeyPairWits era -> Core.Witnesses era) ->
(ShelleyTx era -> Core.Tx era) ->
Core.Value era ->
Core.TxBody era ->
Core.AuxiliaryData era ->
TranslationContext era ->
LedgerExamples era
defaultLedgerExamples proof mkWitnesses mkAlonzoTx value txBody auxData translationContext =
LedgerExamples
{ sleProof = proof,
sleBlock = exampleLedgerBlock proof tx, -- (mkAlonzoTx tx),
sleHashHeader = exampleHashHeader proof,
sleTx = tx,
sleApplyTxError =
ApplyTxError
[ case proof of
Shelley _ -> DelegsFailure $ DelegateeNotRegisteredDELEG @era (mkKeyHash 1)
Allegra _ -> DelegsFailure $ DelegateeNotRegisteredDELEG @era (mkKeyHash 1)
Mary _ -> DelegsFailure $ DelegateeNotRegisteredDELEG @era (mkKeyHash 1)
Alonzo _ -> DelegsFailure $ DelegateeNotRegisteredDELEG @era (mkKeyHash 1)
Babbage _ -> DelegsFailure $ DelegateeNotRegisteredDELEG @era (mkKeyHash 1)
Conway _ -> DelegsFailure $ DelegateeNotRegisteredDELEG @era (mkKeyHash 1)
],
sleRewardsCredentials =
Set.fromList
[ Left (Coin 100),
Right (ScriptHashObj (mkScriptHash 1)),
Right (KeyHashObj (mkKeyHash 2))
],
sleResultExamples = resultExamples,
sleNewEpochState =
exampleNewEpochState
proof
value
undefined -- (emptyPP proof)
undefined, -- ((emptyPP proof) {_minUTxOValue = Coin 1}),
sleChainDepState = exampleLedgerChainDepState 1,
sleTranslationContext = translationContext
}
where
tx = exampleTx proof mkWitnesses txBody auxData
resultExamples =
ResultExamples
{ sreProof =proof,
srePParams = (case proof of
Shelley _ -> def
Allegra _ -> def
Mary _ -> def
Alonzo _ -> def
Babbage _ -> def
Conway _ -> def) ,
sreProposedPPUpdates = exampleProposedPParamsUpdates proof,
srePoolDistr = examplePoolDistr,
sreNonMyopicRewards = exampleNonMyopicRewards,
sreShelleyGenesis = testShelleyGenesis
}
-- ============================================
mkKeyHash :: forall c discriminator. CC.Crypto c => Int -> KeyHash discriminator c
mkKeyHash = KeyHash . mkDummyHash (Proxy @(ADDRHASH c))
mkScriptHash :: forall c. CC.Crypto c => Int -> ScriptHash c
mkScriptHash = ScriptHash . mkDummyHash (Proxy @(ADDRHASH c))
mkDummyHash :: forall h a. HashAlgorithm h => Proxy h -> Int -> Hash.Hash h a
mkDummyHash _ = coerce . hashWithSerialiser @h toCBOR
mkDummySafeHash :: forall c a. CC.Crypto c => Proxy c -> Int -> SafeHash c a
mkDummySafeHash _ =
unsafeMakeSafeHash
. mkDummyHash (Proxy @(HASH c))
exampleLedgerBlock ::
forall era.
( Reflect era
-- EraSegWits era
) =>
Proof era ->
Core.Tx era ->
Block (BHeader (Era.Crypto era)) era
exampleLedgerBlock proof tx = specialize @EraSegWits proof (Block blockHeader blockBody)
where
keys :: AllIssuerKeys (Cardano.Ledger.Era.Crypto era) 'StakePool
keys = exampleKeys
(_, (hotKey, _)) = head $ hot keys
KeyPair vKeyCold _ = cold keys
blockHeader :: BHeader (Cardano.Ledger.Era.Crypto era)
blockHeader = BHeader blockHeaderBody (signedKES () 0 blockHeaderBody hotKey)
blockHeaderBody :: BHBody (Cardano.Ledger.Era.Crypto era)
blockHeaderBody =
BHBody
{ bheaderBlockNo = BlockNo 3,
bheaderSlotNo = SlotNo 9,
bheaderPrev = BlockHash (HashHeader (mkDummyHash Proxy 2)),
bheaderVk = coerceKeyRole vKeyCold,
bheaderVrfVk = snd $ vrf keys,
bheaderEta = mkCertifiedVRF (mkBytes 0) (fst $ vrf keys),
bheaderL = mkCertifiedVRF (mkBytes 1) (fst $ vrf keys),
bsize = 2345,
bhash = specialize @EraSegWits proof (hashTxSeq @era blockBody),
bheaderOCert = mkOCert keys 0 (KESPeriod 0),
bprotver = ProtVer 2 0
}
blockBody = specialize @EraSegWits proof (toTxSeq @era (StrictSeq.fromList [tx]))
mkBytes :: Int -> Cardano.Ledger.BaseTypes.Seed
mkBytes = Seed . mkDummyHash (Proxy @Blake2b_256)
exampleKeys :: forall c r. CC.Crypto c => AllIssuerKeys c r
exampleKeys =
AllIssuerKeys
coldKey
(mkVRFKeyPair (Proxy @c) 1)
[(KESPeriod 0, mkKESKeyPair (RawSeed 1 0 0 0 3))]
(hashKey (vKey coldKey))
where
coldKey = mkDSIGNKeyPair 1
mkVRFKeyPair ::
forall c.
VRFAlgorithm (VRF c) =>
Proxy c ->
Word8 ->
(Cardano.Ledger.Keys.SignKeyVRF c, Cardano.Ledger.Keys.VerKeyVRF c)
mkVRFKeyPair _ byte = (sk, VRF.deriveVerKeyVRF sk)
where
seed =
Seed.mkSeedFromBytes $
Strict.replicate
(fromIntegral (VRF.seedSizeVRF (Proxy @(VRF c))))
byte
sk = VRF.genKeyVRF seed
-- | @mkKeyPair'@ from @Test.Cardano.Ledger.Shelley.Utils@ doesn't work for real
-- crypto:
-- <https://github.com/input-output-hk/cardano-ledger/issues/1770>
mkDSIGNKeyPair ::
forall c kd.
DSIGNAlgorithm (DSIGN c) =>
Word8 ->
KeyPair kd c
mkDSIGNKeyPair byte = KeyPair (VKey $ DSIGN.deriveVerKeyDSIGN sk) sk
where
seed =
Seed.mkSeedFromBytes $
Strict.replicate
(fromIntegral (DSIGN.seedSizeDSIGN (Proxy @(DSIGN c))))
byte
sk = DSIGN.genKeyDSIGN seed
exampleHashHeader :: forall era. Reflect era =>
Proof era ->
HashHeader (Cardano.Ledger.Era.Crypto era)
exampleHashHeader proof = coerce $ mkDummyHash (Proxy @(HASH (Cardano.Ledger.Era.Crypto era))) 0
exampleProposedPParamsUpdates ::
( Reflect era
) =>
Proof era ->
ProposedPPUpdates era
exampleProposedPParamsUpdates proof@(Shelley _) =
ProposedPPUpdates $ Map.singleton
(mkKeyHash 0)
((emptyPPUpdate proof) {_keyDeposit = SJust (Coin 100)})
exampleProposedPParamsUpdates proof@(Allegra _) =
ProposedPPUpdates $ Map.singleton
(mkKeyHash 0)
((emptyPPUpdate proof) {_keyDeposit = SJust (Coin 100)})
exampleProposedPParamsUpdates proof@(Mary _) =
ProposedPPUpdates $ Map.singleton
(mkKeyHash 0)
((emptyPPUpdate proof) {_keyDeposit = SJust (Coin 100)})
exampleProposedPParamsUpdates proof@(Alonzo _) =
ProposedPPUpdates $ Map.singleton
(mkKeyHash 1)
((emptyPPUpdate proof) {AlonzoPP._maxBHSize = SJust 4000})
exampleProposedPParamsUpdates proof@(Babbage _) =
ProposedPPUpdates $ Map.singleton
(mkKeyHash 1)
((emptyPPUpdate proof) {BabbagePP._maxBHSize = SJust 4000})
exampleProposedPParamsUpdates proof@(Conway _) =
ProposedPPUpdates $ Map.singleton
(mkKeyHash 1)
((emptyPPUpdate proof) {ConwayPP._maxBHSize = SJust 4000})
exampleNonMyopicRewards ::
forall c.
CC.Crypto c =>
Map
(Either Coin (Credential 'Staking c))
(Map (KeyHash 'StakePool c) Coin)
exampleNonMyopicRewards =
Map.fromList
[ (Left (Coin 100), Map.singleton (mkKeyHash 2) (Coin 3)),
(Right (ScriptHashObj (mkScriptHash 1)), Map.empty),
(Right (KeyHashObj (mkKeyHash 2)), Map.singleton (mkKeyHash 3) (Coin 9))
]
-- =====================================================================
-- | The EpochState has a field which is (PParams era). We need these
-- fields, a subset of the fields in PParams, in: startStep and createRUpd.
type UsesPP era =
( HasField "_d" (Core.PParams era) UnitInterval,
HasField "_tau" (Core.PParams era) UnitInterval,
HasField "_a0" (Core.PParams era) NonNegativeInterval,
HasField "_rho" (Core.PParams era) UnitInterval,
HasField "_nOpt" (Core.PParams era) Natural,
HasField "_protocolVersion" (Core.PParams era) ProtVer
)
-- | This is probably not a valid ledger. We don't care, we are only
-- interested in serialisation, not validation.
exampleNewEpochState ::
forall era.
( Reflect era,
Default (StashedAVVMAddresses era),
Default (State (Core.EraRule "PPUP" era)),
Core.EraTxOut era
) =>
Proof era ->
Core.Value era ->
Core.PParams era ->
Core.PParams era ->
NewEpochState era
exampleNewEpochState proof value ppp pp =
NewEpochState
{ nesEL = EpochNo 0,
nesBprev = BlocksMade (Map.singleton (mkKeyHash 1) 10),
nesBcur = BlocksMade (Map.singleton (mkKeyHash 2) 3),
nesEs = epochState,
nesRu = SJust rewardUpdate,
nesPd = examplePoolDistr,
stashedAVVMAddresses = def
}
where
epochState :: EpochState era
epochState =
EpochState
{ esAccountState =
AccountState
{ _treasury = Coin 10000,
_reserves = Coin 1000
},
esSnapshots = emptySnapShots,
esLState =
LedgerState
{ lsUTxOState =
UTxOState
{ _utxo =
UTxO $
Map.fromList
[ ( TxIn (TxId (mkDummySafeHash Proxy 1)) minBound,
Core.mkBasicTxOut addr value
)
],
_deposited = Coin 1000,
_fees = Coin 1,
_ppups = def,
_stakeDistro = mempty
},
lsDPState = def
},
esPrevPp = ppp,
esPp = pp,
esNonMyopic = def
}
where
addr :: Addr (Cardano.Ledger.Era.Crypto era)
addr =
Addr
Testnet
(keyToCredential examplePayKey)
(StakeRefBase (keyToCredential exampleStakeKey))
rewardUpdate :: PulsingRewUpdate (Era.Crypto era)
rewardUpdate = case proof of
Shelley _ -> step
Allegra _ -> step
Mary _ -> step
Alonzo _ -> step
Babbage _ -> step
Conway _ -> step
step :: UsesPP era => PulsingRewUpdate (Era.Crypto era)
step = (startStep @era
(EpochSize 432000)
(BlocksMade (Map.singleton (mkKeyHash 1) 10))
epochState
(Coin 45)
(activeSlotCoeff testGlobals)
10)
keyToCredential :: CC.Crypto c => KeyPair r c -> Credential r c
keyToCredential = KeyHashObj . hashKey . vKey
examplePayKey :: CC.Crypto c => KeyPair 'Payment c
examplePayKey = mkDSIGNKeyPair 0
exampleStakeKey :: CC.Crypto c => KeyPair 'Staking c
exampleStakeKey = mkDSIGNKeyPair 1
examplePoolDistr :: forall c. PraosCrypto c => PoolDistr c
examplePoolDistr =
PoolDistr $
Map.fromList
[ ( mkKeyHash 1,
IndividualPoolStake
1
(hashVerKeyVRF (snd (vrf (exampleKeys @c))))
)
]
exampleLedgerChainDepState :: forall c. CC.Crypto c => Word64 -> ChainDepState c
exampleLedgerChainDepState seed =
ChainDepState
{ csProtocol =
PrtclState
( Map.fromList
[ (mkKeyHash 1, 1),
(mkKeyHash 2, 2)
]
)
(mkNonceFromNumber seed)
(mkNonceFromNumber seed),
csTickn =
TicknState
NeutralNonce
(mkNonceFromNumber seed),
csLabNonce =
mkNonceFromNumber seed
}
-- | This is not a valid transaction. We don't care, we are only interested in
-- serialisation, not validation.
exampleTx ::
forall era.
( Reflect era,
Core.EraTx era
) =>
Proof era ->
(Core.TxBody era -> KeyPairWits era -> Core.Witnesses era) ->
Core.TxBody era ->
Core.AuxiliaryData era ->
Core.Tx era
exampleTx proof mkWitnesses txBody auxData =
-- ShelleyTx txBody (mkWitnesses txBody keyPairWits) (SJust auxData)
Core.mkBasicTx txBody
where
keyPairWits :: KeyPairWits era
keyPairWits =
[ asWitness examplePayKey,
asWitness exampleStakeKey,
asWitness $ cold (exampleKeys @(Cardano.Ledger.Era.Crypto era) @'StakePool)
]
-- ==========================================
testShelleyGenesis = undefined
-- | Specialize ('action' :: (constraint era => t)) to all known 'era', because
-- we know (constraint era) holds for all known era. In order for this to work
-- it is best to type apply 'specialize' to a concrete constraint. So a call site
-- looks like '(specialize @EraSegWits proof action). This way the constraint does
-- not percolate upwards, past the call site of 'action'
specialize :: forall constraint era t .
( constraint (ShelleyEra (Era.Crypto era)),
constraint (AllegraEra (Era.Crypto era)),
constraint (MaryEra (Era.Crypto era)),
constraint (AlonzoEra (Era.Crypto era)),
constraint (BabbageEra (Era.Crypto era)),
constraint (ConwayEra (Era.Crypto era))
) => Proof era -> (constraint era => t) -> t
specialize proof action =
case proof of
Shelley _ -> action
Allegra _ -> action
Mary _ -> action
Alonzo _ -> action
Babbage _ -> action
Conway _ -> action