-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathUtxo.hs
492 lines (442 loc) · 17.9 KB
/
Utxo.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
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DerivingVia #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
module Cardano.Ledger.Babbage.Rules.Utxo where
import Cardano.Binary (FromCBOR (..), ToCBOR (..), serialize)
import Cardano.Ledger.Address (bootstrapAddressAttrsSize)
import Cardano.Ledger.Alonzo.Rules.Utxo
( UtxoEvent (..),
UtxoPredicateFailure (..),
utxoPredFailMaToAlonzo,
utxoPredFailShelleyToAlonzo,
validateCollateralContainsNonADA,
validateExUnitsTooBigUTxO,
validateInsufficientCollateral,
validateOutsideForecast,
validateScriptsNotPaidUTxO,
validateTooManyCollateralInputs,
validateWrongNetworkInTxBody,
)
import Cardano.Ledger.Alonzo.Rules.Utxos (UtxosPredicateFailure (..))
import Cardano.Ledger.Alonzo.Rules.Utxow (UtxowPredicateFail (WrappedShelleyEraFailure))
import Cardano.Ledger.Alonzo.Scripts (Prices)
import Cardano.Ledger.Alonzo.Tx (ValidatedTx (..), minfee)
import Cardano.Ledger.Alonzo.TxInfo (ExtendedUTxO (allOuts))
import Cardano.Ledger.Alonzo.TxWitness (Redeemers, TxWitness (..), nullRedeemers)
import Cardano.Ledger.Babbage.Collateral
import Cardano.Ledger.Babbage.PParams (PParams' (..))
import Cardano.Ledger.Babbage.Rules.Utxos (BabbageUTXOS, ConcreteBabbage)
import Cardano.Ledger.Babbage.TxBody
( TxBody (..),
TxOut,
txfee',
)
import Cardano.Ledger.BaseTypes
( ShelleyBase,
epochInfoWithErr,
networkId,
systemStart,
)
import Cardano.Ledger.Coin (Coin (..))
import qualified Cardano.Ledger.Core as Core
import Cardano.Ledger.Era (Era (..), ValidateScript (..), getTxOutBootstrapAddress)
import Cardano.Ledger.Hashes (ScriptHash)
import Cardano.Ledger.Rules.ValidationMode
( Inject (..),
Test,
runTest,
runTestOnSignal,
)
import qualified Cardano.Ledger.Shelley.LedgerState as Shelley
import qualified Cardano.Ledger.Shelley.Rules.Utxo as Shelley
import Cardano.Ledger.Shelley.Rules.Utxow (UtxowPredicateFailure)
import Cardano.Ledger.Shelley.UTxO (UTxO (..))
import qualified Cardano.Ledger.ShelleyMA.Rules.Utxo as ShelleyMA
( UtxoPredicateFailure,
validateOutsideValidityIntervalUTxO,
validateTriesToForgeADA,
validateValueNotConservedUTxO,
)
import Cardano.Ledger.TxIn (TxIn)
import qualified Cardano.Ledger.Val as Val
import Control.Monad (unless)
import Control.Monad.Trans.Reader (asks)
import Control.State.Transition.Extended
( Embed (..),
STS (..),
TRC (..),
TransitionRule,
judgmentContext,
liftSTS,
trans,
)
import Data.Bifunctor (first)
import qualified Data.ByteString.Lazy as BSL
import Data.Coders
import Data.Coerce (coerce)
import qualified Data.Compact.SplitMap as SplitMap
import Data.Foldable (Foldable (foldl'), sequenceA_)
import Data.List.NonEmpty (NonEmpty)
import Data.Maybe.Strict (StrictMaybe (..))
import Data.Set (Set)
import Data.Typeable (Typeable)
import GHC.Natural (Natural)
import GHC.Records (HasField (getField))
import NoThunks.Class (InspectHeapNamed (..), NoThunks (..))
import Validation
-- ======================================================
data BabbageUTXO era
-- | Predicate failure for the Babbage Era
data BabbageUtxoPred era
= FromAlonzoUtxoFail !(UtxoPredicateFailure era) -- Inherited from Alonzo
| FromAlonzoUtxowFail !(UtxowPredicateFail era)
| -- | The collateral is not equivalent to the total collateral asserted by the transaction
UnequalCollateralReturn
!Coin
-- ^ collateral needed
!Coin
-- ^ collateral returned
| -- | the set of malformed scripts
MalformedScripts
!(Set (ScriptHash (Crypto era)))
| -- | list of supplied transaction outputs that are too small,
-- together with the minimum value for the given output.
BabbageOutputTooSmallUTxO
![(Core.TxOut era, Integer)]
deriving instance
( Era era,
Show (UtxoPredicateFailure era),
Show (PredicateFailure (Core.EraRule "UTXO" era)),
Show (Core.TxOut era),
Show (Core.Script era)
) =>
Show (BabbageUtxoPred era)
deriving instance
( Era era,
Eq (UtxoPredicateFailure era),
Eq (PredicateFailure (Core.EraRule "UTXO" era)),
Eq (Core.TxOut era),
Eq (Core.Script era)
) =>
Eq (BabbageUtxoPred era)
-- ===============================================
-- Inject instances
instance Inject (UtxoPredicateFailure era) (BabbageUtxoPred era) where
inject = FromAlonzoUtxoFail
instance Inject (UtxowPredicateFail era) (BabbageUtxoPred era) where
inject = FromAlonzoUtxowFail
instance Inject (BabbageUtxoPred era) (BabbageUtxoPred era) where
inject = id
instance
Inject (PredicateFailure (Core.EraRule "PPUP" era)) (PredicateFailure (Core.EraRule "UTXOS" era)) =>
Inject (ShelleyMA.UtxoPredicateFailure era) (BabbageUtxoPred era)
where
inject = FromAlonzoUtxoFail . utxoPredFailMaToAlonzo
instance
Inject (PredicateFailure (Core.EraRule "PPUP" era)) (PredicateFailure (Core.EraRule "UTXOS" era)) =>
Inject (Shelley.UtxoPredicateFailure era) (BabbageUtxoPred era)
where
inject = FromAlonzoUtxoFail . utxoPredFailShelleyToAlonzo
instance Inject (UtxowPredicateFailure era) (BabbageUtxoPred era) where
inject = FromAlonzoUtxowFail . WrappedShelleyEraFailure
-- =======================================================
-- | feesOK is a predicate with several parts. Some parts only apply in special circumstances.
-- 1) The fee paid is >= the minimum fee
-- 2) If the total ExUnits are 0 in both Memory and Steps, no further part needs to be checked.
-- 3) The collateral consists only of VKey addresses
-- 4) The collateral inputs do not contain any non-ADA part
-- 5) The collateral is sufficient to cover the appropriate percentage of the
-- fee marked in the transaction
-- 6) The collateral is equivalent to total collateral asserted by the transaction
-- 7) There is at least one collateral input
--
-- feesOK can differ from Era to Era, as new notions of fees arise. This is the Babbage version
-- See: Figure 2: Functions related to fees and collateral, in the Babbage specification
-- In the spec feesOK is a boolean function. Because wee need to handle predicate failures
-- in the implementaion, it is coded as a Test. Which is a validation.
-- This version is generic in that it can be lifted to any PredicateFailure type that
-- embeds BabbageUtxoPred era. This makes it possibly useful in future Eras.
feesOK ::
forall era.
( Era era,
Core.Tx era ~ ValidatedTx era,
Core.TxBody era ~ TxBody era,
-- "collateral" to get inputs to pay the fees
HasField "collateral" (Core.TxBody era) (Set (TxIn (Crypto era))),
HasField "_minfeeA" (Core.PParams era) Natural,
HasField "_minfeeB" (Core.PParams era) Natural,
HasField "_collateralPercentage" (Core.PParams era) Natural,
HasField "collateralReturn" (Core.TxBody era) (StrictMaybe (TxOut era)),
HasField "_prices" (Core.PParams era) Prices,
HasField "txrdmrs" (Core.Witnesses era) (Redeemers era),
HasField "totalCollateral" (Core.TxBody era) (StrictMaybe Coin)
) =>
Core.PParams era ->
Core.Tx era ->
UTxO era ->
Test (BabbageUtxoPred era)
feesOK pp tx u@(UTxO utxo) =
let txb = getField @"body" tx
collateral' = getField @"collateral" txb -- Inputs allocated to pay txfee
-- restrict Utxo to those inputs we use to pay fees.
-- (collateral ◁ utxo)
utxoCollateral = collateral' SplitMap.◁ utxo
bal = collBalance txb u
theFee = txfee' txb -- Coin supplied to pay fees
minimumFee = minfee @era pp tx
in sequenceA_
[ -- Part 1: minfee pp tx ≤ txfee txb
failureUnless (minimumFee <= theFee) (inject (FeeTooSmallUTxO @era minimumFee theFee)),
-- Part 2: (txrdmrs tx ≠ ∅ ⇒ validateCollateral)
unless (nullRedeemers . txrdmrs' . wits $ tx) $
validateTotalCollateral pp txb utxoCollateral bal
]
validateTotalCollateral ::
forall era.
( Era era,
HasField "_collateralPercentage" (Core.PParams era) Natural,
HasField "totalCollateral" (Core.TxBody era) (StrictMaybe Coin)
) =>
Core.PParams era ->
Core.TxBody era ->
SplitMap.SplitMap (TxIn (Crypto era)) (Core.TxOut era) ->
Core.Value era ->
Test (BabbageUtxoPred era)
validateTotalCollateral pp txb utxoCollateral bal =
sequenceA_
[ -- Part 3: (∀(a,_,_) ∈ range (collateral txb ◁ utxo), a ∈ Addrvkey)
fromAlonzoValidation $ validateScriptsNotPaidUTxO utxoCollateral,
-- Part 4: isAdaOnly balance
fromAlonzoValidation $ validateCollateralContainsNonADA @era bal,
-- Part 5: balance ≥ ⌈txfee txb ∗ (collateralPercent pp) / 100⌉
fromAlonzoValidation $ validateInsufficientCollateral pp txb bal,
-- Part 6: (txcoll tx ≠ ◇) ⇒ balance = txcoll tx
validateCollateralEqBalance (Val.coin bal) (getField @"totalCollateral" txb),
-- Part 7: collInputs tx ≠ ∅
fromAlonzoValidation $ failureIf (null utxoCollateral) (NoCollateralInputs @era)
]
where
fromAlonzoValidation x = first (fmap inject) x
-- > (txcoll tx ≠ ◇) => balance == txcoll tx
validateCollateralEqBalance :: Coin -> StrictMaybe Coin -> Validation (NonEmpty (BabbageUtxoPred era)) ()
validateCollateralEqBalance bal txcoll =
case txcoll of
SNothing -> pure ()
SJust tc -> failureUnless (bal == tc) (UnequalCollateralReturn bal tc)
-- > getValue txout ≥ inject ( ⌈ serSize txout ∗ coinsPerUTxOWord pp / 8 ⌉ )
validateOutputTooSmallUTxO ::
( Era era,
ToCBOR (Core.TxOut era),
HasField "_coinsPerUTxOWord" (Core.PParams era) Coin
) =>
Core.PParams era ->
[Core.TxOut era] ->
Test (BabbageUtxoPred era)
validateOutputTooSmallUTxO pp outs = failureUnless (null outputsTooSmall) $ BabbageOutputTooSmallUTxO outputsTooSmall
where
Coin coinsPerUTxOWord = getField @"_coinsPerUTxOWord" pp
serSize = fromIntegral . BSL.length . serialize
outs' = map (\out -> (out, (serSize out * coinsPerUTxOWord + 7) `div` 8)) outs
outputsTooSmall =
filter
( \(out, minSize) ->
let v = getField @"value" out
in -- pointwise is used because non-ada amounts must be >= 0 too
not $
Val.pointwise
(>=)
v
(Val.inject . Coin $ minSize)
)
outs'
-- > serSize (getValue txout) ≤ maxValSize pp
validateOutputTooBigUTxO ::
( HasField "_maxValSize" (Core.PParams era) Natural,
HasField "value" (Core.TxOut era) (Core.Value era),
ToCBOR (Core.Value era)
) =>
Core.PParams era ->
[Core.TxOut era] ->
Test (UtxoPredicateFailure era)
validateOutputTooBigUTxO pp outs =
failureUnless (null outputsTooBig) $ OutputTooBigUTxO outputsTooBig
where
maxValSize = getField @"_maxValSize" pp
outputsTooBig = foldl' accum [] outs
accum ans out =
let v = getField @"value" out
serSize = fromIntegral $ BSL.length $ serialize v
in if serSize > maxValSize
then (fromIntegral serSize, fromIntegral maxValSize, out) : ans
else ans
-- > a ∈ Addr_bootstrap ⇒ bootstrapAttrsSize a ≤ 64
validateOutputBootAddrAttrsTooBig ::
Era era =>
[Core.TxOut era] ->
Test (UtxoPredicateFailure era)
validateOutputBootAddrAttrsTooBig outs =
failureUnless (null outputsAttrsTooBig) $ OutputBootAddrAttrsTooBig outputsAttrsTooBig
where
outputsAttrsTooBig =
filter
( \txOut ->
case getTxOutBootstrapAddress txOut of
Just addr -> bootstrapAddressAttrsSize addr > 64
_ -> False
)
outs
-- | The UTxO transition rule for the Babbage eras.
utxoTransition ::
forall era.
( Era era,
ValidateScript era,
ConcreteBabbage era, -- Unlike the Tests, we are only going to use this once, so we fix the Core.XX types
STS (BabbageUTXO era),
-- In this function we we call the UTXOS rule, so we need some assumptions
Embed (Core.EraRule "UTXOS" era) (BabbageUTXO era),
Environment (Core.EraRule "UTXOS" era) ~ Shelley.UtxoEnv era,
State (Core.EraRule "UTXOS" era) ~ Shelley.UTxOState era,
Signal (Core.EraRule "UTXOS" era) ~ Core.Tx era,
Inject (PredicateFailure (Core.EraRule "PPUP" era)) (PredicateFailure (Core.EraRule "UTXOS" era)),
ExtendedUTxO era
) =>
TransitionRule (BabbageUTXO era)
utxoTransition = do
TRC (Shelley.UtxoEnv slot pp stakepools _genDelegs, u, tx) <- judgmentContext
let Shelley.UTxOState utxo _deposits _fees _ppup _ = u
{- txb := txbody tx -}
let txb = body tx
allInputs = getAllTxInputs txb
{- ininterval slot (txvld txb) -}
runTest $
ShelleyMA.validateOutsideValidityIntervalUTxO slot txb
sysSt <- liftSTS $ asks systemStart
ei <- liftSTS $ asks epochInfoWithErr
{- epochInfoSlotToUTCTime epochInfo systemTime i_f ≠ ◇ -}
runTest $ validateOutsideForecast ei sysSt tx
{- txins txb ≠ ∅ -}
runTestOnSignal $ Shelley.validateInputSetEmptyUTxO txb
{- feesOK pp tx utxo -}
runTest $ feesOK pp tx utxo -- Generalizes the fee to small from earlier Era's
{- allInputs = spendInputs txb ∪ collInputs txb ∪ refInputs txb -}
{- (spendInputs txb ∪ collInputs txb ∪ refInputs txb) ⊆ dom utxo -}
runTest $
Shelley.validateBadInputsUTxO utxo allInputs
{- consumed pp utxo txb = produced pp poolParams txb -}
runTest $
ShelleyMA.validateValueNotConservedUTxO pp utxo stakepools txb
{- adaID ∉ supp mint tx -}
runTestOnSignal $
ShelleyMA.validateTriesToForgeADA txb
let outs = allOuts txb
{- ∀ txout ∈ allOuts txb, getValue txout ≥ inject ⌈ uxoEntrySize txout ∗ coinsPerUTxOWord p / 8 ⌉ -}
runTest $ validateOutputTooSmallUTxO pp outs
{- ∀ txout ∈ allOuts txb, serSize (getValue txout) ≤ maxValSize pp -}
runTest $ validateOutputTooBigUTxO pp outs
{- ∀ ( _ ↦ (a,_)) ∈ allOuts txb, a ∈ Addrbootstrap → bootstrapAttrsSize a ≤ 64 -}
runTestOnSignal $
validateOutputBootAddrAttrsTooBig outs
netId <- liftSTS $ asks networkId
{- ∀(_ → (a, _)) ∈ allOuts txb, netId a = NetworkId -}
runTestOnSignal $ Shelley.validateWrongNetwork netId outs
{- ∀(a → ) ∈ txwdrls txb, netId a = NetworkId -}
runTestOnSignal $ Shelley.validateWrongNetworkWithdrawal netId txb
{- (txnetworkid txb = NetworkId) ∨ (txnetworkid txb = ◇) -}
runTestOnSignal $ validateWrongNetworkInTxBody netId txb
{- txsize tx ≤ maxTxSize pp -}
runTestOnSignal $ Shelley.validateMaxTxSizeUTxO pp tx
{- totExunits tx ≤ maxTxExUnits pp -}
runTest $ validateExUnitsTooBigUTxO pp tx
{- ‖collateral tx‖ ≤ maxCollInputs pp -}
runTest $ validateTooManyCollateralInputs pp txb
trans @(Core.EraRule "UTXOS" era) =<< coerce <$> judgmentContext
--------------------------------------------------------------------------------
-- BabbageUTXO STS
--------------------------------------------------------------------------------
instance
forall era.
( ValidateScript era,
Era era,
ValidateScript era,
ConcreteBabbage era, -- Unlike the Tests, we are only going to use this once, so we fix the Core.XX types
Core.Tx era ~ ValidatedTx era,
Core.Witnesses era ~ TxWitness era,
-- instructions for calling UTXOS from BabbageUTXO
Embed (Core.EraRule "UTXOS" era) (BabbageUTXO era),
Environment (Core.EraRule "UTXOS" era) ~ Shelley.UtxoEnv era,
State (Core.EraRule "UTXOS" era) ~ Shelley.UTxOState era,
Signal (Core.EraRule "UTXOS" era) ~ Core.Tx era,
Inject (PredicateFailure (Core.EraRule "PPUP" era)) (PredicateFailure (Core.EraRule "UTXOS" era)),
PredicateFailure (Core.EraRule "UTXO" era) ~ BabbageUtxoPred era,
ExtendedUTxO era
) =>
STS (BabbageUTXO era)
where
type State (BabbageUTXO era) = Shelley.UTxOState era
type Signal (BabbageUTXO era) = ValidatedTx era
type Environment (BabbageUTXO era) = Shelley.UtxoEnv era
type BaseM (BabbageUTXO era) = ShelleyBase
type PredicateFailure (BabbageUTXO era) = BabbageUtxoPred era
type Event (BabbageUTXO era) = UtxoEvent era
initialRules = []
transitionRules = [utxoTransition]
instance
( Era era,
STS (BabbageUTXOS era),
PredicateFailure (Core.EraRule "UTXOS" era) ~ UtxosPredicateFailure era,
Event (Core.EraRule "UTXOS" era) ~ Event (BabbageUTXOS era)
) =>
Embed (BabbageUTXOS era) (BabbageUTXO era)
where
wrapFailed = FromAlonzoUtxoFail . UtxosFailure
wrapEvent = UtxosEvent
-- ============================================
-- CBOR for Predicate faiure type
instance
( Era era,
Typeable era,
ToCBOR (Core.TxOut era),
ToCBOR (Core.Value era),
ToCBOR (PredicateFailure (Core.EraRule "UTXOS" era)),
ToCBOR (PredicateFailure (Core.EraRule "UTXO" era)),
ToCBOR (Core.Script era),
Typeable (Core.AuxiliaryData era)
) =>
ToCBOR (BabbageUtxoPred era)
where
toCBOR pf = encode (work pf)
where
work (FromAlonzoUtxoFail x) = Sum FromAlonzoUtxoFail 1 !> To x
work (FromAlonzoUtxowFail x) = Sum FromAlonzoUtxowFail 2 !> To x
work (UnequalCollateralReturn c1 c2) = Sum UnequalCollateralReturn 3 !> To c1 !> To c2
work (MalformedScripts x) = Sum MalformedScripts 4 !> To x
work (BabbageOutputTooSmallUTxO x) = Sum BabbageOutputTooSmallUTxO 5 !> To x
instance
( Era era,
Typeable era,
FromCBOR (Core.TxOut era),
FromCBOR (Core.Value era),
FromCBOR (PredicateFailure (Core.EraRule "UTXOS" era)),
FromCBOR (PredicateFailure (Core.EraRule "UTXO" era)),
Typeable (Core.Script era),
Typeable (Core.AuxiliaryData era)
) =>
FromCBOR (BabbageUtxoPred era)
where
fromCBOR = decode (Summands "BabbageUtxoPred" work)
where
work 1 = SumD FromAlonzoUtxoFail <! From
work 2 = SumD FromAlonzoUtxowFail <! From
work 3 = SumD UnequalCollateralReturn <! From <! From
work 4 = SumD MalformedScripts <! From
work 5 = SumD BabbageOutputTooSmallUTxO <! From
work n = Invalid n
deriving via InspectHeapNamed "BabbageUtxoPred" (BabbageUtxoPred era) instance NoThunks (BabbageUtxoPred era)