-
Notifications
You must be signed in to change notification settings - Fork 157
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix ex unit evaluation #2380
Merged
Merged
fix ex unit evaluation #2380
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,19 +11,10 @@ import Cardano.Ledger.Alonzo.Scripts (Script (..)) | |
import Data.ByteString.Short (ShortByteString) | ||
import Data.Maybe (fromMaybe) | ||
import qualified Plutus.V1.Ledger.Api as P | ||
( EvaluationError (..), | ||
ExBudget (..), | ||
ExCPU (..), | ||
ExMemory (..), | ||
VerboseMode (..), | ||
defaultCostModelParams, | ||
evaluateScriptRestricting, | ||
) | ||
import Plutus.V1.Ledger.Examples | ||
( alwaysFailingNAryFunction, | ||
alwaysSucceedingNAryFunction, | ||
) | ||
import qualified PlutusTx as P | ||
import qualified Test.Cardano.Ledger.Alonzo.PlutusScripts as Generated | ||
( evendata3, | ||
guessTheNumber2, | ||
|
@@ -39,27 +30,24 @@ data ShouldSucceed = ShouldSucceed | ShouldFail | |
|
||
directPlutusTest :: ShouldSucceed -> ShortByteString -> [P.Data] -> Assertion | ||
directPlutusTest expectation script ds = | ||
case (expectation, evalWithHugeBudget script ds) of | ||
(ShouldSucceed, (_, Left e)) -> | ||
case (expectation, evalWithTightBudget script ds) of | ||
(ShouldSucceed, Left e) -> | ||
assertBool ("This script should have succeeded, but: " <> show e) False | ||
(ShouldSucceed, (_, Right _)) -> | ||
(ShouldSucceed, Right _) -> | ||
assertBool "" True | ||
(ShouldFail, (_, Left ((P.CekError _)))) -> | ||
(ShouldFail, Left ((P.CekError _))) -> | ||
assertBool "" True -- TODO rule out cost model failure | ||
(ShouldFail, (_, Left e)) -> | ||
(ShouldFail, Left e) -> | ||
assertBool ("Not the script failure we expected: " <> show e) False | ||
(ShouldFail, (_, Right _)) -> | ||
(ShouldFail, Right _) -> | ||
assertBool "This script should have failed" False | ||
where | ||
costModel = fromMaybe (error "corrupt default cost model") P.defaultCostModelParams | ||
-- Evaluate a script with sufficient budget to run it. | ||
evalWithHugeBudget scr datums = | ||
P.evaluateScriptRestricting | ||
P.Verbose | ||
costModel | ||
(P.ExBudget (P.ExCPU 100000000) (P.ExMemory 10000000)) | ||
scr | ||
datums | ||
evalWithTightBudget :: ShortByteString -> [P.Data] -> Either P.EvaluationError () | ||
evalWithTightBudget scr datums = do | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. much better, thank you! |
||
budget <- snd $ P.evaluateScriptCounting P.Quiet costModel scr datums | ||
snd $ P.evaluateScriptRestricting P.Verbose costModel budget scr datums | ||
|
||
-- | Expects 3 args (data, redeemer, context) | ||
guessTheNumber3 :: ShortByteString | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,188 @@ | ||
{-# LANGUAGE BangPatterns #-} | ||
{-# LANGUAGE DataKinds #-} | ||
{-# LANGUAGE RankNTypes #-} | ||
{-# LANGUAGE TypeApplications #-} | ||
|
||
module Test.Cardano.Ledger.Alonzo.Tools (tests, testExUnitCalculation) where | ||
|
||
import Cardano.Ledger.Alonzo.Language (Language (..)) | ||
import Cardano.Ledger.Alonzo.PParams (PParams, PParams' (..), ProtVer (..)) | ||
import Cardano.Ledger.Alonzo.Rules.Utxos (UTXOS) | ||
import Cardano.Ledger.Alonzo.Scripts (CostModel, ExUnits (..), defaultCostModel) | ||
import Cardano.Ledger.Alonzo.Tools (evaluateTransactionExecutionUnits) | ||
import Cardano.Ledger.Alonzo.Tx | ||
( IsValidating (..), | ||
ValidatedTx (..), | ||
) | ||
import Cardano.Ledger.Alonzo.TxInfo (exBudgetToExUnits, transExUnits) | ||
import Cardano.Ledger.Alonzo.TxWitness (RdmrPtr, Redeemers (..), txrdmrs) | ||
import Cardano.Ledger.Coin (Coin (..)) | ||
import Cardano.Ledger.Keys (GenDelegs (..)) | ||
import Cardano.Ledger.SafeHash (hashAnnotated) | ||
import qualified Cardano.Ledger.Tx as Core | ||
import Cardano.Slotting.EpochInfo (EpochInfo, fixedEpochInfo) | ||
import Cardano.Slotting.Slot (EpochSize (..), SlotNo (..)) | ||
import Cardano.Slotting.Time (SystemStart, mkSlotLength) | ||
import Control.State.Transition.Extended (TRC (..)) | ||
import Data.Array (Array, array) | ||
import Data.Default.Class (Default (..)) | ||
import Data.Map (Map) | ||
import qualified Data.Map as Map | ||
import Data.Maybe (fromJust) | ||
import Data.Word (Word64) | ||
import GHC.Records (getField) | ||
import Shelley.Spec.Ledger.LedgerState (UTxOState (..)) | ||
import Shelley.Spec.Ledger.STS.Utxo (UtxoEnv (..)) | ||
import Shelley.Spec.Ledger.UTxO (UTxO, makeWitnessVKey) | ||
import Test.Cardano.Ledger.Examples.TwoPhaseValidation (A, datumExample1, initUTxO, someKeys, testSystemStart, validatingBody, validatingRedeemersEx1) | ||
import Test.Cardano.Ledger.Generic.Proof (Evidence (Mock), Proof (Alonzo)) | ||
import Test.Cardano.Ledger.Generic.Updaters | ||
import Test.Shelley.Spec.Ledger.Utils (applySTSTest, runShelleyBase) | ||
import Test.Tasty (TestTree, testGroup) | ||
import Test.Tasty.HUnit (assertFailure, testCase) | ||
import Test.Tasty.QuickCheck (Gen, Property, chooseBoundedIntegral, counterexample, testProperty) | ||
|
||
tests :: TestTree | ||
tests = | ||
testGroup "ExUnit tools" $ | ||
[ testProperty "Plutus ExUnit translation round-trip" exUnitsTranslationRoundTrip, | ||
testCase "calculate ExUnits" exampleExUnitCalc | ||
] | ||
|
||
genExUnits :: Gen ExUnits | ||
genExUnits = ExUnits <$> genUnit <*> genUnit | ||
where | ||
genUnit :: Gen Word64 | ||
genUnit = chooseBoundedIntegral (0, 2 ^ (63 :: Word64) - 1) | ||
|
||
-- ExUnits should remain intact when translating to and from the plutus type | ||
exUnitsTranslationRoundTrip :: Gen Property | ||
exUnitsTranslationRoundTrip = do | ||
e <- genExUnits | ||
let result = (exBudgetToExUnits . transExUnits) e | ||
pure $ | ||
counterexample | ||
( "Before: " <> show (Just e) | ||
<> "\n After: " | ||
<> show result | ||
) | ||
$ result == Just e | ||
|
||
-- checks plutus script validation against a tx which has had | ||
-- its ex units replaced by the output of evaluateTransactionExecutionUnits | ||
testExUnitCalculation :: | ||
MonadFail m => | ||
Core.Tx A -> | ||
UTxOState A -> | ||
UtxoEnv A -> | ||
EpochInfo m -> | ||
SystemStart -> | ||
Array Language CostModel -> | ||
(forall a. String -> m a) -> | ||
m () | ||
testExUnitCalculation tx utxoState ue ei ss costmdls err = do | ||
tx' <- updateTxExUnits tx utxo ei ss costmdls err | ||
_ <- | ||
failLeft err $ | ||
runShelleyBase $ | ||
applySTSTest @(UTXOS A) (TRC (ue, utxoState, vtx tx')) | ||
pure () | ||
where | ||
utxo = _utxo utxoState | ||
|
||
exampleExUnitCalc :: IO () | ||
exampleExUnitCalc = | ||
testExUnitCalculation | ||
exampleTx | ||
ustate | ||
uenv | ||
exampleEpochInfo | ||
testSystemStart | ||
costmodels | ||
assertFailure | ||
|
||
exampleTx :: Core.Tx A | ||
exampleTx = | ||
let pf = Alonzo Mock | ||
in newTx | ||
Override | ||
pf | ||
[ Body (validatingBody pf), | ||
Witnesses' | ||
[ AddrWits [makeWitnessVKey (hashAnnotated (validatingBody pf)) (someKeys pf)], | ||
ScriptWits [always 3 pf], | ||
DataWits [datumExample1], | ||
RdmrWits validatingRedeemersEx1 | ||
] | ||
] | ||
|
||
exampleEpochInfo :: Monad m => EpochInfo m | ||
exampleEpochInfo = fixedEpochInfo (EpochSize 100) (mkSlotLength 1) | ||
|
||
uenv :: UtxoEnv A | ||
uenv = UtxoEnv (SlotNo 0) pparams mempty (GenDelegs mempty) | ||
|
||
costmodels :: Array Language CostModel | ||
costmodels = array (PlutusV1, PlutusV1) [(PlutusV1, fromJust defaultCostModel)] | ||
|
||
ustate :: UTxOState A | ||
ustate = | ||
UTxOState | ||
{ _utxo = initUTxO (Alonzo Mock), | ||
_deposited = Coin 0, | ||
_fees = Coin 0, | ||
_ppups = def | ||
} | ||
|
||
-- Requires ex units, but there are no fees | ||
pparams :: PParams A | ||
pparams = | ||
newPParams | ||
(Alonzo Mock) | ||
[ Costmdls $ Map.singleton PlutusV1 $ fromJust defaultCostModel, | ||
MaxValSize 1000000000, | ||
MaxTxExUnits $ ExUnits 100000000 100000000, | ||
MaxBlockExUnits $ ExUnits 100000000 100000000, | ||
ProtocolVersion $ ProtVer 5 0 | ||
] | ||
|
||
updateTxExUnits :: | ||
MonadFail m => | ||
Core.Tx A -> | ||
UTxO A -> | ||
EpochInfo m -> | ||
SystemStart -> | ||
Array Language CostModel -> | ||
(forall a. String -> m a) -> | ||
m (Core.Tx A) | ||
updateTxExUnits tx utxo ei ss costmdls err = do | ||
-- rdmrs :: Map RdmrPtr ExUnits | ||
rdmrs <- | ||
traverse (failLeft err) | ||
=<< evaluateTransactionExecutionUnits tx utxo ei ss costmdls | ||
pure (replaceRdmrs tx rdmrs) | ||
|
||
replaceRdmrs :: Core.Tx A -> Map RdmrPtr ExUnits -> Core.Tx A | ||
replaceRdmrs tx rdmrs = tx {Core.wits = wits'} | ||
where | ||
wits' = (Core.wits tx) {txrdmrs = newrdmrs} | ||
newrdmrs = foldr replaceRdmr (txrdmrs (Core.wits tx)) (Map.assocs rdmrs) | ||
|
||
replaceRdmr :: (RdmrPtr, ExUnits) -> Redeemers A -> Redeemers A | ||
replaceRdmr (ptr, ex) x@(Redeemers r) = | ||
case Map.lookup ptr r of | ||
Just (dat, _ex) -> Redeemers $ Map.insert ptr (dat, ex) r | ||
Nothing -> x | ||
|
||
failLeft :: (Monad m, Show e) => (String -> m a) -> Either e a -> m a | ||
failLeft _ (Right a) = pure a | ||
failLeft err (Left e) = err (show e) | ||
|
||
vtx :: Core.Tx A -> ValidatedTx A | ||
vtx tx = | ||
ValidatedTx | ||
{ body = getField @"body" tx, | ||
wits = getField @"wits" tx, | ||
isValidating = IsValidating True, | ||
auxiliaryData = getField @"auxiliaryData" tx | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is going to be a bit confusing, since I think that package will ultimately want to depend on this one