-
Notifications
You must be signed in to change notification settings - Fork 155
/
Evaluate.hs
248 lines (230 loc) · 9.3 KB
/
Evaluate.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
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
module Cardano.Ledger.Alonzo.Plutus.Evaluate (
evalPlutusScripts,
evalPlutusScriptsWithLogs,
CollectError (..),
collectPlutusScriptsWithContext,
lookupPlutusScript,
)
where
import Cardano.Ledger.Alonzo.Core
import Cardano.Ledger.Alonzo.Plutus.Context (EraPlutusContext (..))
import Cardano.Ledger.Alonzo.Scripts (plutusScriptLanguage, toAsItem, toAsIx)
import Cardano.Ledger.Alonzo.TxWits (lookupRedeemer)
import Cardano.Ledger.Alonzo.UTxO (AlonzoEraUTxO (getSpendingDatum), AlonzoScriptsNeeded (..))
import Cardano.Ledger.BaseTypes (ProtVer (pvMajor), kindObject, natVersion)
import Cardano.Ledger.Binary (DecCBOR (..), EncCBOR (..))
import Cardano.Ledger.Binary.Coders
import Cardano.Ledger.Plutus.CostModels (costModelsValid)
import Cardano.Ledger.Plutus.Data (fromMaybeData, getPlutusData)
import Cardano.Ledger.Plutus.Evaluate (
PlutusDatums (..),
PlutusWithContext (..),
ScriptResult (..),
runPlutusScriptWithLogs,
)
import Cardano.Ledger.Plutus.Language (Language (..))
import Cardano.Ledger.UTxO (EraUTxO (..), ScriptsProvided (..), UTxO (..))
import Cardano.Slotting.EpochInfo (EpochInfo)
import Cardano.Slotting.Time (SystemStart)
import Control.DeepSeq (NFData)
import Control.Monad (guard)
import Data.Aeson (ToJSON (..), (.=), pattern String)
import Data.List (intercalate)
import qualified Data.Map.Strict as Map
import Data.Maybe (mapMaybe)
import qualified Data.Set as Set
import Data.Text (Text)
import Debug.Trace (traceEvent)
import GHC.Generics
import Lens.Micro
import NoThunks.Class (NoThunks)
-- ===============================================================
-- From the specification, Figure 7 "Scripts and their Arguments"
-- ===============================================================
-- | When collecting inputs for two phase scripts, 3 things can go wrong.
data CollectError era
= NoRedeemer !(PlutusPurpose AsItem era)
| NoWitness !(ScriptHash (EraCrypto era))
| NoCostModel !Language
| BadTranslation !(ContextError era)
deriving (Generic)
deriving instance
(AlonzoEraScript era, Eq (ContextError era)) =>
Eq (CollectError era)
deriving instance
(AlonzoEraScript era, Show (ContextError era)) =>
Show (CollectError era)
deriving instance
(AlonzoEraScript era, NoThunks (ContextError era)) =>
NoThunks (CollectError era)
deriving instance
(AlonzoEraScript era, NFData (ContextError era)) =>
NFData (CollectError era)
instance (AlonzoEraScript era, EncCBOR (ContextError era)) => EncCBOR (CollectError era) where
encCBOR (NoRedeemer x) = encode $ Sum NoRedeemer 0 !> To x
encCBOR (NoWitness x) = encode $ Sum (NoWitness @era) 1 !> To x
encCBOR (NoCostModel x) = encode $ Sum NoCostModel 2 !> To x
encCBOR (BadTranslation x) = encode $ Sum (BadTranslation @era) 3 !> To x
instance (AlonzoEraScript era, DecCBOR (ContextError era)) => DecCBOR (CollectError era) where
decCBOR = decode (Summands "CollectError" dec)
where
dec 0 = SumD NoRedeemer <! From
dec 1 = SumD NoWitness <! From
dec 2 = SumD NoCostModel <! From
dec 3 = SumD BadTranslation <! From
dec n = Invalid n
instance
( Era era
, ToJSON (PlutusPurpose AsItem era)
, ToJSON (ContextError era)
) =>
ToJSON (CollectError era)
where
toJSON = \case
NoRedeemer sPurpose ->
kindObject "CollectError" $
[ "error" .= String "NoRedeemer"
, "plutusPurpose" .= toJSON sPurpose
]
NoWitness sHash ->
kindObject "CollectError" $
[ "error" .= String "NoWitness"
, "scriptHash" .= toJSON sHash
]
NoCostModel lang ->
kindObject "CollectError" $
[ "error" .= String "NoCostModel"
, "language" .= toJSON lang
]
BadTranslation err ->
kindObject "BadTranslation" ["error" .= toJSON err]
-- | Given a script hash and a Map of available scripts, find the PlutusScript. Returns
-- Nothing when script is missing or it is not a PlutusScript
lookupPlutusScript ::
AlonzoEraScript era =>
Map.Map (ScriptHash (EraCrypto era)) (Script era) ->
ScriptHash (EraCrypto era) ->
Maybe (PlutusScript era)
lookupPlutusScript scriptsAvailable scriptHash = do
script <- scriptHash `Map.lookup` scriptsAvailable
toPlutusScript script
collectPlutusScriptsWithContext ::
forall era.
( AlonzoEraTxBody era
, AlonzoEraTxWits era
, AlonzoEraUTxO era
, ScriptsNeeded era ~ AlonzoScriptsNeeded era
, EraPlutusContext era
) =>
EpochInfo (Either Text) ->
SystemStart ->
PParams era ->
Tx era ->
UTxO era ->
Either [CollectError era] [PlutusWithContext (EraCrypto era)]
collectPlutusScriptsWithContext epochInfo sysStart pp tx utxo =
-- TODO: remove this whole complicated check when we get into Conway. It is much simpler
-- to fail on a CostModel lookup in the `apply` function (already implemented).
let missingCostModels = Set.filter (`Map.notMember` costModels) usedLanguages
in case guard (protVerMajor < natVersion @9) >> Set.lookupMin missingCostModels of
Just l -> Left [NoCostModel l]
Nothing ->
merge
apply
(map getScriptWithRedeemer neededPlutusScripts)
(Right [])
where
-- Check on a protocol version to preserve failure mode (a single NoCostModel failure
-- for languages with missing cost models) until we are in Conway era. After we hard
-- fork into Conway it will be safe to remove this check together with the
-- `missingCostModels` lookup
--
-- We also need to pass major protocol version to the script for script evaluation
protVerMajor = pvMajor (pp ^. ppProtocolVersionL)
costModels = costModelsValid $ pp ^. ppCostModelsL
ScriptsProvided scriptsProvided = getScriptsProvided utxo tx
AlonzoScriptsNeeded scriptsNeeded = getScriptsNeeded utxo (tx ^. bodyTxL)
neededPlutusScripts =
mapMaybe (\(sp, sh) -> (,) (sh, sp) <$> lookupPlutusScript scriptsProvided sh) scriptsNeeded
usedLanguages = Set.fromList $ map (plutusScriptLanguage . snd) neededPlutusScripts
getScriptWithRedeemer ((plutusScriptHash, plutusPurpose), plutusScript) =
let redeemerIndex = hoistPlutusPurpose toAsIx plutusPurpose
in case lookupRedeemer redeemerIndex $ tx ^. witsTxL . rdmrsTxWitsL of
Just (d, exUnits) -> Right (plutusScript, plutusPurpose, d, exUnits, plutusScriptHash)
Nothing -> Left (NoRedeemer (hoistPlutusPurpose toAsItem plutusPurpose))
apply (plutusScript, plutusPurpose, d, exUnits, plutusScriptHash) = do
let lang = plutusScriptLanguage plutusScript
costModel <- maybe (Left (NoCostModel lang)) Right $ Map.lookup lang costModels
case mkPlutusScriptContext plutusScript plutusPurpose pp epochInfo sysStart utxo tx of
Right scriptContext ->
let spendingDatum = getSpendingDatum utxo tx $ hoistPlutusPurpose toAsItem plutusPurpose
datums
| protVerMajor < natVersion @9 = maybe id (:) spendingDatum [d, scriptContext]
| otherwise = [fromMaybeData spendingDatum, d, scriptContext]
in Right $
withPlutusScript plutusScript $ \plutus ->
PlutusWithContext
{ pwcProtocolVersion = protVerMajor
, pwcScript = Left plutus
, pwcScriptHash = plutusScriptHash
, pwcDatums = PlutusDatums (getPlutusData <$> datums)
, pwcExUnits = exUnits
, pwcCostModel = costModel
}
Left te -> Left $ BadTranslation te
-- | Merge two lists (the first of which may have failures, i.e. (Left _)), collect all the failures
-- but if there are none, use 'f' to construct a success.
merge :: forall t b a. (t -> Either a b) -> [Either a t] -> Either [a] [b] -> Either [a] [b]
merge _f [] answer = answer
merge f (x : xs) zs = merge f xs (gg x zs)
where
gg :: Either a t -> Either [a] [b] -> Either [a] [b]
gg (Right t) (Right cs) =
case f t of
Right c -> Right $ c : cs
Left e -> Left [e]
gg (Left a) (Right _) = Left [a]
gg (Right _) (Left cs) = Left cs
gg (Left a) (Left cs) = Left (a : cs)
-- | Evaluate a list of Plutus scripts. All scripts in the list must evaluate to `True`.
evalPlutusScripts ::
EraTx era =>
Tx era ->
[PlutusWithContext (EraCrypto era)] ->
ScriptResult (EraCrypto era)
evalPlutusScripts tx pwcs = snd $ evalPlutusScriptsWithLogs tx pwcs
evalPlutusScriptsWithLogs ::
EraTx era =>
Tx era ->
[PlutusWithContext (EraCrypto era)] ->
([Text], ScriptResult (EraCrypto era))
evalPlutusScriptsWithLogs _tx [] = mempty
evalPlutusScriptsWithLogs tx (plutusWithContext : rest) =
let beginMsg =
intercalate
","
[ "[LEDGER][PLUTUS_SCRIPT]"
, "BEGIN"
]
!res = traceEvent beginMsg $ runPlutusScriptWithLogs plutusWithContext
endMsg =
intercalate
","
[ "[LEDGER][PLUTUS_SCRIPT]"
, "END"
]
in traceEvent endMsg res <> evalPlutusScriptsWithLogs tx rest