From 49df021d1fb4d538db4e9873f46d78f2021452b2 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Tue, 4 Jan 2022 15:04:57 +0100 Subject: [PATCH 1/7] Create new 'plutus-cbor' package. --- cabal.project | 4 + plutus-cbor/LICENSE | 202 ++++++++++++++++++++++++++++++++++ plutus-cbor/NOTICE | 14 +++ plutus-cbor/README.md | 1 + plutus-cbor/plutus-cbor.cabal | 105 ++++++++++++++++++ 5 files changed, 326 insertions(+) create mode 100644 plutus-cbor/LICENSE create mode 100644 plutus-cbor/NOTICE create mode 100644 plutus-cbor/README.md create mode 100644 plutus-cbor/plutus-cbor.cabal diff --git a/cabal.project b/cabal.project index 5abe7748e6d..72638df409d 100644 --- a/cabal.project +++ b/cabal.project @@ -8,6 +8,7 @@ packages: hydra-test-utils hydra-tui merkle-patricia-tree + plutus-cbor tests: False package local-cluster @@ -26,6 +27,9 @@ package hydra-tui package merkle-patricia-tree tests: True +package plutus-cbor + tests: True + -- Always show detailed output for tests test-show-details: direct diff --git a/plutus-cbor/LICENSE b/plutus-cbor/LICENSE new file mode 100644 index 00000000000..e1dcc94dd19 --- /dev/null +++ b/plutus-cbor/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2022] [IOG] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/plutus-cbor/NOTICE b/plutus-cbor/NOTICE new file mode 100644 index 00000000000..23d65433d68 --- /dev/null +++ b/plutus-cbor/NOTICE @@ -0,0 +1,14 @@ +Copyright 2021 Input Output Global Ltd. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + diff --git a/plutus-cbor/README.md b/plutus-cbor/README.md new file mode 100644 index 00000000000..6efd0dbddf8 --- /dev/null +++ b/plutus-cbor/README.md @@ -0,0 +1 @@ +# Plutus CBOR diff --git a/plutus-cbor/plutus-cbor.cabal b/plutus-cbor/plutus-cbor.cabal new file mode 100644 index 00000000000..778b6bd8b2b --- /dev/null +++ b/plutus-cbor/plutus-cbor.cabal @@ -0,0 +1,105 @@ +cabal-version: 2.2 +name: plutus-cbor +version: 0.1.0 +synopsis: On-chain CBOR encoders/decoders +author: IOG +copyright: 2022 IOG +license: Apache-2.0 +license-files: + LICENSE + NOTICE + +source-repository head + type: git + location: https://github.com/input-output-hk/hydra-poc + +flag hydra-development + description: Disable -Werror for development + default: False + manual: True + +common project-config + default-language: Haskell2010 + default-extensions: + NoImplicitPrelude + BangPatterns + BinaryLiterals + ConstraintKinds + DataKinds + DefaultSignatures + DeriveAnyClass + DeriveDataTypeable + DeriveFoldable + DeriveFunctor + DeriveGeneric + DeriveTraversable + DerivingStrategies + EmptyDataDecls + ExistentialQuantification + FlexibleContexts + FlexibleInstances + FunctionalDependencies + GADTs + GeneralizedNewtypeDeriving + InstanceSigs + KindSignatures + LambdaCase + MultiParamTypeClasses + MultiWayIf + NamedFieldPuns + NumericUnderscores + OverloadedStrings + PartialTypeSignatures + PatternGuards + RankNTypes + ScopedTypeVariables + StandaloneDeriving + TupleSections + TypeFamilies + TypeSynonymInstances + ViewPatterns + + ghc-options: + -Wall -Wcompat -Widentities -Wincomplete-record-updates + -Wincomplete-uni-patterns -Wpartial-fields -Wredundant-constraints + -fprint-potential-instances + + if !flag(hydra-development) + ghc-options: -Werror + +library + import: project-config + hs-source-dirs: src + ghc-options: -haddock + if flag(hydra-development) + -- NOTE(SN): should fix HLS choking on PlutusTx plugin + ghc-options: -fplugin-opt PlutusTx.Plugin:defer-errors + build-depends: + plutus-core + , plutus-tx + , plutus-tx-plugin + exposed-modules: + Plutus.Codec.CBOR.Encoding + +test-suite unit + import: project-config + type: exitcode-stdio-1.0 + hs-source-dirs: test + ghc-options: -threaded -rtsopts + build-tool-depends: hspec-discover:hspec-discover -any + build-depends: + , base + , base16 + , bytestring + , cborg + , hspec + , hydra-prelude + , hydra-test-utils + , memory + , plutus-cbor + , plutus-tx + , QuickCheck + other-modules: + Plutus.Codec.CBOR.EncodingSpec + Spec + main-is: Main.hs From a3adc4d7b8671b7106ad7f5f5ec096beba353fda Mon Sep 17 00:00:00 2001 From: KtorZ Date: Tue, 4 Jan 2022 15:05:26 +0100 Subject: [PATCH 2/7] Write simple implementation of an on-chain CBOR encoder for integer. --- plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs | 78 +++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs diff --git a/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs b/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs new file mode 100644 index 00000000000..6a3dcba60a7 --- /dev/null +++ b/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs @@ -0,0 +1,78 @@ +{-# OPTIONS_GHC -fno-specialize #-} + +module Plutus.Codec.CBOR.Encoding ( + -- * Encoding + Encoding, + encodingToBuiltinByteString, + + -- * Basic types + encodeInteger, + + -- * Data-structures +) where + +import PlutusTx.Prelude + +-- * Encoding + +type Encoding = BuiltinByteString + +encodingToBuiltinByteString :: Encoding -> BuiltinByteString +encodingToBuiltinByteString = id +{-# INLINEABLE encodingToBuiltinByteString #-} + +-- * Basic types + +encodeInteger :: Integer -> Encoding +encodeInteger n + | n < 0 = + encodeUnsigned 1 (-n - 1) + | otherwise = + encodeUnsigned 0 n +{-# INLINEABLE encodeInteger #-} + +-- * Internal + +withMajorType :: Integer -> Integer -> Encoding -> Encoding +withMajorType major n = + consByteString (32 * major + n) + +encodeUnsigned :: Integer -> Integer -> Encoding +encodeUnsigned major n + | n < 24 = + withMajorType major n emptyByteString + | n < 256 = + withMajorType major 24 (encodeUnsigned8 n) + | n < 65536 = + withMajorType major 25 (encodeUnsigned16 n) + | n < 4294967296 = + withMajorType major 26 (encodeUnsigned32 n) + | otherwise = + withMajorType major 27 (encodeUnsigned64 n) +{-# INLINEABLE encodeUnsigned #-} + +encodeUnsigned8 :: Integer -> Encoding +encodeUnsigned8 n = + consByteString n emptyByteString +{-# INLINEABLE encodeUnsigned8 #-} + +encodeUnsigned16 :: Integer -> Encoding +encodeUnsigned16 n = + appendByteString + (encodeUnsigned8 (quotient n 256)) + (encodeUnsigned8 (remainder n 256)) +{-# INLINEABLE encodeUnsigned16 #-} + +encodeUnsigned32 :: Integer -> Encoding +encodeUnsigned32 n = + appendByteString + (encodeUnsigned16 (quotient n 65536)) + (encodeUnsigned16 (remainder n 65536)) +{-# INLINEABLE encodeUnsigned32 #-} + +encodeUnsigned64 :: Integer -> Encoding +encodeUnsigned64 n = + appendByteString + (encodeUnsigned32 (quotient n 4294967296)) + (encodeUnsigned32 (remainder n 4294967296)) +{-# INLINEABLE encodeUnsigned64 #-} From af9264a119373d3241ccce11ddba32116f01e1e1 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Tue, 4 Jan 2022 15:05:48 +0100 Subject: [PATCH 3/7] Compare on-chain CBOR encoder with off-chain oracle ('cborg' library). --- plutus-cbor/test/Main.hs | 14 ++++ .../test/Plutus/Codec/CBOR/EncodingSpec.hs | 74 +++++++++++++++++++ plutus-cbor/test/Spec.hs | 1 + 3 files changed, 89 insertions(+) create mode 100644 plutus-cbor/test/Main.hs create mode 100644 plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs create mode 100644 plutus-cbor/test/Spec.hs diff --git a/plutus-cbor/test/Main.hs b/plutus-cbor/test/Main.hs new file mode 100644 index 00000000000..6599db9178f --- /dev/null +++ b/plutus-cbor/test/Main.hs @@ -0,0 +1,14 @@ +module Main where + +import Hydra.Prelude + +import Test.Hspec.Runner (configFormat, defaultConfig, hspecWith) +import Test.Hydra.Prelude (dualFormatter) + +import qualified Spec + +main :: IO () +main = + hspecWith + defaultConfig{configFormat = Just (dualFormatter "plutus-cbor")} + Spec.spec diff --git a/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs b/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs new file mode 100644 index 00000000000..948ede7ef1c --- /dev/null +++ b/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs @@ -0,0 +1,74 @@ +module Plutus.Codec.CBOR.EncodingSpec where + +import Hydra.Prelude hiding (label) +import Test.Hydra.Prelude + +import qualified Codec.CBOR.Encoding as CBOR +import qualified Codec.CBOR.Pretty as CBOR +import qualified Codec.CBOR.Write as CBOR +import Data.ByteArray (convert) +import Data.ByteString.Base16 (encodeBase16) +import Plutus.Codec.CBOR.Encoding ( + Encoding, + encodeInteger, + encodingToBuiltinByteString, + ) +import Test.QuickCheck ( + Property, + choose, + counterexample, + forAll, + oneof, + (===), + ) + +spec :: Spec +spec = do + describe "Comparing CBOR encoding with oracle ('cborg' library)" $ do + prop + "works for all (x :: Integer) with 'encodeInteger'" + propEncodeInteger + +-- +-- CBOR encoding against oracle +-- + +propCompareWithOracle :: + Show x => + (x -> CBOR.Encoding) -> + (x -> Encoding) -> + x -> + Property +propCompareWithOracle encodeOracle encodeOurs x = + ( convert (CBOR.toStrictByteString oracle) === ours + ) + & counterexample ("value: " <> show x) + & counterexample ("\n─── cborg: \n" <> CBOR.prettyHexEnc oracle) + & counterexample ("\n─── ours: \n" <> toString (encodeBase16 $ convert ours)) + where + oracle = encodeOracle x + ours = encodingToBuiltinByteString (encodeOurs x) + +propEncodeInteger :: Property +propEncodeInteger = + forAll genInteger $ propCompareWithOracle CBOR.encodeInteger encodeInteger + +-- +-- Generators +-- + +genInteger :: Gen Integer +genInteger = + oneof + [ genUnsignedInteger + , negate <$> genUnsignedInteger + ] + where + genUnsignedInteger = + oneof + [ choose (0, 24) + , choose (24, 256) + , choose (256, 65536) + , choose (65536, 4294967296) + , choose (4294967296, 18446744073709552000) + ] diff --git a/plutus-cbor/test/Spec.hs b/plutus-cbor/test/Spec.hs new file mode 100644 index 00000000000..5416ef6a866 --- /dev/null +++ b/plutus-cbor/test/Spec.hs @@ -0,0 +1 @@ +{-# OPTIONS_GHC -F -pgmF hspec-discover -optF --module-name=Spec #-} From 6c5feb125751438eb0c327aa3cbc31f77790e5f0 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Tue, 4 Jan 2022 15:06:57 +0100 Subject: [PATCH 4/7] fixup create lib. --- plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs | 1 + 1 file changed, 1 insertion(+) diff --git a/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs b/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs index 6a3dcba60a7..d8ecaeff574 100644 --- a/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs +++ b/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs @@ -36,6 +36,7 @@ encodeInteger n withMajorType :: Integer -> Integer -> Encoding -> Encoding withMajorType major n = consByteString (32 * major + n) +{-# INLINEABLE withMajorType #-} encodeUnsigned :: Integer -> Integer -> Encoding encodeUnsigned major n From 76b8baffbfad3cda7564db2b9cca10c8be4ad09d Mon Sep 17 00:00:00 2001 From: KtorZ Date: Tue, 4 Jan 2022 19:40:38 +0100 Subject: [PATCH 5/7] Define new property for measuring and controlling the execution cost of an encoder. --- plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs | 2 - .../test/Plutus/Codec/CBOR/EncodingSpec.hs | 108 ++++++++++++++++-- 2 files changed, 98 insertions(+), 12 deletions(-) diff --git a/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs b/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs index d8ecaeff574..1404e4eca01 100644 --- a/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs +++ b/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs @@ -1,5 +1,3 @@ -{-# OPTIONS_GHC -fno-specialize #-} - module Plutus.Codec.CBOR.Encoding ( -- * Encoding Encoding, diff --git a/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs b/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs index 948ede7ef1c..7f508b2e58a 100644 --- a/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs +++ b/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs @@ -1,38 +1,63 @@ +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE TypeApplications #-} + module Plutus.Codec.CBOR.EncodingSpec where import Hydra.Prelude hiding (label) import Test.Hydra.Prelude +import Cardano.Ledger.Alonzo.Scripts (ExUnits (..)) import qualified Codec.CBOR.Encoding as CBOR import qualified Codec.CBOR.Pretty as CBOR import qualified Codec.CBOR.Write as CBOR +import Data.Binary.Builder (toLazyByteString) import Data.ByteArray (convert) import Data.ByteString.Base16 (encodeBase16) +import Data.ByteString.Builder.Scientific (FPFormat (Fixed), formatScientificBuilder) +import Data.Ratio ((%)) +import Data.Scientific (unsafeFromRational) +import qualified Ledger.Typed.Scripts as Scripts import Plutus.Codec.CBOR.Encoding ( Encoding, encodeInteger, encodingToBuiltinByteString, ) +import qualified PlutusTx as Plutus +import Test.Plutus.Codec.CBOR.Encoding.Utils ( + evaluateScriptExecutionUnits, + ) +import Test.Plutus.Codec.CBOR.Encoding.Validators ( + EncodeValidator, + emptyValidator, + encodeIntegerValidator, + ) import Test.QuickCheck ( Property, choose, counterexample, forAll, + forAllBlind, oneof, + vectorOf, + (.&&.), (===), ) spec :: Spec spec = do - describe "Comparing CBOR encoding with oracle ('cborg' library)" $ do - prop - "works for all (x :: Integer) with 'encodeInteger'" - propEncodeInteger + describe "our CBOR encoding matches oracle's ('cborg' library)" $ do + prop "for all (x :: Integer) w/ 'encodeInteger'" $ + forAll genInteger $ + propCompareWithOracle CBOR.encodeInteger encodeInteger --- --- CBOR encoding against oracle --- + describe "(on-chain) execution cost of CBOR encoding is small" $ do + prop "for all (x :: Integer), <0.05%" $ + forAllBlind (vectorOf 100 genInteger) $ + propCostIsSmall (1 % 2_000) defaultMaxExecutionUnits encodeIntegerValidator +-- | Compare encoding a value 'x' with our own encoder and a reference +-- implementation. Counterexamples shows both encoded values, but in a pretty / +-- readable form for the reference implementation. propCompareWithOracle :: Show x => (x -> CBOR.Encoding) -> @@ -49,9 +74,72 @@ propCompareWithOracle encodeOracle encodeOurs x = oracle = encodeOracle x ours = encodingToBuiltinByteString (encodeOurs x) -propEncodeInteger :: Property -propEncodeInteger = - forAll genInteger $ propCompareWithOracle CBOR.encodeInteger encodeInteger +-- | Measure that the execution cost of encoding a certain value 'x' is small in +-- front of some max execution budget. +propCostIsSmall :: + Plutus.ToData a => + Rational -> + ExUnits -> + Scripts.TypedValidator (EncodeValidator a) -> + [a] -> + Property +propCostIsSmall tolerance (ExUnits maxMemUnits maxStepsUnits) encode xs = + ((relativeMemCost < tolerance) .&&. (relativeStepCost < tolerance)) + & counterexample + ( "memory execution units: " + <> show mem + <> " (" + <> asPercent relativeMemCost + <> ")" + ) + & counterexample + ( "CPU execution units: " + <> show steps + <> " (" + <> asPercent relativeStepCost + <> ")" + ) + where + n = fromIntegral (length xs) + + ExUnits mem steps = + distanceExUnits + (evaluateScriptExecutionUnits emptyValidator ()) + (evaluateScriptExecutionUnits encode xs) + & (\(ExUnits m s) -> ExUnits (m `div` n) (s `div` n)) + + (relativeMemCost, relativeStepCost) = + ( toInteger mem % toInteger maxMemUnits + , toInteger steps % toInteger maxStepsUnits + ) + +-- +-- Compare scripts to baselines +-- + +-- | Current (2022-04-01) mainchain parameters. +defaultMaxExecutionUnits :: ExUnits +defaultMaxExecutionUnits = + ExUnits + { exUnitsMem = 10_000_000 + , exUnitsSteps = 10_000_000_000 + } + +distanceExUnits :: ExUnits -> ExUnits -> ExUnits +distanceExUnits (ExUnits m0 s0) (ExUnits m1 s1) = + ExUnits + (if m0 > m1 then m0 - m1 else m1 - m0) + (if s0 > s1 then s0 - s1 else s1 - s0) + +-- +-- Helpers +-- + +asPercent :: Rational -> String +asPercent r = + decodeUtf8 (toLazyByteString $ toFixedDecimals 6 $ 100 * r) <> "%" + where + toFixedDecimals n = formatScientificBuilder Fixed (Just n) . unsafeFromRational -- -- Generators From 26a6edf83f82e985cc8daaf12da7f65350761fab Mon Sep 17 00:00:00 2001 From: KtorZ Date: Tue, 4 Jan 2022 19:41:03 +0100 Subject: [PATCH 6/7] Write plumbing code for the validators and the calculation of execution units. --- plutus-cbor/plutus-cbor.cabal | 20 +++ .../Test/Plutus/Codec/CBOR/Encoding/Utils.hs | 157 ++++++++++++++++++ .../Plutus/Codec/CBOR/Encoding/Validators.hs | 45 +++++ 3 files changed, 222 insertions(+) create mode 100644 plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Utils.hs create mode 100644 plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Validators.hs diff --git a/plutus-cbor/plutus-cbor.cabal b/plutus-cbor/plutus-cbor.cabal index 778b6bd8b2b..177defa8e56 100644 --- a/plutus-cbor/plutus-cbor.cabal +++ b/plutus-cbor/plutus-cbor.cabal @@ -88,18 +88,38 @@ test-suite unit ghc-options: -threaded -rtsopts build-tool-depends: hspec-discover:hspec-discover -any build-depends: + , array , base , base16 + , binary , bytestring + , cardano-binary + , cardano-ledger-shelley + , cardano-ledger-shelley-ma + , cardano-ledger-alonzo + , cardano-ledger-alonzo-test + , cardano-ledger-core + , cardano-slotting , cborg + , containers + , data-default , hspec , hydra-prelude , hydra-test-utils , memory , plutus-cbor + , plutus-core + , plutus-ledger + , plutus-ledger-api , plutus-tx + , plutus-tx-plugin + , scientific + , serialise + , strict-containers , QuickCheck other-modules: Plutus.Codec.CBOR.EncodingSpec + Test.Plutus.Codec.CBOR.Encoding.Utils + Test.Plutus.Codec.CBOR.Encoding.Validators Spec main-is: Main.hs diff --git a/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Utils.hs b/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Utils.hs new file mode 100644 index 00000000000..355e8255726 --- /dev/null +++ b/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Utils.hs @@ -0,0 +1,157 @@ +{-# LANGUAGE TypeApplications #-} + +-- | A helper module mostly wrapping the Alonzo.Tools' +-- 'evaluateTransactionExecutionUnits' with a much simpler API (just a plutus +-- script). +-- +-- This is generally handy to measure the execution of Plutus code outside of any +-- context (e.g. an implementation of a data-structure on-chain or, as here, +-- data encoders). +module Test.Plutus.Codec.CBOR.Encoding.Utils ( + evaluateScriptExecutionUnits, +) where + +import Hydra.Prelude hiding (label) + +import Cardano.Binary (unsafeDeserialize') +import Cardano.Ledger.Address (Addr (..)) +import Cardano.Ledger.Alonzo (AlonzoEra) +import Cardano.Ledger.Alonzo.Data (Data (..), hashData) +import Cardano.Ledger.Alonzo.Language (Language (PlutusV1)) +import Cardano.Ledger.Alonzo.PParams (PParams' (..)) +import Cardano.Ledger.Alonzo.Scripts (ExUnits (..), Script (..), Tag (..)) +import Cardano.Ledger.Alonzo.Tools (evaluateTransactionExecutionUnits) +import Cardano.Ledger.Alonzo.Tx (IsValid (..), ValidatedTx (..)) +import Cardano.Ledger.Alonzo.TxBody (TxBody (..), TxOut (..)) +import Cardano.Ledger.Alonzo.TxWitness ( + RdmrPtr (..), + Redeemers (..), + TxDats (..), + TxWitness (..), + ) +import Cardano.Ledger.BaseTypes (Network (..)) +import Cardano.Ledger.Credential (Credential (..), StakeReference (..)) +import Cardano.Ledger.Crypto (StandardCrypto) +import Cardano.Ledger.Era (ValidateScript (hashScript)) +import Cardano.Ledger.Hashes (ScriptHash (..)) +import Cardano.Ledger.Shelley.TxBody (Wdrl (..)) +import qualified Cardano.Ledger.Shelley.UTxO as Ledger +import Cardano.Ledger.ShelleyMA.Timelocks (ValidityInterval (..)) +import Cardano.Ledger.TxIn (TxIn (..)) +import Cardano.Slotting.EpochInfo (fixedEpochInfo) +import Cardano.Slotting.Slot (EpochSize (EpochSize)) +import Cardano.Slotting.Time (SystemStart (SystemStart), mkSlotLength) +import Codec.Serialise (serialise) +import Data.Array (array) +import qualified Data.ByteString as BS +import Data.Default (def) +import qualified Data.Map as Map +import Data.Maybe (fromJust) +import Data.Maybe.Strict (StrictMaybe (..)) +import qualified Data.Set as Set +import qualified Ledger.Typed.Scripts as Scripts +import qualified PlutusTx as Plutus +import Test.Cardano.Ledger.Alonzo.PlutusScripts (defaultCostModel) +import qualified Prelude + +evaluateScriptExecutionUnits :: + Plutus.ToData a => + Scripts.TypedValidator v -> + a -> + ExUnits +evaluateScriptExecutionUnits validator redeemer = + case runIdentity (evaluateTransactionExecutionUnits pparams tx utxo epoch start costModels) of + Right (toList -> [units]) -> + either (error . ("unexpected script failure: " <>) . show) id units + Right{} -> + error "executed more than one script?!" + Left e -> + error ("unexpected failure: " <> show e) + where + (tx, utxo) = transactionFromScript validator redeemer + costModels = array (PlutusV1, PlutusV1) [(PlutusV1, fromJust defaultCostModel)] + epoch = fixedEpochInfo (EpochSize 432000) (mkSlotLength 1) + start = SystemStart $ Prelude.read "2017-09-23 21:44:51 UTC" + pparams = def{_maxTxExUnits = ExUnits 9999999999 9999999999} + +transactionFromScript :: + Plutus.ToData a => + Scripts.TypedValidator v -> + a -> + (ValidatedTx (AlonzoEra StandardCrypto), Ledger.UTxO (AlonzoEra StandardCrypto)) +transactionFromScript validator redeemer = + ( ValidatedTx + { body = defaultTxBody + , wits = defaultTxWits + , isValid = IsValid True + , auxiliaryData = SNothing + } + , Ledger.UTxO (fromList [(defaultTxIn, txOutFromScript)]) + ) + where + script :: Script (AlonzoEra StandardCrypto) + script = + PlutusScript + PlutusV1 + (toShort $ toStrict $ serialise $ Scripts.validatorScript validator) + + scriptHash :: ScriptHash StandardCrypto + scriptHash = + hashScript @(AlonzoEra StandardCrypto) script + + txOutFromScript :: TxOut (AlonzoEra StandardCrypto) + txOutFromScript = + TxOut + (Addr Testnet (ScriptHashObj scriptHash) StakeRefNull) + mempty + (SJust $ hashData defaultDatum) + + defaultTxWits :: TxWitness (AlonzoEra StandardCrypto) + defaultTxWits = + TxWitness + mempty + mempty + (Map.fromList [(scriptHash, script)]) + ( TxDats $ + Map.fromList + [ + ( hashData defaultDatum + , defaultDatum + ) + ] + ) + ( Redeemers $ + Map.fromList + [ + ( RdmrPtr Spend 0 + , (Data $ Plutus.toData redeemer, defaultExUnits) + ) + ] + ) + + defaultDatum :: Data (AlonzoEra StandardCrypto) + defaultDatum = Data (Plutus.toData ()) + + defaultExUnits :: ExUnits + defaultExUnits = ExUnits 0 0 + + defaultTxBody :: TxBody (AlonzoEra StandardCrypto) + defaultTxBody = + TxBody + { inputs = Set.singleton defaultTxIn + , collateral = mempty + , outputs = mempty + , txcerts = mempty + , txwdrls = Wdrl mempty + , txfee = mempty + , txvldt = ValidityInterval SNothing SNothing + , txUpdates = SNothing + , reqSignerHashes = mempty + , mint = mempty + , scriptIntegrityHash = SNothing + , adHash = SNothing + , txnetworkid = SNothing + } + + defaultTxIn :: TxIn StandardCrypto + defaultTxIn = TxIn (unsafeDeserialize' $ BS.pack [88, 32] <> BS.replicate 32 0) 0 diff --git a/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Validators.hs b/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Validators.hs new file mode 100644 index 00000000000..cec404a3a78 --- /dev/null +++ b/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Validators.hs @@ -0,0 +1,45 @@ +{-# LANGUAGE TemplateHaskell #-} +{-# LANGUAGE TypeApplications #-} +{-# OPTIONS_GHC -fno-specialize #-} + +module Test.Plutus.Codec.CBOR.Encoding.Validators where + +import Hydra.Prelude hiding (label) + +import qualified Ledger.Typed.Scripts as Scripts +import Plutus.Codec.CBOR.Encoding ( + encodeInteger, + ) +import qualified PlutusTx as Plutus + +-- | A baseline validator which does nothing but returning 'True'. We use it as +-- baseline to measure the deviation for cost execution of other validators. +data EmptyValidator + +instance Scripts.ValidatorTypes EmptyValidator where + type DatumType EmptyValidator = () + type RedeemerType EmptyValidator = () + +emptyValidator :: Scripts.TypedValidator EmptyValidator +emptyValidator = + Scripts.mkTypedValidator @EmptyValidator + $$(Plutus.compile [||\() () _ctx -> True||]) + $$(Plutus.compile [||wrap||]) + where + wrap = Scripts.wrapValidator @() @() + +-- | A validator for measuring cost of encoding values. The validator is +-- parameterized by the type of value. +data EncodeValidator a + +instance Scripts.ValidatorTypes (EncodeValidator a) where + type DatumType (EncodeValidator a) = () + type RedeemerType (EncodeValidator a) = [a] + +encodeIntegerValidator :: Scripts.TypedValidator (EncodeValidator Integer) +encodeIntegerValidator = + Scripts.mkTypedValidator @(EncodeValidator Integer) + $$(Plutus.compile [||\() xs _ctx -> let _bytes = encodeInteger <$> xs in True||]) + $$(Plutus.compile [||wrap||]) + where + wrap = Scripts.wrapValidator @() @[Integer] From 53eab8e5f9b88a88048126db2a79e6363b5ef088 Mon Sep 17 00:00:00 2001 From: KtorZ Date: Wed, 5 Jan 2022 09:37:20 +0100 Subject: [PATCH 7/7] Fix validator evaluation -> force evaluation of the computation. --- plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs | 9 ++---- .../test/Plutus/Codec/CBOR/EncodingSpec.hs | 32 +++++++++++-------- .../Plutus/Codec/CBOR/Encoding/Validators.hs | 19 ++++++----- 3 files changed, 33 insertions(+), 27 deletions(-) diff --git a/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs b/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs index 1404e4eca01..acfd5559cbb 100644 --- a/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs +++ b/plutus-cbor/src/Plutus/Codec/CBOR/Encoding.hs @@ -1,16 +1,13 @@ module Plutus.Codec.CBOR.Encoding ( - -- * Encoding Encoding, encodingToBuiltinByteString, - - -- * Basic types encodeInteger, - - -- * Data-structures ) where import PlutusTx.Prelude +import PlutusTx.Builtins (subtractInteger) + -- * Encoding type Encoding = BuiltinByteString @@ -24,7 +21,7 @@ encodingToBuiltinByteString = id encodeInteger :: Integer -> Encoding encodeInteger n | n < 0 = - encodeUnsigned 1 (-n - 1) + encodeUnsigned 1 (subtractInteger 0 n - 1) | otherwise = encodeUnsigned 0 n {-# INLINEABLE encodeInteger #-} diff --git a/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs b/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs index 7f508b2e58a..2b2bb592ba6 100644 --- a/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs +++ b/plutus-cbor/test/Plutus/Codec/CBOR/EncodingSpec.hs @@ -12,6 +12,7 @@ import qualified Codec.CBOR.Pretty as CBOR import qualified Codec.CBOR.Write as CBOR import Data.Binary.Builder (toLazyByteString) import Data.ByteArray (convert) +import qualified Data.ByteString as BS import Data.ByteString.Base16 (encodeBase16) import Data.ByteString.Builder.Scientific (FPFormat (Fixed), formatScientificBuilder) import Data.Ratio ((%)) @@ -34,12 +35,12 @@ import Test.Plutus.Codec.CBOR.Encoding.Validators ( import Test.QuickCheck ( Property, choose, + conjoin, counterexample, forAll, forAllBlind, + label, oneof, - vectorOf, - (.&&.), (===), ) @@ -51,9 +52,12 @@ spec = do propCompareWithOracle CBOR.encodeInteger encodeInteger describe "(on-chain) execution cost of CBOR encoding is small" $ do - prop "for all (x :: Integer), <0.05%" $ - forAllBlind (vectorOf 100 genInteger) $ - propCostIsSmall (1 % 2_000) defaultMaxExecutionUnits encodeIntegerValidator + prop "for all (x :: Integer), <0.5%" $ + forAllBlind genInteger $ + propCostIsSmall + (1 % 200) + defaultMaxExecutionUnits + (encodeInteger, encodeIntegerValidator) -- | Compare encoding a value 'x' with our own encoder and a reference -- implementation. Counterexamples shows both encoded values, but in a pretty / @@ -80,11 +84,15 @@ propCostIsSmall :: Plutus.ToData a => Rational -> ExUnits -> - Scripts.TypedValidator (EncodeValidator a) -> - [a] -> + (a -> Encoding, Scripts.TypedValidator (EncodeValidator a)) -> + a -> Property -propCostIsSmall tolerance (ExUnits maxMemUnits maxStepsUnits) encode xs = - ((relativeMemCost < tolerance) .&&. (relativeStepCost < tolerance)) +propCostIsSmall tolerance (ExUnits maxMemUnits maxStepsUnits) (encode, validator) a = + conjoin + [ relativeMemCost < tolerance + , relativeStepCost < tolerance + ] + & label ("of size = " <> show n <> ", mem units = " <> show mem <> ", CPU units = " <> show steps) & counterexample ( "memory execution units: " <> show mem @@ -100,13 +108,11 @@ propCostIsSmall tolerance (ExUnits maxMemUnits maxStepsUnits) encode xs = <> ")" ) where - n = fromIntegral (length xs) - + n = BS.length $ convert $ encode a ExUnits mem steps = distanceExUnits (evaluateScriptExecutionUnits emptyValidator ()) - (evaluateScriptExecutionUnits encode xs) - & (\(ExUnits m s) -> ExUnits (m `div` n) (s `div` n)) + (evaluateScriptExecutionUnits validator a) (relativeMemCost, relativeStepCost) = ( toInteger mem % toInteger maxMemUnits diff --git a/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Validators.hs b/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Validators.hs index cec404a3a78..e1a6f5f1358 100644 --- a/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Validators.hs +++ b/plutus-cbor/test/Test/Plutus/Codec/CBOR/Encoding/Validators.hs @@ -4,12 +4,10 @@ module Test.Plutus.Codec.CBOR.Encoding.Validators where -import Hydra.Prelude hiding (label) +import PlutusTx.Prelude import qualified Ledger.Typed.Scripts as Scripts -import Plutus.Codec.CBOR.Encoding ( - encodeInteger, - ) +import Plutus.Codec.CBOR.Encoding (encodeInteger) import qualified PlutusTx as Plutus -- | A baseline validator which does nothing but returning 'True'. We use it as @@ -23,7 +21,7 @@ instance Scripts.ValidatorTypes EmptyValidator where emptyValidator :: Scripts.TypedValidator EmptyValidator emptyValidator = Scripts.mkTypedValidator @EmptyValidator - $$(Plutus.compile [||\() () _ctx -> True||]) + $$(Plutus.compile [||\() () _ctx -> lengthOfByteString "" == 0||]) $$(Plutus.compile [||wrap||]) where wrap = Scripts.wrapValidator @() @() @@ -34,12 +32,17 @@ data EncodeValidator a instance Scripts.ValidatorTypes (EncodeValidator a) where type DatumType (EncodeValidator a) = () - type RedeemerType (EncodeValidator a) = [a] + type RedeemerType (EncodeValidator a) = a encodeIntegerValidator :: Scripts.TypedValidator (EncodeValidator Integer) encodeIntegerValidator = Scripts.mkTypedValidator @(EncodeValidator Integer) - $$(Plutus.compile [||\() xs _ctx -> let _bytes = encodeInteger <$> xs in True||]) + $$( Plutus.compile + [|| + \() a _ctx -> + lengthOfByteString (encodeInteger a) > 0 + ||] + ) $$(Plutus.compile [||wrap||]) where - wrap = Scripts.wrapValidator @() @[Integer] + wrap = Scripts.wrapValidator @() @Integer