From 3ef535afed1cb53dd4a22cc874250ca54f926efe Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jann=20M=C3=BCller?= Date: Sat, 22 Jul 2023 14:52:07 +0200 Subject: [PATCH] Bump cardano-api, cardano-node * Use node 8.1.1 and cardano-api 8.8.0.0 --- .github/workflows/ci-linux.yaml | 7 +- .gitignore | 3 +- cabal.project | 171 +----- ...lonzo-genesis.json => alonzo-genesis.json} | 0 ...-byron-genesis.json => byron-genesis.json} | 0 node-config/mainnet/conway-genesis.json | 3 + node-config/mainnet/mainnet-config.json | 198 +++---- ...lley-genesis.json => shelley-genesis.json} | 0 src/base/convex-base.cabal | 21 +- src/base/lib/Convex/Class.hs | 17 +- src/base/lib/Convex/Event.hs | 100 ++-- src/base/lib/Convex/Lenses.hs | 35 +- src/base/lib/Convex/NodeQueries.hs | 4 +- src/base/lib/Convex/PlutusLedger.hs | 95 ++-- src/base/lib/Convex/Scripts.hs | 27 +- src/base/lib/Convex/Utils.hs | 4 +- src/base/lib/Convex/Utxos.hs | 82 +-- .../convex-coin-selection.cabal | 17 +- src/coin-selection/lib/Convex/BuildTx.hs | 49 +- .../lib/Convex/CoinSelection.hs | 115 ++-- .../lib/Convex/CoinSelection/CardanoApi.hs | 183 ------- src/coin-selection/test/Scripts.hs | 20 +- src/coin-selection/test/Spec.hs | 33 +- src/devnet/config/devnet/cardano-node.json | 5 +- src/devnet/config/devnet/genesis-alonzo.json | 509 ++++++------------ src/devnet/config/devnet/genesis-conway.json | 4 + src/devnet/convex-devnet.cabal | 4 +- src/devnet/lib/Convex/Devnet/CardanoNode.hs | 7 + src/devnet/lib/Convex/Devnet/Logging.hs | 24 +- src/devnet/lib/Convex/Devnet/NodeQueries.hs | 15 +- src/devnet/lib/Convex/Devnet/Utils.hs | 2 +- src/devnet/test/Spec.hs | 2 +- src/mockchain/convex-mockchain.cabal | 8 +- src/mockchain/lib/Convex/MockChain.hs | 164 +++--- .../lib/Convex/MockChain/Defaults.hs | 230 +++++--- src/mockchain/lib/Convex/NodeParams.hs | 19 +- src/node-client/convex-node-client.cabal | 1 + src/wallet/convex-wallet.cabal | 2 +- 38 files changed, 880 insertions(+), 1300 deletions(-) rename node-config/mainnet/{mainnet-alonzo-genesis.json => alonzo-genesis.json} (100%) rename node-config/mainnet/{mainnet-byron-genesis.json => byron-genesis.json} (100%) create mode 100644 node-config/mainnet/conway-genesis.json rename node-config/mainnet/{mainnet-shelley-genesis.json => shelley-genesis.json} (100%) delete mode 100644 src/coin-selection/lib/Convex/CoinSelection/CardanoApi.hs create mode 100644 src/devnet/config/devnet/genesis-conway.json diff --git a/.github/workflows/ci-linux.yaml b/.github/workflows/ci-linux.yaml index 5bf68f46..0692da87 100644 --- a/.github/workflows/ci-linux.yaml +++ b/.github/workflows/ci-linux.yaml @@ -88,8 +88,8 @@ jobs: - uses: haskell/actions/setup@v1 with: - ghc-version: '8.10' # Resolves to the latest point release of GHC 8.10 - cabal-version: '3.6.0.0' # Exact version of Cabal + ghc-version: '9.2.8' + cabal-version: '3.10.1.0' - uses: actions/checkout@v2 @@ -101,7 +101,8 @@ jobs: - name: Build dependencies for integration test run: | cabal update - cabal install -j cardano-node cardano-cli --overwrite-policy=always + cabal install -j cardano-node --overwrite-policy=always + cabal install -j cardano-cli-8.4.0.0 --overwrite-policy=always echo "/home/runner/.cabal/bin" >> $GITHUB_PATH - name: build & test diff --git a/.gitignore b/.gitignore index 5011bda9..951a15cb 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,5 @@ cabal.project.local~ .ghc.environment.* result .vscode -work/ \ No newline at end of file +work/ +nohup.out \ No newline at end of file diff --git a/cabal.project b/cabal.project index 8da9b520..45848312 100644 --- a/cabal.project +++ b/cabal.project @@ -13,169 +13,24 @@ repository cardano-haskell-packages c00aae8461a256275598500ea0e187588c35a5d5d7454fb57eac18d9edb86a56 d4a35cd3121aa00d18544bb0ac01c3e1691d618f462c46129271bccf39f7e8ee -index-state: - 2022-09-27T00:00:00Z - , cardano-haskell-packages 2022-10-25T20:00:00Z +index-state: + , hackage.haskell.org 2023-07-22T22:41:49Z + , cardano-haskell-packages 2023-07-26T01:36:26Z -with-compiler: ghc-8.10.7 + +with-compiler: ghc-9.2.8 packages: src/base - src/coin-selection - src/devnet - src/mockchain src/node-client src/wallet - src/un-ada - -source-repository-package - type: git - location: https://github.com/input-output-hk/bech32 - tag: ab61914443e5f53624d3b2995767761b3f68e576 - --sha256: 0isqh5s6rdhmqa3jhvc32zb3kvzy149hmzddx1ld9f9jhls4f3wg - subdir: bech32 - bech32-th - -source-repository-package - type: git - location: https://github.com/input-output-hk/cardano-crypto - tag: f73079303f663e028288f9f4a9e08bcca39a923e - --sha256: 1n87i15x54s0cjkh3nsxs4r1x016cdw1fypwmr68936n3xxsjn6q - -source-repository-package - type: git - location: https://github.com/input-output-hk/ekg-forward - tag: 297cd9db5074339a2fb2e5ae7d0780debb670c63 - --sha256: 1zcwry3y5rmd9lgxy89wsb3k4kpffqji35dc7ghzbz603y1gy24g - --- It seems that if we remove this source-repository-package to rely on CHaP, --- for some reason, we're unable to retrieve the cardano-node executables in --- our nix/haskell.nix file. - --- Without this source-repository-package: --- config.hsPkgs.cardano-node.components.exes --- => [] --- --- With: --- config.hsPkgs.cardano-node.components.exes --- => [ "cardano-node" ] --- --- TODO [ADP-2447] See if the situation has improved and try to remove this source-repository-package. -source-repository-package - type: git - location: https://github.com/input-output-hk/cardano-node - tag: ebc7be471b30e5931b35f9bbc236d21c375b91bb - --sha256: 1j01m2cp2vdcl26zx9xmipr551v3b2rz9kfn9ik8byfwj1z7652r - subdir: - cardano-api - cardano-git-rev - cardano-cli - cardano-node - cardano-node-chairman - trace-dispatcher - trace-resources - trace-forward - -source-repository-package - type: git - location: https://github.com/input-output-hk/cardano-sl-x509 - tag: a91add165152fa36f08e95fafe7da24f1dba4690 - --sha256: 1ia8vlqghis92cla8qmqa6kh8f3jn29b01fshyk5hmgy5373s684 - --- Different version than from CHaP to include the ReaderT fix. --- TODO [ADP-2447] This source-repository-package should be removable with next node bump. -source-repository-package - type: git - location: https://github.com/input-output-hk/io-sim - tag: 57e888b1894829056cb00b7b5785fdf6a74c3271 - --sha256: 1kv8lwmrw1c0g03jy3i3fgk3c8d47ihjcslg295djqj442y95y2f - subdir: - io-classes - io-sim - strict-stm - -source-repository-package - type: git - location: https://github.com/j-mueller/annealing - tag: ea8e9ec8cf63796205372cedb265836cb8e526b2 - -source-repository-package - type: git - location: https://github.com/j-mueller/csv - tag: b2f00d7819ff62cb80532adfbc28dbc1046d3d96 - --- ------------------------------------------------------------------------- --- Constraints tweaking - --- cardano-addresses unit tests bring in some version constraint conflicts. --- --- 1. hjsonschema and hjsonpointer deps have overly strict bounds. --- 2. it has strict aeson < 1.5 dep - this will be fixed in the next release. -allow-newer: - hjsonschema:* - , hjsonpointer:* - , cardano-sl-x509:ip - , *:aeson - , size-based:template-haskell - --- Copied from (copied from cardano-node/cabal.project) -allow-newer: - *:aeson, - monoidal-containers:aeson, - size-based:template-haskell - -allow-newer: - async-timer:unliftio-core -constraints: - bimap >= 0.4.0 - , openapi3 >= 3.2.0 - , libsystemd-journal >= 1.4.4 - , systemd >= 2.3.0 - -- dependency of systemd-2.3.0 - , network >= 3.1.1.1 - -- choose versions that work with base >= 4.12 - , hjsonpointer >= 1.5.0 - , hjsonschema >= 1.10.0 - , Cabal >= 3.4.0.0 - , async-timer >= 0.2.0.0 - , unliftio-core >= 0.2.0.1 - , cardano-api == 1.35.4 - , cardano-node == 1.35.4 - , generic-arbitrary == 0.2.2 - , iohk-monitoring >= 0.1.11 - - -- Could probably be bumped with minor work in the wallet - , resource-pool == 0.2.3.2 + src/mockchain + src/coin-selection + src/devnet - -- TH Name shadowing warnings need to be addressed when bumping to 2.13.3.5 - , persistent == 2.13.3.3 +-- https://github.com/obsidiansystems/dependent-sum-template/issues/5 +-- requires cabal 3.10 +if impl(ghc >= 9.2) + constraints : + dependent-sum-template < 0.1.2 - -- Copied from cardano-node's cabal.project: - , bimap >= 0.4.0 - , libsystemd-journal >= 1.4.4 - , systemd >= 2.3.0 - -- systemd-2.3.0 requires at least network 3.1.1.0 but it doesn't declare - -- that dependency - , network >= 3.1.1.0 - , HSOpenSSL >= 0.11.7.2 - , algebraic-graphs < 0.7 - , protolude < 0.3.1 - , cardano-prelude == 0.1.0.0 - , base-deriving-via == 0.1.0.0 - , cardano-binary == 1.5.0 - , cardano-binary-test == 1.3.0 - , cardano-crypto-class == 2.0.0.0.1 - , cardano-crypto-praos == 2.0.0.0.1 - , cardano-crypto-tests == 2.0.0.0.1 - , cardano-slotting == 0.1.0.0 - , measures == 0.1.0.0 - , orphans-deriving-via == 0.1.0.0 - , strict-containers == 0.1.0.0 - , plutus-core == 1.0.0.1 - , plutus-ledger-api == 1.0.0.1 - , plutus-tx == 1.0.0.0 - , plutus-tx-plugin == 1.0.0.0 - , prettyprinter-configurable == 0.1.0.0 - , plutus-ghc-stub == 8.6.5 - , word-array == 0.1.0.0 - , word-array == 0.1.0.0 diff --git a/node-config/mainnet/mainnet-alonzo-genesis.json b/node-config/mainnet/alonzo-genesis.json similarity index 100% rename from node-config/mainnet/mainnet-alonzo-genesis.json rename to node-config/mainnet/alonzo-genesis.json diff --git a/node-config/mainnet/mainnet-byron-genesis.json b/node-config/mainnet/byron-genesis.json similarity index 100% rename from node-config/mainnet/mainnet-byron-genesis.json rename to node-config/mainnet/byron-genesis.json diff --git a/node-config/mainnet/conway-genesis.json b/node-config/mainnet/conway-genesis.json new file mode 100644 index 00000000..4525ef4a --- /dev/null +++ b/node-config/mainnet/conway-genesis.json @@ -0,0 +1,3 @@ +{ + "genDelegs": {} +} diff --git a/node-config/mainnet/mainnet-config.json b/node-config/mainnet/mainnet-config.json index 6e97e287..dd72258d 100644 --- a/node-config/mainnet/mainnet-config.json +++ b/node-config/mainnet/mainnet-config.json @@ -1,103 +1,103 @@ { - "AlonzoGenesisFile": "mainnet-alonzo-genesis.json", - "AlonzoGenesisHash": "7e94a15f55d1e82d10f09203fa1d40f8eede58fd8066542cf6566008068ed874", - "ApplicationName": "cardano-sl", - "ApplicationVersion": 1, - "ByronGenesisFile": "mainnet-byron-genesis.json", - "ByronGenesisHash": "5f20df933584822601f9e3f8c024eb5eb252fe8cefb24d1317dc3d432e940ebb", - "EnableP2P": false, - "LastKnownBlockVersion-Alt": 0, - "LastKnownBlockVersion-Major": 3, - "LastKnownBlockVersion-Minor": 0, - "MaxKnownMajorProtocolVersion": 2, - "Protocol": "Cardano", - "RequiresNetworkMagic": "RequiresNoMagic", - "ShelleyGenesisFile": "mainnet-shelley-genesis.json", - "ShelleyGenesisHash": "1a3be38bcbb7911969283716ad7aa550250226b76a61fc51cc9a9a35d9276d81", - "TraceAcceptPolicy": true, - "TraceBlockFetchClient": false, - "TraceBlockFetchDecisions": false, - "TraceBlockFetchProtocol": false, - "TraceBlockFetchProtocolSerialised": false, - "TraceBlockFetchServer": false, - "TraceChainDb": true, - "TraceChainSyncBlockServer": false, - "TraceChainSyncClient": false, - "TraceChainSyncHeaderServer": false, - "TraceChainSyncProtocol": false, - "TraceConnectionManager": true, - "TraceDNSResolver": true, - "TraceDNSSubscription": true, - "TraceDiffusionInitialization": true, - "TraceErrorPolicy": true, - "TraceForge": true, - "TraceHandshake": false, - "TraceInboundGovernor": true, - "TraceIpSubscription": true, - "TraceLedgerPeers": true, - "TraceLocalChainSyncProtocol": false, - "TraceLocalErrorPolicy": true, - "TraceLocalHandshake": false, - "TraceLocalRootPeers": true, - "TraceLocalTxSubmissionProtocol": false, - "TraceLocalTxSubmissionServer": false, - "TraceMempool": true, - "TraceMux": false, - "TracePeerSelection": true, - "TracePeerSelectionActions": true, - "TracePublicRootPeers": true, - "TraceServer": true, - "TraceTxInbound": false, - "TraceTxOutbound": false, - "TraceTxSubmissionProtocol": false, - "TracingVerbosity": "NormalVerbosity", - "TurnOnLogMetrics": true, - "TurnOnLogging": true, - "defaultBackends": [ - "KatipBK" - ], - "defaultScribes": [ - [ - "StdoutSK", - "stdout" + "AlonzoGenesisFile": "alonzo-genesis.json", + "AlonzoGenesisHash": "7e94a15f55d1e82d10f09203fa1d40f8eede58fd8066542cf6566008068ed874", + "ApplicationName": "cardano-sl", + "ApplicationVersion": 1, + "ByronGenesisFile": "byron-genesis.json", + "ByronGenesisHash": "5f20df933584822601f9e3f8c024eb5eb252fe8cefb24d1317dc3d432e940ebb", + "ConwayGenesisFile": "conway-genesis.json", + "ConwayGenesisHash": "f28f1c1280ea0d32f8cd3143e268650d6c1a8e221522ce4a7d20d62fc09783e1", + "LastKnownBlockVersion-Alt": 0, + "LastKnownBlockVersion-Major": 3, + "LastKnownBlockVersion-Minor": 0, + "MaxKnownMajorProtocolVersion": 2, + "Protocol": "Cardano", + "RequiresNetworkMagic": "RequiresNoMagic", + "ShelleyGenesisFile": "shelley-genesis.json", + "ShelleyGenesisHash": "1a3be38bcbb7911969283716ad7aa550250226b76a61fc51cc9a9a35d9276d81", + "TraceAcceptPolicy": true, + "TraceBlockFetchClient": false, + "TraceBlockFetchDecisions": false, + "TraceBlockFetchProtocol": false, + "TraceBlockFetchProtocolSerialised": false, + "TraceBlockFetchServer": false, + "TraceChainDb": true, + "TraceChainSyncBlockServer": false, + "TraceChainSyncClient": false, + "TraceChainSyncHeaderServer": false, + "TraceChainSyncProtocol": false, + "TraceConnectionManager": true, + "TraceDNSResolver": true, + "TraceDNSSubscription": true, + "TraceDiffusionInitialization": true, + "TraceErrorPolicy": true, + "TraceForge": true, + "TraceHandshake": false, + "TraceInboundGovernor": true, + "TraceIpSubscription": true, + "TraceLedgerPeers": true, + "TraceLocalChainSyncProtocol": false, + "TraceLocalErrorPolicy": true, + "TraceLocalHandshake": false, + "TraceLocalRootPeers": true, + "TraceLocalTxSubmissionProtocol": false, + "TraceLocalTxSubmissionServer": false, + "TraceMempool": true, + "TraceMux": false, + "TracePeerSelection": true, + "TracePeerSelectionActions": true, + "TracePublicRootPeers": true, + "TraceServer": true, + "TraceTxInbound": false, + "TraceTxOutbound": false, + "TraceTxSubmissionProtocol": false, + "TracingVerbosity": "NormalVerbosity", + "TurnOnLogMetrics": true, + "TurnOnLogging": true, + "defaultBackends": [ + "KatipBK" + ], + "defaultScribes": [ + [ + "StdoutSK", + "stdout" + ] + ], + "hasEKG": 12788, + "hasPrometheus": [ + "127.0.0.1", + 12798 + ], + "minSeverity": "Info", + "options": { + "mapBackends": { + "cardano.node.metrics": [ + "EKGViewBK" + ], + "cardano.node.resources": [ + "EKGViewBK" ] - ], - "hasEKG": 12788, - "hasPrometheus": [ - "127.0.0.1", - 12798 - ], - "minSeverity": "Info", - "options": { - "mapBackends": { - "cardano.node.metrics": [ - "EKGViewBK" - ], - "cardano.node.resources": [ - "EKGViewBK" - ] - }, - "mapSubtrace": { - "cardano.node.metrics": { - "subtrace": "Neutral" - } - } }, - "rotation": { - "rpKeepFilesNum": 10, - "rpLogLimitBytes": 5000000, - "rpMaxAgeHours": 24 - }, - "setupBackends": [ - "KatipBK" - ], - "setupScribes": [ - { - "scFormat": "ScText", - "scKind": "StdoutSK", - "scName": "stdout", - "scRotation": null + "mapSubtrace": { + "cardano.node.metrics": { + "subtrace": "Neutral" } - ] - } - \ No newline at end of file + } + }, + "rotation": { + "rpKeepFilesNum": 10, + "rpLogLimitBytes": 5000000, + "rpMaxAgeHours": 24 + }, + "setupBackends": [ + "KatipBK" + ], + "setupScribes": [ + { + "scFormat": "ScText", + "scKind": "StdoutSK", + "scName": "stdout", + "scRotation": null + } + ] +} diff --git a/node-config/mainnet/mainnet-shelley-genesis.json b/node-config/mainnet/shelley-genesis.json similarity index 100% rename from node-config/mainnet/mainnet-shelley-genesis.json rename to node-config/mainnet/shelley-genesis.json diff --git a/src/base/convex-base.cabal b/src/base/convex-base.cabal index db0b50be..ab00ab91 100644 --- a/src/base/convex-base.cabal +++ b/src/base/convex-base.cabal @@ -42,7 +42,7 @@ library Convex.Utxos hs-source-dirs: lib build-depends: - base >= 4.14.0, + base >= 4.14 && < 4.19, lens, containers, aeson, @@ -55,22 +55,23 @@ library time build-depends: - cardano-api, - cardano-ledger-shelley, - small-steps, + cardano-api == 8.8.0.0, + cardano-ledger-binary, cardano-ledger-core, - cardano-ledger-babbage, + cardano-crypto-wrapper, + cardano-ledger-byron, + cardano-ledger-mary, + cardano-ledger-shelley, + cardano-ledger-babbage, cardano-ledger-alonzo, - cardano-ledger-shelley-ma, - ouroboros-consensus-shelley, - cardano-crypto-wrapper, + ouroboros-consensus, ouroboros-consensus-cardano, - plutus-ledger-api, - ouroboros-network, + ouroboros-network-protocols, cardano-slotting, plutus-tx, + plutus-ledger-api, serialise, bytestring, dlist, diff --git a/src/base/lib/Convex/Class.hs b/src/base/lib/Convex/Class.hs index ba40baba..da731343 100644 --- a/src/base/lib/Convex/Class.hs +++ b/src/base/lib/Convex/Class.hs @@ -29,10 +29,8 @@ import Cardano.Api.Shelley (BabbageEra, LocalNodeConnectInfo, NetworkId, PoolId, - ProtocolParameters, SlotNo, Tx, TxId) -import qualified Cardano.Ledger.Core as Core import Cardano.Ledger.Shelley.API (UTxO) import Cardano.Slotting.Time (SlotLength, SystemStart) @@ -51,7 +49,6 @@ import qualified Control.Monad.State.Strict as StrictStat import Control.Monad.Trans.Except (ExceptT) import Control.Monad.Trans.Except.Result (ResultT) import Convex.Era (ERA) -import qualified Convex.Era as Ledger.Era import Convex.MonadLog (MonadLog (..), logInfoS, logWarnS) @@ -62,14 +59,14 @@ import Data.Time.Clock (UTCTime) import Ouroboros.Consensus.HardFork.History (interpretQuery, slotToSlotLength) import Ouroboros.Network.Protocol.LocalTxSubmission.Type (SubmitResult (..)) -import qualified Plutus.V1.Ledger.Time as PV1 +import qualified PlutusLedgerApi.V1 as PV1 {-| Send transactions and resolve tx inputs. -} class Monad m => MonadBlockchain m where sendTx :: Tx BabbageEra -> m TxId -- ^ Submit a transaction to the network utxoByTxIn :: Set C.TxIn -> m (C.UTxO C.BabbageEra) -- ^ Resolve tx inputs - queryProtocolParameters :: m (ProtocolParameters, Core.PParams Ledger.Era.ERA) -- ^ Get the protocol parameters + queryProtocolParameters :: m (C.BundledProtocolParameters C.BabbageEra) -- ^ Get the protocol parameters queryStakePools :: m (Set PoolId) -- ^ Get the stake pools querySystemStart :: m SystemStart queryEraHistory :: m (EraHistory CardanoMode) @@ -194,12 +191,14 @@ nextSlot = modifySlot (\s -> (succ s, ())) data MonadBlockchainError e = MonadBlockchainError e + | ProtocolConversionError C.ProtocolParametersConversionError | FailWith String deriving (Eq) instance Show e => Show (MonadBlockchainError e) where - show (MonadBlockchainError e) = show e - show (FailWith str) = str + show (MonadBlockchainError e) = show e + show (FailWith str) = str + show (ProtocolConversionError e) = show e {-| 'MonadBlockchain' implementation that connects to a cardano node -} @@ -256,7 +255,9 @@ instance (MonadLog m, MonadIO m) => MonadBlockchain (MonadBlockchainCardanoNodeT queryProtocolParameters = do p <- runQuery' (C.QueryInEra C.BabbageEraInCardanoMode (C.QueryInShelleyBasedEra C.ShelleyBasedEraBabbage C.QueryProtocolParameters)) - return (p, C.toLedgerPParams C.ShelleyBasedEraBabbage p) + case C.bundleProtocolParams C.BabbageEra p of + Right x -> pure x + Left err -> MonadBlockchainCardanoNodeT $ throwError (ProtocolConversionError err) queryStakePools = runQuery' (C.QueryInEra C.BabbageEraInCardanoMode (C.QueryInShelleyBasedEra C.ShelleyBasedEraBabbage C.QueryStakePools)) diff --git a/src/base/lib/Convex/Event.hs b/src/base/lib/Convex/Event.hs index acb9db5c..5c2bf396 100644 --- a/src/base/lib/Convex/Event.hs +++ b/src/base/lib/Convex/Event.hs @@ -24,48 +24,50 @@ module Convex.Event( extractBabbageTxn ) where -import Cardano.Api (BabbageEra, Block (..), - BlockHeader, - BlockInMode (..), BlockNo, - CardanoMode, EraInMode (..), - ScriptHash, SlotNo, Tx (..), - TxId, TxIn (..), TxIx (..)) -import qualified Cardano.Api as C -import Cardano.Api.Shelley (TxBody (..)) -import qualified Cardano.Api.Shelley as CS -import qualified Cardano.Ledger.Address as Address -import Cardano.Ledger.Alonzo.Data (Data, DataHash) -import qualified Cardano.Ledger.Alonzo.Data as Alonzo.Data -import qualified Cardano.Ledger.Alonzo.Scripts as Scripts -import qualified Cardano.Ledger.Alonzo.TxWitness as TxWitness -import qualified Cardano.Ledger.Babbage as Babbage -import qualified Cardano.Ledger.Babbage.TxBody as Babbage.TxBody -import qualified Cardano.Ledger.BaseTypes as CT -import qualified Cardano.Ledger.Credential as Credential -import Cardano.Ledger.Crypto (StandardCrypto) -import qualified Cardano.Ledger.Era as Era -import Cardano.Ledger.Keys (KeyHash, KeyRole (Witness)) -import qualified Cardano.Ledger.Serialization -import Cardano.Ledger.Shelley.Metadata (Metadatum) -import Cardano.Ledger.Shelley.TxBody (witKeyHash) -import qualified Cardano.Ledger.TxIn as CT -import Control.Monad.State.Strict (MonadState, get, put, - runState) -import Convex.Era (ERA) -import Data.Bifunctor (Bifunctor (..)) -import Data.Foldable (foldl', toList) -import Data.List (sortOn) -import Data.List.NonEmpty (NonEmpty (..)) -import Data.Map.Strict (Map) -import qualified Data.Map.Strict as Map -import Data.Maybe (catMaybes, mapMaybe, - maybeToList) -import qualified Data.Set as Set -import Data.Word (Word64) -import GHC.Generics (Generic) -import Ouroboros.Consensus.Shelley.Eras (StandardBabbage) - -type ScriptOutDataHash = DataHash (Era.Crypto ERA) +import Cardano.Api (BabbageEra, Block (..), + BlockHeader, + BlockInMode (..), BlockNo, + CardanoMode, + EraInMode (..), ScriptHash, + SlotNo, Tx (..), TxId, + TxIn (..), TxIx (..)) +import qualified Cardano.Api as C +import Cardano.Api.Shelley (TxBody (..)) +import qualified Cardano.Api.Shelley as CS +import qualified Cardano.Ledger.Address as Address +import qualified Cardano.Ledger.Alonzo.Scripts as Scripts +import Cardano.Ledger.Alonzo.Scripts.Data (Data, DataHash) +import Cardano.Ledger.Alonzo.TxAuxData (AlonzoTxAuxData (..)) +import qualified Cardano.Ledger.Alonzo.TxWits as TxWitness +import qualified Cardano.Ledger.Babbage as Babbage +import qualified Cardano.Ledger.Babbage.TxBody as Babbage.TxBody +import qualified Cardano.Ledger.Babbage.TxOut +import qualified Cardano.Ledger.BaseTypes as CT +import qualified Cardano.Ledger.Binary +import qualified Cardano.Ledger.Credential as Credential +import Cardano.Ledger.Crypto (StandardCrypto) +import qualified Cardano.Ledger.Era as Era +import Cardano.Ledger.Keys (KeyHash, KeyRole (Witness)) +import Cardano.Ledger.Shelley.TxAuxData (Metadatum) +import Cardano.Ledger.Shelley.TxBody (witVKeyHash) +import qualified Cardano.Ledger.TxIn as CT +import Control.Monad.State.Strict (MonadState, get, put, + runState) +import Convex.Era (ERA) +import Data.Bifunctor (Bifunctor (..)) +import Data.Foldable (foldl', toList) +import Data.List (sortOn) +import Data.List.NonEmpty (NonEmpty (..)) +import Data.Map.Strict (Map) +import qualified Data.Map.Strict as Map +import Data.Maybe (catMaybes, mapMaybe, + maybeToList) +import qualified Data.Set as Set +import Data.Word (Word64) +import GHC.Generics (Generic) +import Ouroboros.Consensus.Shelley.Eras (StandardBabbage) + +type ScriptOutDataHash = DataHash (Era.EraCrypto ERA) type Extract a = C.TxOut C.CtxTx C.BabbageEra -> ScriptHash -> Maybe a @@ -135,7 +137,7 @@ extractBabbageBlock :: Extract a -> ResolvedInputs a -> Block BabbageEra -> ([Tx extractBabbageBlock ex resolvedInputs (Block blockHeader txns) = first catMaybes $ flip runState resolvedInputs $ traverse (extractBabbageTxn ex blockHeader) txns -type ScriptOut = Babbage.TxBody.TxOut (Babbage.BabbageEra StandardCrypto) +type ScriptOut = Babbage.TxBody.BabbageTxOut (Babbage.BabbageEra StandardCrypto) extractBabbageTxn' :: ResolvedInputs a -> Extract a -> BlockHeader -> Tx BabbageEra -> ([TxWithEvents a], ResolvedInputs a) extractBabbageTxn' resolvedInputs ex blockHeader tx = @@ -146,7 +148,7 @@ extractBabbageTxn ex (C.BlockHeader slotNo _ twBlock@(C.BlockNo blockNo)) twTx@( ResolvedInputs resolvedInputs <- get let txId = C.getTxId txBody ShelleyTxBody _ txBody' _scripts scriptData auxiliaryData _ = txBody - Babbage.TxBody.TxBody{Babbage.TxBody.outputs, Babbage.TxBody.inputs} = txBody' + Babbage.TxBody.BabbageTxBody{Babbage.TxBody.btbOutputs, Babbage.TxBody.btbInputs} = txBody' TxWitness.TxDats' txDats = case scriptData of C.TxBodyScriptData C.ScriptDataInBabbageEra txDats' _ -> txDats' _ -> mempty @@ -157,7 +159,7 @@ extractBabbageTxn ex (C.BlockHeader slotNo _ twBlock@(C.BlockNo blockNo)) twTx@( capiTxOuts = C.fromLedgerTxOuts C.ShelleyBasedEraBabbage txBody' scriptData mapOutput :: TxIx -> (ScriptOut, C.TxOut C.CtxTx C.BabbageEra) -> Maybe (ScriptHash, ScriptOut, TxIx, ScriptOutDataHash, a) - mapOutput ix (scriptOut@(Babbage.TxBody.TxOut address _value (Babbage.TxBody.DatumHash dataHash) _), capiOut) = case address of -- FIXME: Could also be Datum? + mapOutput ix (scriptOut@(Cardano.Ledger.Babbage.TxOut.BabbageTxOut address _value (Babbage.TxBody.DatumHash dataHash) _), capiOut) = case address of -- FIXME: Could also be Datum? Address.Addr _network paymentCredential _stakeReference -> case paymentCredential of Credential.ScriptHashObj hsh -> let hsh' = CS.fromShelleyScriptHash hsh in @@ -168,7 +170,7 @@ extractBabbageTxn ex (C.BlockHeader slotNo _ twBlock@(C.BlockNo blockNo)) twTx@( _ -> Nothing mapOutput _ _ = Nothing - relevantOutputs = mapMaybe (uncurry mapOutput) (zip (toEnum <$> [0..]) (fmap (first Cardano.Ledger.Serialization.sizedValue) $ zip (toList outputs) capiTxOuts)) + relevantOutputs = mapMaybe (uncurry mapOutput) (zip (toEnum <$> [0..]) (fmap (first Cardano.Ledger.Binary.sizedValue) $ zip (toList btbOutputs) capiTxOuts)) outputEvents :: [NewOutputEvent a] outputEvents = fmap mkEvent relevantOutputs where @@ -185,7 +187,7 @@ extractBabbageTxn ex (C.BlockHeader slotNo _ twBlock@(C.BlockNo blockNo)) twTx@( , neDatum , neDataHash , neSigners = mapMaybe getKeyWitness keyWitnesses - , neTxMetadata = maybe mempty (\(Alonzo.Data.AuxiliaryData meta _) -> meta) auxiliaryData + , neTxMetadata = maybe mempty (\(AlonzoTxAuxData meta _ _) -> meta) auxiliaryData } outputSpentEvents :: [OutputSpentEvent a] @@ -197,7 +199,7 @@ extractBabbageTxn ex (C.BlockHeader slotNo _ twBlock@(C.BlockNo blockNo)) twTx@( $ zip [0..] $ fmap (uncurry TxIn . first CS.fromShelleyTxId . second txIx . (\(CT.TxIn i n) -> (i, n))) $ sortOn id - $ Set.toList inputs + $ Set.toList btbInputs resolvedInputsDeleted = ResolvedInputs (foldl' (\inp OutputSpentEvent{oseTxIn} -> Map.delete oseTxIn inp) resolvedInputs outputSpentEvents) @@ -215,7 +217,7 @@ convertScript = \case getKeyWitness :: C.KeyWitness BabbageEra -> Maybe (KeyHash 'Witness StandardCrypto) getKeyWitness = \case - CS.ShelleyKeyWitness _era withVKey -> Just $ witKeyHash withVKey + CS.ShelleyKeyWitness _era withVKey -> Just $ witVKeyHash withVKey _ -> Nothing txIx :: CT.TxIx -> TxIx diff --git a/src/base/lib/Convex/Lenses.hs b/src/base/lib/Convex/Lenses.hs index 374a7fcd..5940a048 100644 --- a/src/base/lib/Convex/Lenses.hs +++ b/src/base/lib/Convex/Lenses.hs @@ -2,6 +2,7 @@ {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} {-| Lenses for @cardano-api@ types @@ -93,23 +94,22 @@ import qualified Cardano.Ledger.BaseTypes as Shelley import qualified Cardano.Ledger.Core as Core import qualified Cardano.Ledger.Credential as Credential import Cardano.Ledger.Crypto (StandardCrypto) -import Cardano.Ledger.Era (Era) import qualified Cardano.Ledger.Hashes as Hashes import qualified Cardano.Ledger.Keys as Keys import Cardano.Ledger.Shelley.API (Coin, LedgerEnv (..), UTxO, UTxOState (..)) +import Cardano.Ledger.Shelley.Governance (EraGovernance (GovernanceState)) import Cardano.Ledger.Shelley.LedgerState (LedgerState (..), - smartUTxOState) + updateStakeDistribution) import Control.Lens (Iso', Lens', Prism', iso, lens, prism') -import Control.State.Transition (STS (State)) import qualified Convex.Scripts as Scripts import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Proxy (Proxy (..)) import Data.Word (Word64) -import qualified Plutus.V1.Ledger.Api as PV1 -import Plutus.V1.Ledger.Crypto (PubKeyHash (..)) +import PlutusLedgerApi.V1 (PubKeyHash (..)) +import qualified PlutusLedgerApi.V1 as PV1 import qualified PlutusTx.Prelude as PlutusTx {-| 'TxBodyContent' with all fields set to empty, none, default values @@ -134,6 +134,8 @@ emptyTx = , C.txUpdateProposal = C.TxUpdateProposalNone , C.txMintValue = C.TxMintNone , C.txScriptValidity = C.TxScriptValidityNone + , C.txGovernanceActions = C.TxGovernanceActionsNone + , C.txVotes = C.TxVotesNone } type TxIn v = (C.TxIn, BuildTxWith v (C.Witness C.WitCtxTxIn BabbageEra)) @@ -282,20 +284,20 @@ _TxOutDatumHash = prism' from to where from :: C.Hash C.ScriptData -> TxOutDatum ctx C.BabbageEra from h = C.TxOutDatumHash C.ScriptDataInBabbageEra h -_TxOutDatumInTx :: Prism' (TxOutDatum CtxTx C.BabbageEra) C.ScriptData +_TxOutDatumInTx :: Prism' (TxOutDatum CtxTx C.BabbageEra) C.HashableScriptData _TxOutDatumInTx = prism' from to where - to :: TxOutDatum CtxTx C.BabbageEra -> Maybe C.ScriptData + to :: TxOutDatum CtxTx C.BabbageEra -> Maybe C.HashableScriptData to (C.TxOutDatumInTx _ k) = Just k to _ = Nothing - from :: C.ScriptData -> TxOutDatum CtxTx C.BabbageEra + from :: C.HashableScriptData -> TxOutDatum CtxTx C.BabbageEra from cd = C.TxOutDatumInTx C.ScriptDataInBabbageEra cd -_TxOutDatumInline :: Prism' (TxOutDatum CtxTx C.BabbageEra) C.ScriptData +_TxOutDatumInline :: Prism' (TxOutDatum CtxTx C.BabbageEra) C.HashableScriptData _TxOutDatumInline = prism' from to where - to :: TxOutDatum CtxTx C.BabbageEra -> Maybe C.ScriptData + to :: TxOutDatum CtxTx C.BabbageEra -> Maybe C.HashableScriptData to (C.TxOutDatumInline _ k) = Just k to _ = Nothing - from :: C.ScriptData -> TxOutDatum CtxTx C.BabbageEra + from :: C.HashableScriptData -> TxOutDatum CtxTx C.BabbageEra from cd = C.TxOutDatumInline C.ReferenceTxInsScriptsInlineDatumsInBabbageEra cd _ShelleyAddressInBabbageEra :: Prism' (C.AddressInEra C.BabbageEra) (Shelley.Network, Credential.PaymentCredential StandardCrypto, Credential.StakeReference StandardCrypto) @@ -373,10 +375,11 @@ slot = lens get set_ where {-| 'UTxOState' iso. Note that this doesn't touch the '_stakeDistro' field. This is because the stake distro is a function of @utxo :: UTxO era@ and can be computed by @updateStakeDistribution mempty mempty utxo@. -} -_UTxOState :: forall era. Era era => Iso' (UTxOState era) (UTxO era, Coin, Coin, State (Core.EraRule "PPUP" era)) -_UTxOState = iso from to where - from UTxOState{_utxo, _deposited, _fees, _ppups} = (_utxo, _deposited, _fees, _ppups) - to (utxo, deposited, fees, pups) = smartUTxOState @era utxo deposited fees pups +_UTxOState :: forall era. (Core.EraTxOut era) => Core.PParams era -> Iso' (UTxOState era) (UTxO era, Coin, Coin, GovernanceState era) +_UTxOState pp = iso from to where + from UTxOState{utxosUtxo, utxosDeposited, utxosFees, utxosGovernance} = (utxosUtxo, utxosDeposited, utxosFees, utxosGovernance) + to (utxosUtxo, utxosDeposited, utxosFees, utxosGovernance) = UTxOState{utxosUtxo, utxosDeposited, utxosFees, utxosGovernance, utxosStakeDistr = updateStakeDistribution pp mempty mempty utxosUtxo} + utxoState :: Lens' (LedgerState era) (UTxOState era) utxoState = lens get set_ where @@ -416,7 +419,7 @@ _PlutusPubKeyHash = prism' from to where from = PubKeyHash . PlutusTx.toBuiltin . C.serialiseToRawBytes to :: PubKeyHash -> Maybe (C.Hash C.PaymentKey) - to (PubKeyHash h) = C.deserialiseFromRawBytes (C.proxyToAsType $ Proxy @(C.Hash C.PaymentKey)) $ PlutusTx.fromBuiltin h + to (PubKeyHash h) = either (const Nothing) Just $ C.deserialiseFromRawBytes (C.proxyToAsType $ Proxy @(C.Hash C.PaymentKey)) $ PlutusTx.fromBuiltin h _PaymentCredential :: Iso' C.PaymentCredential (Credential.PaymentCredential StandardCrypto) _PaymentCredential = iso from to where diff --git a/src/base/lib/Convex/NodeQueries.hs b/src/base/lib/Convex/NodeQueries.hs index c3fb1b45..0bbe51fc 100644 --- a/src/base/lib/Convex/NodeQueries.hs +++ b/src/base/lib/Convex/NodeQueries.hs @@ -44,7 +44,7 @@ loadConnectInfo :: -- ^ Node socket -> m (LocalNodeConnectInfo CardanoMode, Env) loadConnectInfo nodeConfigFilePath socketPath = do - (env, _) <- liftIO (runExceptT (CAPI.initialLedgerState nodeConfigFilePath)) >>= either throwError pure + (env, _) <- liftIO (runExceptT (CAPI.initialLedgerState (CAPI.File nodeConfigFilePath))) >>= either throwError pure -- Derive the NetworkId as described in network-magic.md from the -- cardano-ledger-specs repo. @@ -70,7 +70,7 @@ loadConnectInfo nodeConfigFilePath socketPath = do LocalNodeConnectInfo { localConsensusModeParams = cardanoModeParams, localNodeNetworkId = networkId, - localNodeSocketPath = socketPath + localNodeSocketPath = CAPI.File socketPath } pure (connectInfo, env) diff --git a/src/base/lib/Convex/PlutusLedger.hs b/src/base/lib/Convex/PlutusLedger.hs index 1ce1627c..4bb0aa8c 100644 --- a/src/base/lib/Convex/PlutusLedger.hs +++ b/src/base/lib/Convex/PlutusLedger.hs @@ -69,30 +69,31 @@ module Convex.PlutusLedger( ) where -import qualified Cardano.Api.Shelley as C -import Cardano.Ledger.BaseTypes (CertIx (..), TxIx (..)) -import Cardano.Ledger.Credential (Ptr (..)) -import qualified Cardano.Ledger.Mary.Value as Mary (AssetName (..)) -import qualified Codec.Serialise as Codec -import Control.Lens (Iso', Prism', iso, prism') -import qualified Data.ByteString.Lazy as BSL -import Data.ByteString.Short (fromShort) -import qualified Data.ByteString.Short as Short -import Data.Functor ((<&>)) -import Data.Time.Clock.POSIX (POSIXTime) -import qualified Plutus.V1.Ledger.Api as PV1 -import Plutus.V1.Ledger.Interval (Closure, Extended (..), - Interval (..), LowerBound (..), - UpperBound (..)) -import qualified Plutus.V1.Ledger.Scripts as P -import qualified Plutus.V1.Ledger.Value as Value -import qualified PlutusTx.Prelude as PlutusTx - -transScriptHash :: C.ScriptHash -> PV1.ValidatorHash -transScriptHash h = PV1.ValidatorHash (PV1.toBuiltin (C.serialiseToRawBytes h)) -- TODO: is serialiseToRawBytes the correct thing to do here? - -unTransScriptHash :: PV1.ValidatorHash -> Maybe C.ScriptHash -unTransScriptHash (PV1.ValidatorHash vh) = +import qualified Cardano.Api.Shelley as C +import Cardano.Ledger.BaseTypes (CertIx (..), TxIx (..)) +import Cardano.Ledger.Credential (Ptr (..)) +import qualified Cardano.Ledger.Mary.Value as Mary (AssetName (..)) +import qualified Codec.Serialise as Codec +import Control.Lens (Iso', Prism', iso, prism') +import qualified Data.ByteString.Lazy as BSL +import Data.ByteString.Short (fromShort) +import qualified Data.ByteString.Short as Short +import Data.Functor ((<&>)) +import Data.Time.Clock.POSIX (POSIXTime) +import PlutusLedgerApi.Common (SerialisedScript) +import qualified PlutusLedgerApi.V1 as PV1 +import PlutusLedgerApi.V1.Interval (Closure, Extended (..), + Interval (..), LowerBound (..), + UpperBound (..)) +import qualified PlutusLedgerApi.V1.Scripts as P +import qualified PlutusLedgerApi.V1.Value as Value +import qualified PlutusTx.Prelude as PlutusTx + +transScriptHash :: C.ScriptHash -> PV1.ScriptHash +transScriptHash h = PV1.ScriptHash (PV1.toBuiltin (C.serialiseToRawBytes h)) -- TODO: is serialiseToRawBytes the correct thing to do here? + +unTransScriptHash :: PV1.ScriptHash -> Either C.SerialiseAsRawBytesError C.ScriptHash +unTransScriptHash (PV1.ScriptHash vh) = C.deserialiseFromRawBytes C.AsScriptHash $ PlutusTx.fromBuiltin vh transAssetName :: Mary.AssetName -> PV1.TokenName @@ -101,33 +102,33 @@ transAssetName (Mary.AssetName bs) = PV1.TokenName (PV1.toBuiltin (fromShort bs) unTransAssetName :: PV1.TokenName -> C.AssetName unTransAssetName (PV1.TokenName bs) = C.AssetName $ PV1.fromBuiltin bs -transPolicyId :: C.PolicyId -> PV1.MintingPolicyHash -transPolicyId (C.PolicyId scriptHash) = PV1.MintingPolicyHash $ PlutusTx.toBuiltin (C.serialiseToRawBytes scriptHash) +transPolicyId :: C.PolicyId -> PV1.CurrencySymbol +transPolicyId (C.PolicyId scriptHash) = PV1.CurrencySymbol $ PlutusTx.toBuiltin (C.serialiseToRawBytes scriptHash) -unTransPolicyId :: PV1.MintingPolicyHash -> Maybe C.PolicyId -unTransPolicyId (PV1.MintingPolicyHash bs) = +unTransPolicyId :: PV1.CurrencySymbol -> Either C.SerialiseAsRawBytesError C.PolicyId +unTransPolicyId (PV1.CurrencySymbol bs) = C.deserialiseFromRawBytes C.AsPolicyId (PlutusTx.fromBuiltin bs) transAssetId :: C.AssetId -> Value.AssetClass transAssetId C.AdaAssetId = Value.assetClass PV1.adaSymbol PV1.adaToken transAssetId (C.AssetId policyId assetName) = Value.assetClass - (Value.mpsSymbol . transPolicyId $ policyId) + (transPolicyId $ policyId) (transAssetName $ toMaryAssetName assetName) toMaryAssetName :: C.AssetName -> Mary.AssetName toMaryAssetName (C.AssetName n) = Mary.AssetName $ Short.toShort n -unTransAssetId :: Value.AssetClass -> Maybe C.AssetId +unTransAssetId :: Value.AssetClass -> Either C.SerialiseAsRawBytesError C.AssetId unTransAssetId (Value.AssetClass (currencySymbol, tokenName)) | currencySymbol == PV1.adaSymbol && tokenName == PV1.adaToken = pure C.AdaAssetId | otherwise = C.AssetId - <$> unTransPolicyId (Value.currencyMPSHash currencySymbol) + <$> unTransPolicyId currencySymbol <*> pure (unTransAssetName tokenName) -unTransPubKeyHash :: PV1.PubKeyHash -> Maybe (C.Hash C.PaymentKey) +unTransPubKeyHash :: PV1.PubKeyHash -> Either C.SerialiseAsRawBytesError (C.Hash C.PaymentKey) unTransPubKeyHash (PV1.PubKeyHash pkh) = let bsx = PlutusTx.fromBuiltin pkh in C.deserialiseFromRawBytes (C.AsHash C.AsPaymentKey) bsx @@ -138,12 +139,12 @@ transPubKeyHash = PV1.PubKeyHash . PlutusTx.toBuiltin . C.serialiseToRawBytes transStakeKeyHash :: C.Hash C.StakeKey -> PV1.PubKeyHash transStakeKeyHash = PV1.PubKeyHash . PlutusTx.toBuiltin . C.serialiseToRawBytes -unTransStakeKeyHash :: PV1.PubKeyHash -> Maybe (C.Hash C.StakeKey) +unTransStakeKeyHash :: PV1.PubKeyHash -> Either C.SerialiseAsRawBytesError (C.Hash C.StakeKey) unTransStakeKeyHash (PV1.PubKeyHash pkh) = let bsx = PlutusTx.fromBuiltin pkh in C.deserialiseFromRawBytes (C.AsHash C.AsStakeKey) bsx -unTransCredential :: PV1.Credential -> Maybe C.PaymentCredential +unTransCredential :: PV1.Credential -> Either C.SerialiseAsRawBytesError C.PaymentCredential unTransCredential = \case PV1.PubKeyCredential c -> C.PaymentCredentialByKey <$> unTransPubKeyHash c PV1.ScriptCredential c -> C.PaymentCredentialByScript <$> unTransScriptHash c @@ -163,18 +164,18 @@ transStakeCredential :: C.StakeCredential -> PV1.Credential transStakeCredential (C.StakeCredentialByKey stakeKeyHash) = PV1.PubKeyCredential (transStakeKeyHash stakeKeyHash) transStakeCredential (C.StakeCredentialByScript scriptHash) = PV1.ScriptCredential (transScriptHash scriptHash) -unTransStakeCredential :: PV1.Credential -> Maybe C.StakeCredential +unTransStakeCredential :: PV1.Credential -> Either C.SerialiseAsRawBytesError C.StakeCredential unTransStakeCredential (PV1.PubKeyCredential pubKeyHash) = C.StakeCredentialByKey <$> unTransStakeKeyHash pubKeyHash -unTransStakeCredential (PV1.ScriptCredential validatorHash) = C.StakeCredentialByScript <$> unTransScriptHash validatorHash +unTransStakeCredential (PV1.ScriptCredential scriptHash) = C.StakeCredentialByScript <$> unTransScriptHash scriptHash -unTransStakeAddressReference :: Maybe PV1.StakingCredential -> Maybe C.StakeAddressReference -unTransStakeAddressReference Nothing = Just C.NoStakeAddress +unTransStakeAddressReference :: Maybe PV1.StakingCredential -> Either C.SerialiseAsRawBytesError C.StakeAddressReference +unTransStakeAddressReference Nothing = Right C.NoStakeAddress unTransStakeAddressReference (Just (PV1.StakingHash credential)) = C.StakeAddressByValue <$> unTransStakeCredential credential unTransStakeAddressReference (Just (PV1.StakingPtr slotNo txIx ptrIx)) = - Just (C.StakeAddressByPointer (C.StakeAddressPointer (Ptr (C.SlotNo $ fromIntegral slotNo) (TxIx $ fromIntegral txIx) (CertIx $ fromIntegral ptrIx)))) + Right (C.StakeAddressByPointer (C.StakeAddressPointer (Ptr (C.SlotNo $ fromIntegral slotNo) (TxIx $ fromIntegral txIx) (CertIx $ fromIntegral ptrIx)))) -unTransAddressInEra :: C.NetworkId -> PV1.Address -> Maybe (C.AddressInEra C.BabbageEra) +unTransAddressInEra :: C.NetworkId -> PV1.Address -> Either C.SerialiseAsRawBytesError (C.AddressInEra C.BabbageEra) unTransAddressInEra networkId (PV1.Address cred staking) = C.AddressInEra (C.ShelleyAddressInEra C.ShelleyBasedEraBabbage) <$> (C.makeShelleyAddress networkId @@ -192,7 +193,7 @@ transAddressInEra = \case (transStakeAddressReference $ C.fromShelleyStakeReference s) C.AddressInEra C.ByronAddressInAnyEra _ -> Nothing -unTransTxOutRef :: PV1.TxOutRef -> Maybe C.TxIn +unTransTxOutRef :: PV1.TxOutRef -> Either C.SerialiseAsRawBytesError C.TxIn unTransTxOutRef PV1.TxOutRef{PV1.txOutRefId=PV1.TxId bs, PV1.txOutRefIdx} = let i = C.deserialiseFromRawBytes C.AsTxId $ PlutusTx.fromBuiltin bs in C.TxIn <$> i <*> pure (C.TxIx $ fromIntegral txOutRefIdx) @@ -208,10 +209,10 @@ transPOSIXTime posixTimeSeconds = PV1.POSIXTime (floor @Rational (1000 * realToF unTransPOSIXTime :: PV1.POSIXTime -> POSIXTime unTransPOSIXTime (PV1.POSIXTime pt) = realToFrac @Rational $ fromIntegral pt / 1000 -unTransTxOutValue :: PV1.Value -> Maybe (C.TxOutValue C.BabbageEra) +unTransTxOutValue :: PV1.Value -> Either C.SerialiseAsRawBytesError (C.TxOutValue C.BabbageEra) unTransTxOutValue value = C.TxOutValue C.MultiAssetInBabbageEra <$> unTransValue value -unTransValue :: PV1.Value -> Maybe C.Value +unTransValue :: PV1.Value -> Either C.SerialiseAsRawBytesError C.Value unTransValue = fmap C.valueFromList . traverse toSingleton . Value.flattenValue where @@ -221,16 +222,16 @@ unTransValue = unTransPlutusScript :: C.SerialiseAsRawBytes plutusScript => C.AsType plutusScript - -> P.Script - -> Maybe plutusScript + -> SerialisedScript + -> Either C.SerialiseAsRawBytesError plutusScript unTransPlutusScript asPlutusScriptType = C.deserialiseFromRawBytes asPlutusScriptType . BSL.toStrict . Codec.serialise -unTransScriptDataHash :: P.DatumHash -> Maybe (C.Hash C.ScriptData) +unTransScriptDataHash :: P.DatumHash -> Either C.SerialiseAsRawBytesError (C.Hash C.ScriptData) unTransScriptDataHash (P.DatumHash bs) = C.deserialiseFromRawBytes (C.AsHash C.AsScriptData) (PlutusTx.fromBuiltin bs) -unTransTxOutDatumHash :: P.DatumHash -> Maybe (C.TxOutDatum ctx C.BabbageEra) +unTransTxOutDatumHash :: P.DatumHash -> Either C.SerialiseAsRawBytesError (C.TxOutDatum ctx C.BabbageEra) unTransTxOutDatumHash datumHash = C.TxOutDatumHash C.ScriptDataInBabbageEra <$> unTransScriptDataHash datumHash _Interval :: Iso' (Interval a) (LowerBound a, UpperBound a) diff --git a/src/base/lib/Convex/Scripts.hs b/src/base/lib/Convex/Scripts.hs index b28d191c..1d585766 100644 --- a/src/base/lib/Convex/Scripts.hs +++ b/src/base/lib/Convex/Scripts.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE ViewPatterns #-} +{-# LANGUAGE TypeApplications #-} +{-# LANGUAGE ViewPatterns #-} {-| Functions for dealing with scripts and datums -} module Convex.Scripts( @@ -7,27 +8,33 @@ module Convex.Scripts( -- * FromData / ToData fromScriptData, toScriptData, + toHashableScriptData, -- * Translating between ledger and plutus representations ) where -import Cardano.Api (PlutusScript) -import qualified Cardano.Api.Shelley as C -import Codec.Serialise (serialise) -import Data.ByteString.Lazy (toStrict) -import Data.ByteString.Short (toShort) -import qualified Plutus.V1.Ledger.Api as PV1 -import Plutus.V1.Ledger.Scripts (fromCompiledCode) -import PlutusTx.Code (CompiledCode) +import Cardano.Api (PlutusScript) +import qualified Cardano.Api.Shelley as C +import Cardano.Ledger.Alonzo.Scripts.Data (Data (..)) +import Codec.Serialise (serialise) +import Data.ByteString.Lazy (toStrict) +import Data.ByteString.Short (toShort) +import Ouroboros.Consensus.Shelley.Eras (StandardBabbage) +import PlutusLedgerApi.Common (serialiseCompiledCode) +import qualified PlutusLedgerApi.V1 as PV1 +import PlutusTx.Code (CompiledCode) {-| Get the 'PlutusScript' of a 'CompiledCode' -} compiledCodeToScript :: CompiledCode a -> PlutusScript lang -compiledCodeToScript = C.PlutusScriptSerialised . toShort . toStrict . serialise . fromCompiledCode +compiledCodeToScript = C.PlutusScriptSerialised . toShort . toStrict . serialise . serialiseCompiledCode fromScriptData :: PV1.FromData a => C.ScriptData -> Maybe a fromScriptData (C.toPlutusData -> d) = PV1.fromData d toScriptData :: PV1.ToData a => a -> C.ScriptData toScriptData = C.fromPlutusData . PV1.toData + +toHashableScriptData :: PV1.ToData a => a -> C.HashableScriptData +toHashableScriptData = C.fromAlonzoData @StandardBabbage . Data . PV1.toData diff --git a/src/base/lib/Convex/Utils.hs b/src/base/lib/Convex/Utils.hs index c6400ac9..83cd6d89 100644 --- a/src/base/lib/Convex/Utils.hs +++ b/src/base/lib/Convex/Utils.hs @@ -62,7 +62,7 @@ import Data.Time.Clock.POSIX (posixSecondsToUTCTime utcTimeToPOSIXSeconds) import qualified Ouroboros.Consensus.HardFork.History as Consensus import qualified Ouroboros.Consensus.HardFork.History.Qry as Qry -import qualified Plutus.V1.Ledger.Time as PV1 +import qualified PlutusLedgerApi.V1 as PV1 scriptFromCborV1 :: String -> Either String (PlutusScript PlutusScriptV1) scriptFromCborV1 cbor = do @@ -116,7 +116,7 @@ extractTx txIds = extractTx' tx@(C.Tx txBody _) = do let txi = C.getTxId txBody when (txi `Set.member` txIds) $ - void $ liftIO $ C.writeFileTextEnvelope (show txi <> ".json") Nothing tx + void $ liftIO $ C.writeFileTextEnvelope (C.File $ show txi <> ".json") Nothing tx in \case BlockInMode (Block _ txns) C.BabbageEraInCardanoMode -> traverse_ extractTx' txns diff --git a/src/base/lib/Convex/Utxos.hs b/src/base/lib/Convex/Utxos.hs index e76e28c0..1f12ae43 100644 --- a/src/base/lib/Convex/Utxos.hs +++ b/src/base/lib/Convex/Utxos.hs @@ -55,43 +55,43 @@ module Convex.Utxos( changeForAddress ) where -import Cardano.Api (AddressInEra, BabbageEra, - Block (..), BlockInMode (..), - CardanoMode, EraInMode (..), - PaymentCredential, ScriptData, - StakeCredential, Tx (..), - TxId, TxIn (..), TxIx (..), - UTxO (..), Value) -import qualified Cardano.Api as C -import Cardano.Api.Shelley (ExecutionUnits, TxBody (..)) -import qualified Cardano.Api.Shelley as CS -import qualified Cardano.Ledger.Alonzo.Scripts as Scripts -import Cardano.Ledger.Alonzo.TxWitness (unRedeemers) -import qualified Cardano.Ledger.Alonzo.TxWitness as TxWitness -import qualified Cardano.Ledger.Babbage.TxBody as Babbage.TxBody -import qualified Cardano.Ledger.BaseTypes as CT -import qualified Cardano.Ledger.Credential as Shelley -import Cardano.Ledger.Crypto (StandardCrypto) -import qualified Cardano.Ledger.TxIn as CT -import Control.Lens (_1, _2, _3, makeLenses, - makePrisms, over, preview, - view) -import qualified Convex.Lenses as L -import Data.Aeson (FromJSON, ToJSON) -import Data.Bifunctor (Bifunctor (..)) -import Data.DList (DList) -import qualified Data.DList as DList -import Data.Map.Strict (Map) -import qualified Data.Map.Strict as Map -import Data.Maybe (isJust, isNothing, - listToMaybe, mapMaybe) -import qualified Data.Set as Set -import Data.Text (Text) -import qualified Data.Text as Text -import GHC.Word (Word64) -import Prelude hiding (null) -import Prettyprinter (Doc, Pretty (..), hang, - parens, viaShow, vsep, (<+>)) +import Cardano.Api (AddressInEra, BabbageEra, + Block (..), BlockInMode (..), + CardanoMode, EraInMode (..), + HashableScriptData, + PaymentCredential, + StakeCredential, Tx (..), TxId, + TxIn (..), TxIx (..), UTxO (..), + Value) +import qualified Cardano.Api as C +import Cardano.Api.Shelley (ExecutionUnits, TxBody (..)) +import qualified Cardano.Api.Shelley as CS +import qualified Cardano.Ledger.Alonzo.Scripts as Scripts +import Cardano.Ledger.Alonzo.TxWits (unRedeemers) +import qualified Cardano.Ledger.Alonzo.TxWits as TxWitness +import qualified Cardano.Ledger.Babbage.TxBody as Babbage.TxBody +import qualified Cardano.Ledger.BaseTypes as CT +import qualified Cardano.Ledger.Credential as Shelley +import Cardano.Ledger.Crypto (StandardCrypto) +import qualified Cardano.Ledger.TxIn as CT +import Control.Lens (_1, _2, _3, makeLenses, + makePrisms, over, preview, view) +import qualified Convex.Lenses as L +import Data.Aeson (FromJSON, ToJSON) +import Data.Bifunctor (Bifunctor (..)) +import Data.DList (DList) +import qualified Data.DList as DList +import Data.Map.Strict (Map) +import qualified Data.Map.Strict as Map +import Data.Maybe (isJust, isNothing, listToMaybe, + mapMaybe) +import qualified Data.Set as Set +import Data.Text (Text) +import qualified Data.Text as Text +import GHC.Word (Word64) +import Prelude hiding (null) +import Prettyprinter (Doc, Pretty (..), hang, parens, + viaShow, vsep, (<+>)) import qualified Prettyprinter type AddressCredential = Shelley.PaymentCredential StandardCrypto @@ -244,7 +244,7 @@ data RemoveUtxoEvent a = -- ^ Id of the transaction that spent the output , rueTx :: C.Tx BabbageEra -- ^ The transaction that spent the output - , rueRedeemer :: Maybe (ScriptData, ExecutionUnits) -- fromAlonzoData + , rueRedeemer :: Maybe (HashableScriptData, ExecutionUnits) -- fromAlonzoData } {-| The 'UtxoChange' represented by the event. @@ -385,7 +385,7 @@ extractBabbage ex state cred (Block _blockHeader txns) = foldMap (extractBabbage extractBabbageTxn :: forall a. (C.TxIn -> C.TxOut C.CtxTx C.BabbageEra -> Maybe a) -> UtxoSet C.CtxTx a -> Maybe AddressCredential -> C.Tx BabbageEra -> DList (UtxoChangeEvent a) extractBabbageTxn ex UtxoSet{_utxos} cred theTx@(Tx txBody _) = let ShelleyTxBody _ txBody' _scripts scriptData _auxiliaryData _ = txBody - Babbage.TxBody.TxBody{Babbage.TxBody.inputs} = txBody' + Babbage.TxBody.BabbageTxBody{Babbage.TxBody.btbInputs} = txBody' txid = C.getTxId txBody allOuts = C.fromLedgerTxOuts C.ShelleyBasedEraBabbage txBody' scriptData @@ -394,7 +394,7 @@ extractBabbageTxn ex UtxoSet{_utxos} cred theTx@(Tx txBody _) = C.TxBodyScriptData C.ScriptDataInBabbageEra _ r -> unRedeemers r _ -> mempty - checkInput :: (Word64, TxIn) -> Maybe (TxIn, ((C.TxOut C.CtxTx C.BabbageEra, a), Maybe (ScriptData, ExecutionUnits))) + checkInput :: (Word64, TxIn) -> Maybe (TxIn, ((C.TxOut C.CtxTx C.BabbageEra, a), Maybe (HashableScriptData, ExecutionUnits))) checkInput (idx, txIn) = fmap (txIn,) $ do o <- Map.lookup txIn _utxos let redeemer = fmap (bimap CS.fromAlonzoData CS.fromAlonzoExUnits) (Map.lookup (TxWitness.RdmrPtr Scripts.Spend idx) txReds) @@ -423,7 +423,7 @@ extractBabbageTxn ex UtxoSet{_utxos} cred theTx@(Tx txBody _) = $ mapMaybe checkInput $ zip [0..] -- for redeemer pointers $ fmap (uncurry TxIn . bimap CS.fromShelleyTxId txIx . (\(CT.TxIn i n) -> (i, n))) - $ Set.toList inputs + $ Set.toList btbInputs in _outputsAdded <> _outputsRemoved diff --git a/src/coin-selection/convex-coin-selection.cabal b/src/coin-selection/convex-coin-selection.cabal index 8ac67c3f..d2608803 100644 --- a/src/coin-selection/convex-coin-selection.cabal +++ b/src/coin-selection/convex-coin-selection.cabal @@ -30,7 +30,6 @@ library exposed-modules: Convex.BuildTx Convex.CoinSelection - Convex.CoinSelection.CardanoApi Convex.MockChain.CoinSelection hs-source-dirs: lib build-depends: @@ -40,20 +39,13 @@ library convex-base, convex-mockchain, convex-wallet, - array, - text, - mtl -- cardano dependencies build-depends: cardano-api, cardano-ledger-core -any, - cardano-ledger-shelley, - cardano-ledger-alonzo, - cardano-ledger-babbage, plutus-ledger-api, - cardano-slotting, - ouroboros-consensus + cardano-slotting test-suite convex-coin-selection-test import: lang @@ -69,11 +61,14 @@ test-suite convex-coin-selection-test tasty, tasty-hunit, lens, + cardano-ledger-alonzo, convex-coin-selection, convex-mockchain, convex-base, convex-wallet, cardano-api, containers, - plutus-tx, - plutus-tx-plugin \ No newline at end of file + plutus-ledger-api:{plutus-ledger-api, plutus-ledger-api-testlib}, + plutus-ledger-api, + cardano-ledger-core, + mtl \ No newline at end of file diff --git a/src/coin-selection/lib/Convex/BuildTx.hs b/src/coin-selection/lib/Convex/BuildTx.hs index a9026012..fa193ff5 100644 --- a/src/coin-selection/lib/Convex/BuildTx.hs +++ b/src/coin-selection/lib/Convex/BuildTx.hs @@ -30,20 +30,16 @@ module Convex.BuildTx( setMinAdaDepositAll ) where -import Cardano.Api.Shelley (Hash, NetworkId, PaymentKey, - PlutusScript, PlutusScriptV1, - PlutusScriptV2, ScriptData, - ScriptHash) -import qualified Cardano.Api.Shelley as C -import qualified Cardano.Ledger.Core as CLedger -import Control.Lens (_1, _2, at, mapped, over, set, - (&)) -import qualified Convex.CoinSelection.CardanoApi as CC -import qualified Convex.Lenses as L -import Convex.Scripts (toScriptData) -import qualified Data.Map as Map -import Data.Maybe (fromMaybe) -import qualified Plutus.V1.Ledger.Api as Plutus +import Cardano.Api.Shelley (Hash, HashableScriptData, NetworkId, + PaymentKey, PlutusScript, PlutusScriptV1, + PlutusScriptV2, ScriptHash) +import qualified Cardano.Api.Shelley as C +import Control.Lens (_1, _2, at, mapped, over, set, (&)) +import qualified Convex.Lenses as L +import Convex.Scripts (toHashableScriptData) +import qualified Data.Map as Map +import Data.Maybe (fromMaybe) +import qualified PlutusLedgerApi.V1 as Plutus type TxBuild = C.TxBodyContent C.BuildTx C.BabbageEra -> C.TxBodyContent C.BuildTx C.BabbageEra @@ -55,25 +51,25 @@ spendPublicKeyOutput txIn = in over L.txIns ((txIn, wit) :) spendPlutusV1 :: forall datum redeemer. (Plutus.ToData datum, Plutus.ToData redeemer) => C.TxIn -> PlutusScript PlutusScriptV1 -> datum -> redeemer -> TxBuild -spendPlutusV1 txIn s (toScriptData -> dat) (toScriptData -> red) = +spendPlutusV1 txIn s (toHashableScriptData -> dat) (toHashableScriptData -> red) = let wit = C.PlutusScriptWitness C.PlutusScriptV1InBabbage C.PlutusScriptV1 (C.PScript s) (C.ScriptDatumForTxIn dat) red (C.ExecutionUnits 0 0) wit' = C.BuildTxWith (C.ScriptWitness C.ScriptWitnessForSpending wit) in over L.txIns ((txIn, wit') :) . setScriptsValid spendPlutusV2 :: forall datum redeemer. (Plutus.ToData datum, Plutus.ToData redeemer) => C.TxIn -> PlutusScript PlutusScriptV2 -> datum -> redeemer -> TxBuild -spendPlutusV2 txIn s (toScriptData -> dat) (toScriptData -> red) = +spendPlutusV2 txIn s (toHashableScriptData -> dat) (toHashableScriptData -> red) = let wit = C.PlutusScriptWitness C.PlutusScriptV2InBabbage C.PlutusScriptV2 (C.PScript s) (C.ScriptDatumForTxIn dat) red (C.ExecutionUnits 0 0) wit' = C.BuildTxWith (C.ScriptWitness C.ScriptWitnessForSpending wit) in over L.txIns ((txIn, wit') :) . setScriptsValid spendPlutusV2Ref :: forall datum redeemer. (Plutus.ToData datum, Plutus.ToData redeemer) => C.TxIn -> C.TxIn -> Maybe C.ScriptHash -> datum -> redeemer -> TxBuild -spendPlutusV2Ref txIn refTxIn sh (toScriptData -> dat) (toScriptData -> red) = +spendPlutusV2Ref txIn refTxIn sh (toHashableScriptData -> dat) (toHashableScriptData -> red) = let wit = C.PlutusScriptWitness C.PlutusScriptV2InBabbage C.PlutusScriptV2 (C.PReferenceScript refTxIn sh) (C.ScriptDatumForTxIn dat) red (C.ExecutionUnits 0 0) wit' = C.BuildTxWith (C.ScriptWitness C.ScriptWitnessForSpending wit) in over L.txIns ((txIn, wit') :) . setScriptsValid . addReference refTxIn mintPlutusV1 :: forall redeemer. (Plutus.ToData redeemer) => PlutusScript PlutusScriptV1 -> redeemer -> C.AssetName -> C.Quantity -> TxBuild -mintPlutusV1 script (toScriptData -> red) assetName quantity = +mintPlutusV1 script (toHashableScriptData -> red) assetName quantity = let sh = C.hashScript (C.PlutusScript C.PlutusScriptV1 script) v = assetValue sh assetName quantity policyId = C.PolicyId sh @@ -88,7 +84,7 @@ assetValue hsh assetName quantity = C.valueFromList [(C.AssetId (C.PolicyId hsh) assetName, quantity)] mintPlutusV2 :: forall redeemer. (Plutus.ToData redeemer) => PlutusScript PlutusScriptV2 -> redeemer -> C.AssetName -> C.Quantity -> TxBuild -mintPlutusV2 script (toScriptData -> red) assetName quantity = +mintPlutusV2 script (toHashableScriptData -> red) assetName quantity = let sh = C.hashScript (C.PlutusScript C.PlutusScriptV2 script) v = assetValue sh assetName quantity policyId = C.PolicyId sh @@ -118,7 +114,7 @@ payToPublicKey network pk vl = txo = C.TxOut addr val C.TxOutDatumNone C.ReferenceScriptNone in over L.txOuts ((:) txo) -payToScriptHash :: NetworkId -> ScriptHash -> ScriptData -> C.Value -> TxBuild +payToScriptHash :: NetworkId -> ScriptHash -> HashableScriptData -> C.Value -> TxBuild payToScriptHash network script datum vl = let val = C.TxOutValue C.MultiAssetInBabbageEra vl addr = C.makeShelleyAddressInEra network (C.PaymentCredentialByScript script) C.NoStakeAddress @@ -129,13 +125,13 @@ payToScriptHash network script datum vl = payToPlutusV1 :: forall a. Plutus.ToData a => NetworkId -> PlutusScript PlutusScriptV1 -> a -> C.Value -> TxBuild payToPlutusV1 network s datum vl = let sh = C.hashScript (C.PlutusScript C.PlutusScriptV1 s) - dt = C.fromPlutusData (Plutus.toData datum) + dt = toHashableScriptData datum in payToScriptHash network sh dt vl payToPlutusV2 :: forall a. Plutus.ToData a => NetworkId -> PlutusScript PlutusScriptV2 -> a -> C.Value -> TxBuild payToPlutusV2 network s datum vl = let sh = C.hashScript (C.PlutusScript C.PlutusScriptV2 s) - dt = C.fromPlutusData (Plutus.toData datum) + dt = toHashableScriptData datum in payToScriptHash network sh dt vl payToPlutusV2Inline :: C.AddressInEra C.BabbageEra -> PlutusScript PlutusScriptV2 -> C.Value -> TxBuild @@ -151,23 +147,22 @@ setScriptsValid = set L.txScriptValidity (C.TxScriptValidity C.TxScriptValidityS {-| Set the Ada component in an output's value to at least the amount needed to cover the minimum UTxO deposit for this output -} -setMinAdaDeposit :: CLedger.PParams (C.ShelleyLedgerEra C.BabbageEra) -> C.TxOut C.CtxTx C.BabbageEra -> C.TxOut C.CtxTx C.BabbageEra +setMinAdaDeposit :: C.BundledProtocolParameters C.BabbageEra -> C.TxOut C.CtxTx C.BabbageEra -> C.TxOut C.CtxTx C.BabbageEra setMinAdaDeposit params txOut = let minUtxo = minAdaDeposit params txOut in txOut & over (L._TxOut . _2 . L._TxOutValue . L._Value . at C.AdaAssetId) (maybe (Just minUtxo) (Just . max minUtxo)) -minAdaDeposit :: CLedger.PParams (C.ShelleyLedgerEra C.BabbageEra) -> C.TxOut C.CtxTx C.BabbageEra -> C.Quantity +minAdaDeposit :: C.BundledProtocolParameters C.BabbageEra -> C.TxOut C.CtxTx C.BabbageEra -> C.Quantity minAdaDeposit params txOut = let txo = txOut -- set the Ada value to a dummy amount to ensure that it is not 0 (if it was 0, the size of the output -- would be smaller, causing 'calculateMinimumUTxO' to compute an amount that is a little too small) & over (L._TxOut . _2 . L._TxOutValue . L._Value . at C.AdaAssetId) (maybe (Just $ C.Quantity 3_000_000) Just) in fromMaybe (C.Quantity 0) $ do - k <- either (const Nothing) pure (CC.calculateMinimumUTxO txo params) - C.Lovelace l <- C.valueToLovelace k + let C.Lovelace l = C.calculateMinimumUTxO C.ShelleyBasedEraBabbage txo params pure (C.Quantity l) {-| Apply 'setMinAdaDeposit' to all outputs -} -setMinAdaDepositAll :: CLedger.PParams (C.ShelleyLedgerEra C.BabbageEra) -> TxBuild +setMinAdaDepositAll :: C.BundledProtocolParameters C.BabbageEra -> TxBuild setMinAdaDepositAll params = over (L.txOuts . mapped) (setMinAdaDeposit params) diff --git a/src/coin-selection/lib/Convex/CoinSelection.hs b/src/coin-selection/lib/Convex/CoinSelection.hs index a46c5e22..5a83f191 100644 --- a/src/coin-selection/lib/Convex/CoinSelection.hs +++ b/src/coin-selection/lib/Convex/CoinSelection.hs @@ -30,41 +30,32 @@ module Convex.CoinSelection( prepCSInputs ) where -import Cardano.Api.Shelley (AddressInEra, BabbageEra, - BuildTx, CardanoMode, - EraHistory, PoolId, - TxBodyContent, TxOut, - UTxO (..)) -import qualified Cardano.Api.Shelley as C -import qualified Cardano.Ledger.Core as Core -import Cardano.Ledger.Crypto (StandardCrypto) -import qualified Cardano.Ledger.Keys as Keys -import Cardano.Slotting.Time (SystemStart) -import Control.Lens (_1, _2, makeLensesFor, over, - preview, set, to, traversed, - view, (&), (.~), (^.), (^..), - (|>)) -import Convex.BuildTx (addCollateral, - setMinAdaDeposit, - spendPublicKeyOutput) -import Convex.Class (MonadBlockchain (..)) -import qualified Convex.CoinSelection.CardanoApi as CC -import qualified Convex.Era as Ledger.Era -import qualified Convex.Lenses as L -import Convex.Utxos (BalanceChanges (..), - UtxoSet (..)) -import qualified Convex.Utxos as Utxos -import Convex.Wallet (Wallet) -import qualified Convex.Wallet as Wallet -import Data.Bifunctor (Bifunctor (..)) -import Data.Function (on) -import qualified Data.List as List -import Data.Map (Map) -import qualified Data.Map as Map -import Data.Maybe (isNothing, mapMaybe, - maybeToList) -import Data.Set (Set) -import qualified Data.Set as Set +import Cardano.Api.Shelley (AddressInEra, BabbageEra, BuildTx, + CardanoMode, EraHistory, PoolId, + TxBodyContent, TxOut, UTxO (..)) +import qualified Cardano.Api.Shelley as C +import Cardano.Ledger.Crypto (StandardCrypto) +import qualified Cardano.Ledger.Keys as Keys +import Cardano.Slotting.Time (SystemStart) +import Control.Lens (_1, _2, makeLensesFor, over, preview, + set, to, traversed, view, (&), (.~), + (^.), (^..), (|>)) +import Convex.BuildTx (addCollateral, setMinAdaDeposit, + spendPublicKeyOutput) +import Convex.Class (MonadBlockchain (..)) +import qualified Convex.Lenses as L +import Convex.Utxos (BalanceChanges (..), UtxoSet (..)) +import qualified Convex.Utxos as Utxos +import Convex.Wallet (Wallet) +import qualified Convex.Wallet as Wallet +import Data.Bifunctor (Bifunctor (..)) +import Data.Function (on) +import qualified Data.List as List +import Data.Map (Map) +import qualified Data.Map as Map +import Data.Maybe (isNothing, mapMaybe, maybeToList) +import Data.Set (Set) +import qualified Data.Set as Set type ERA = BabbageEra @@ -101,17 +92,17 @@ data BalancingError = {-| Perform transaction balancing -} -balanceTransactionBody :: SystemStart -> EraHistory CardanoMode -> Core.PParams Ledger.Era.ERA -> Set PoolId -> CSInputs -> Either BalancingError (C.BalancedTxBody ERA, BalanceChanges) +balanceTransactionBody :: SystemStart -> EraHistory CardanoMode -> C.BundledProtocolParameters C.BabbageEra -> Set PoolId -> CSInputs -> Either BalancingError (C.BalancedTxBody ERA, BalanceChanges) balanceTransactionBody systemStart eraHistory protocolParams stakePools CSInputs{csiUtxo, csiTxBody, csiChangeAddress, csiNumWitnesses} = do let changeOutputSmall = C.TxOut csiChangeAddress (C.lovelaceToTxOutValue 1) C.TxOutDatumNone C.ReferenceScriptNone changeOutputLarge = C.TxOut csiChangeAddress (C.lovelaceToTxOutValue $ C.Lovelace (2^(64 :: Integer)) - 1) C.TxOutDatumNone C.ReferenceScriptNone -- append output instead of prepending txbody0 <- - first (BalancingError . C.TxBodyError) $ C.makeTransactionBody $ csiTxBody & over L.txOuts (|> changeOutputSmall) + first (BalancingError . C.TxBodyError) $ C.createAndValidateTransactionBody $ csiTxBody & over L.txOuts (|> changeOutputSmall) exUnitsMap <- first (BalancingError . C.TxBodyErrorValidityInterval) $ - CC.evaluateTransactionExecutionUnits - systemStart eraHistory + C.evaluateTransactionExecutionUnits + systemStart (C.toLedgerEpochInfo eraHistory) protocolParams csiUtxo txbody0 @@ -125,18 +116,23 @@ balanceTransactionBody systemStart eraHistory protocolParams stakePools CSInputs -- append output instead of prepending txbody1 <- first (BalancingError . C.TxBodyError) - $ C.makeTransactionBody + $ C.createAndValidateTransactionBody $ txbodycontent1 & set L.txFee (C.Lovelace (2^(32 :: Integer) - 1)) & over L.txOuts (|> changeOutputLarge) - let !t_fee = CC.evaluateTransactionFee protocolParams txbody1 csiNumWitnesses + let !t_fee = C.evaluateTransactionFee protocolParams txbody1 csiNumWitnesses 0 txbody2 <- first (BalancingError . C.TxBodyError) - $ C.makeTransactionBody + $ C.createAndValidateTransactionBody $ txbodycontent1 & set L.txFee t_fee - let !balance = CC.evaluateTransactionBalance protocolParams stakePools csiUtxo txbody2 + -- TODO: If there are any stake pool unregistration certificates in the transaction + -- then we need to provide a @Map StakeCredential Lovelace@ here. + -- See https://github.com/input-output-hk/cardano-api/commit/d23f964d311282b1950b2fd840bcc57ae40a0998 + let unregPoolStakeBalance = mempty + + let !balance = C.evaluateTransactionBalance protocolParams stakePools unregPoolStakeBalance csiUtxo txbody2 mapM_ (`checkMinUTxOValue` protocolParams) $ C.txOuts txbodycontent1 @@ -153,23 +149,22 @@ balanceTransactionBody systemStart eraHistory protocolParams stakePools CSInputs & set L.txFee t_fee & over L.txOuts (accountForNoChange (C.TxOut csiChangeAddress balance C.TxOutDatumNone C.ReferenceScriptNone)) - txbody3 <- first (BalancingError . C.TxBodyError) $ C.makeTransactionBody finalBodyContent + txbody3 <- first (BalancingError . C.TxBodyError) $ C.createAndValidateTransactionBody finalBodyContent balances <- maybe (Left ComputeBalanceChangeError) Right (balanceChanges csiUtxo finalBodyContent) - let mkBalancedBody b = C.BalancedTxBody b (C.TxOut csiChangeAddress balance C.TxOutDatumNone C.ReferenceScriptNone) t_fee + let mkBalancedBody b = C.BalancedTxBody finalBodyContent b (C.TxOut csiChangeAddress balance C.TxOutDatumNone C.ReferenceScriptNone) t_fee return (mkBalancedBody txbody3, balances) checkMinUTxOValue :: C.TxOut C.CtxTx C.BabbageEra - -> Core.PParams Ledger.Era.ERA + -> C.BundledProtocolParameters C.BabbageEra -> Either BalancingError () checkMinUTxOValue txout@(C.TxOut _ v _ _) pparams' = do - minUTxO <- first (BalancingError . C.TxBodyErrorMinUTxOMissingPParams) - $ CC.calculateMinimumUTxO txout pparams' - if C.txOutValueToLovelace v >= C.selectLovelace minUTxO + let minUTxO = C.calculateMinimumUTxO C.ShelleyBasedEraBabbage txout pparams' + if C.txOutValueToLovelace v >= minUTxO then Right () - else Left (CheckMinUtxoValueError txout (C.selectLovelace minUTxO)) + else Left (CheckMinUtxoValueError txout minUTxO) accountForNoChange :: C.TxOut C.CtxTx C.BabbageEra -> [C.TxOut C.CtxTx C.BabbageEra] -> [C.TxOut C.CtxTx C.BabbageEra] accountForNoChange change@(C.TxOut _ balance _ _) rest = @@ -181,7 +176,7 @@ accountForNoChange change@(C.TxOut _ balance _ _) rest = -- instead of creating a new txout, i.e., rest ++ [change] updateRestWithChange change rest -balanceCheck :: Core.PParams Ledger.Era.ERA -> AddressInEra BabbageEra -> C.TxOutValue C.BabbageEra -> Either BalancingError () +balanceCheck :: C.BundledProtocolParameters C.BabbageEra -> AddressInEra BabbageEra -> C.TxOutValue C.BabbageEra -> Either BalancingError () balanceCheck pparams changeaddr balance | C.txOutValueToLovelace balance == 0 = return () | C.txOutValueToLovelace balance < 0 = @@ -323,20 +318,20 @@ balanceTx :: -- | The balanced transaction body and the balance changes (per address) m (C.BalancedTxBody ERA, BalanceChanges) balanceTx returnAddress walletUtxo txb = do - (params, ledgerPPs) <- queryProtocolParameters + params <- queryProtocolParameters pools <- queryStakePools - let txb0 = txb & L.txProtocolParams .~ C.BuildTxWith (Just params) + let txb0 = txb & L.txProtocolParams .~ C.BuildTxWith (Just $ C.unbundleProtocolParams params) -- TODO: Better error handling (better than 'fail') otherInputs <- lookupTxIns (requiredTxIns txb) let combinedTxIns = let UtxoSet w = walletUtxo UTxO o = otherInputs in UTxO (Map.union (fmap fst w) o) - finalBody <- either (fail . show) pure (addMissingInputs pools ledgerPPs combinedTxIns returnAddress walletUtxo (flip setCollateral walletUtxo $ flip addOwnInput walletUtxo txb0)) + finalBody <- either (fail . show) pure (addMissingInputs pools params combinedTxIns returnAddress walletUtxo (flip setCollateral walletUtxo $ flip addOwnInput walletUtxo txb0)) csi <- prepCSInputs returnAddress combinedTxIns finalBody start <- querySystemStart hist <- queryEraHistory - either (fail . show) pure (balanceTransactionBody start hist ledgerPPs pools csi) + either (fail . show) pure (balanceTransactionBody start hist params pools csi) {-| Balance the transaction using the wallet's funds, then sign it. -} @@ -349,7 +344,7 @@ balanceForWallet wallet walletUtxo txb = do {-| Sign a transaction with the wallet's key -} signForWallet :: Wallet -> C.BalancedTxBody ERA -> C.Tx ERA -signForWallet wallet (C.BalancedTxBody txbody _changeOutput _fee) = +signForWallet wallet (C.BalancedTxBody _ txbody _changeOutput _fee) = let wit = [C.makeShelleyKeyWitness txbody $ C.WitnessPaymentKey (Wallet.getWallet wallet)] in C.makeSignedTransaction wit txbody @@ -379,10 +374,10 @@ runsScripts body = {-| Add inputs to ensure that the balance is strictly positive -} -addMissingInputs :: Set PoolId -> Core.PParams Ledger.Era.ERA -> C.UTxO ERA -> C.AddressInEra C.BabbageEra -> UtxoSet ctx a -> TxBodyContent BuildTx ERA -> Either CoinSelectionError (TxBodyContent BuildTx ERA) +addMissingInputs :: Set PoolId -> C.BundledProtocolParameters BabbageEra -> C.UTxO ERA -> C.AddressInEra C.BabbageEra -> UtxoSet ctx a -> TxBodyContent BuildTx ERA -> Either CoinSelectionError (TxBodyContent BuildTx ERA) addMissingInputs poolIds ledgerPPs utxo_ returnAddress walletUtxo txBodyContent = do - txb <- first BodyError (C.makeTransactionBody txBodyContent) - let bal = CC.evaluateTransactionBalance ledgerPPs poolIds utxo_ txb & view L._TxOutValue + txb <- first BodyError (C.createAndValidateTransactionBody txBodyContent) + let bal = C.evaluateTransactionBalance ledgerPPs poolIds mempty utxo_ txb & view L._TxOutValue available = Utxos.removeUtxos (spentTxIns txBodyContent) walletUtxo (txBodyContent0, additionalBalance) <- addInputsForNonAdaAssets bal walletUtxo txBodyContent @@ -436,7 +431,7 @@ any non-Ada asset it contains. If the positive part only contains Ada then no output is added. -} addOutputForNonAdaAssets :: - Core.PParams Ledger.Era.ERA -> -- ^ Protocol parameters (for computing the minimum lovelace amount in the output) + C.BundledProtocolParameters BabbageEra -> -- ^ Protocol parameters (for computing the minimum lovelace amount in the output) C.AddressInEra C.BabbageEra -> -- ^ Address of the newly created output C.Value -> -- ^ The balance of the transaction TxBodyContent BuildTx ERA -> -- ^ Transaction body diff --git a/src/coin-selection/lib/Convex/CoinSelection/CardanoApi.hs b/src/coin-selection/lib/Convex/CoinSelection/CardanoApi.hs deleted file mode 100644 index 688c3750..00000000 --- a/src/coin-selection/lib/Convex/CoinSelection/CardanoApi.hs +++ /dev/null @@ -1,183 +0,0 @@ - -{-| Balancing functions from @cardano-api@, modified to use -the ledger's @PParams@ type instead of ProtocolParams from -cardano-api. --} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE EmptyCase #-} -{-# LANGUAGE GADTs #-} -{-# OPTIONS_GHC -Wno-unticked-promoted-constructors #-} -module Convex.CoinSelection.CardanoApi( - evaluateTransactionBalance, - evaluateTransactionFee, - evaluateTransactionExecutionUnits, - calculateMinimumUTxO -) where - -import qualified Cardano.Api as C -import qualified Cardano.Api.Shelley as C -import qualified Cardano.Ledger.Alonzo.Data as Alonzo -import qualified Cardano.Ledger.Alonzo.Language as Alonzo -import qualified Cardano.Ledger.Alonzo.Scripts as Alonzo -import qualified Cardano.Ledger.Alonzo.Tools as Alonzo -import qualified Cardano.Ledger.Alonzo.TxWitness as Alonzo -import qualified Cardano.Ledger.Babbage.PParams as Babbage -import qualified Cardano.Ledger.Babbage.TxBody as Babbage -import qualified Cardano.Ledger.Core as CLedger -import qualified Cardano.Ledger.Crypto as CLedger -import qualified Cardano.Ledger.Keys as CLedger -import qualified Cardano.Ledger.Shelley.API.Wallet as Shelley -import Cardano.Slotting.EpochInfo.API (EpochInfo, - hoistEpochInfo) -import Cardano.Slotting.Time (SystemStart) -import Control.Monad.Except (runExcept) -import qualified Convex.Era -import qualified Data.Array as Array -import Data.Bifunctor (bimap, first) -import Data.Map (Map) -import qualified Data.Map as Map -import Data.Set as Set (Set) -import qualified Data.Set as Set -import Data.Text (Text) -import qualified Data.Text as Text -import qualified Ouroboros.Consensus.HardFork.History as Consensus - --- | same as function defined in cardano-api but is specialized for Babbage era --- and accepts a Ledger.PParams as argument instead of ProtocolParameters -evaluateTransactionBalance :: - CLedger.PParams (C.ShelleyLedgerEra C.BabbageEra) - -> Set C.PoolId - -> C.UTxO C.BabbageEra - -> C.TxBody C.BabbageEra - -> C.TxOutValue C.BabbageEra -evaluateTransactionBalance pparams poolids utxo (C.ShelleyTxBody _ txbody _ _ _ _) = - C.TxOutValue C.MultiAssetInBabbageEra - $ C.fromMaryValue - $ Shelley.evaluateTransactionBalance pparams (C.toLedgerUTxO C.ShelleyBasedEraBabbage utxo) isNewPool txbody - - where - isNewPool :: CLedger.KeyHash CLedger.StakePool CLedger.StandardCrypto -> Bool - isNewPool kh = C.StakePoolKeyHash kh `Set.notMember` poolids - --- | same as function defined in cardano-api but is specialized for Babbage era --- and accepts a Ledger.PParams as argument instead of ProtocolParameters -evaluateTransactionFee :: - CLedger.PParams (C.ShelleyLedgerEra C.BabbageEra) - -> C.TxBody C.BabbageEra - -> Word -- ^ The number of Shelley key witnesses - -> C.Lovelace -evaluateTransactionFee pparams txbody keywitcount = - case C.makeSignedTransaction [] txbody of - C.ShelleyTx _ tx -> C.fromShelleyLovelace $ Shelley.evaluateTransactionFee pparams tx keywitcount - --- FIXME: Looks like this function is exposed by Cardano.Api in cardano-node@v1.36 -toLedgerEpochInfo :: C.EraHistory mode -> EpochInfo (Either Text) -toLedgerEpochInfo (C.EraHistory _ interpreter) = - hoistEpochInfo (first (Text.pack . show) . runExcept) $ - Consensus.interpreterToEpochInfo interpreter - --- | same as function defined in cardano-api but is specialized for Babbage era --- and accepts a Ledger.PParams as argument instead of ProtocolParameters -evaluateTransactionExecutionUnits :: - SystemStart - -> C.EraHistory C.CardanoMode - -> CLedger.PParams (C.ShelleyLedgerEra C.BabbageEra) - -> C.UTxO C.BabbageEra - -> C.TxBody C.BabbageEra - -> Either C.TransactionValidityError - (Map C.ScriptWitnessIndex (Either C.ScriptExecutionError C.ExecutionUnits)) -evaluateTransactionExecutionUnits systemstart history pparams utxo txbody = - -- considering babbageEra only - case C.makeSignedTransaction [] txbody of - C.ShelleyTx _ tx' -> evalBabbage tx' - - where - evalBabbage tx = - let costModelsArray = toAlonzoCostModelsArray pparams in - case Alonzo.evaluateTransactionExecutionUnits - pparams - tx - (C.toLedgerUTxO C.ShelleyBasedEraBabbage utxo) - (toLedgerEpochInfo history) - systemstart - costModelsArray - of Left err -> Left (C.TransactionValidityTranslationError err) - Right exmap -> Right (fromLedgerScriptExUnitsMap exmap) - - toAlonzoCostModelsArray - :: CLedger.PParams (C.ShelleyLedgerEra C.BabbageEra) - -> Array.Array Alonzo.Language Alonzo.CostModel - toAlonzoCostModelsArray lparams = - let Alonzo.CostModels cModels = Babbage._costmdls lparams in - Array.array (minBound, maxBound) (Map.toList cModels) - - - fromLedgerScriptExUnitsMap - :: Map Alonzo.RdmrPtr (Either (Alonzo.TransactionScriptFailure CLedger.StandardCrypto) Alonzo.ExUnits) - -> Map C.ScriptWitnessIndex (Either C.ScriptExecutionError C.ExecutionUnits) - fromLedgerScriptExUnitsMap exmap = - Map.fromList - [ (C.fromAlonzoRdmrPtr rdmrptr, - bimap fromAlonzoScriptExecutionError C.fromAlonzoExUnits exunitsOrFailure) - | (rdmrptr, exunitsOrFailure) <- Map.toList exmap ] - - - fromAlonzoScriptExecutionError :: Alonzo.TransactionScriptFailure CLedger.StandardCrypto - -> C.ScriptExecutionError - fromAlonzoScriptExecutionError failure = - case failure of - Alonzo.UnknownTxIn txin -> C.ScriptErrorMissingTxIn txin' - where txin' = C.fromShelleyTxIn txin - Alonzo.InvalidTxIn txin -> C.ScriptErrorTxInWithoutDatum txin' - where txin' = C.fromShelleyTxIn txin - Alonzo.MissingDatum dh -> C.ScriptErrorWrongDatum (C.ScriptDataHash dh) - Alonzo.ValidationFailedV1 err logs -> C.ScriptErrorEvaluationFailed err logs - Alonzo.ValidationFailedV2 err logs -> C.ScriptErrorEvaluationFailed err logs - Alonzo.IncompatibleBudget _ -> C.ScriptErrorExecutionUnitsOverflow - - -- This is only possible for spending scripts and occurs when - -- we attempt to spend a key witnessed tx input with a Plutus - -- script witness. - Alonzo.RedeemerNotNeeded rdmrPtr sh -> - C.ScriptErrorNotPlutusWitnessedTxIn - (C.fromAlonzoRdmrPtr rdmrPtr) - (C.fromShelleyScriptHash sh) - Alonzo.RedeemerPointsToUnknownScriptHash rdmrPtr -> - C.ScriptErrorRedeemerPointsToUnknownScriptHash $ C.fromAlonzoRdmrPtr rdmrPtr - -- This should not occur while using cardano-cli because we zip together - -- the Plutus script and the use site (txin, certificate etc). Therefore - -- the redeemer pointer will always point to a Plutus script. - Alonzo.MissingScript rdmrPtr resolveable -> C.ScriptErrorMissingScript rdmrPtr resolveable - - Alonzo.NoCostModelInLedgerState l -> C.ScriptErrorMissingCostModel l - -calculateMinimumUTxO - :: C.TxOut C.CtxTx C.BabbageEra - -> CLedger.PParams (C.ShelleyLedgerEra C.BabbageEra) - -> Either C.MinimumUTxOError C.Value -calculateMinimumUTxO txout pparams' = - let lTxOut = toShelleyTxOutAny txout - minUTxO = Shelley.evaluateMinLovelaceOutput pparams' lTxOut - val = C.lovelaceToValue $ C.fromShelleyLovelace minUTxO - in Right val - --- | A variant of 'toShelleyTxOutAny that is used only internally to this module --- that works with a 'TxOut' in any context (including CtxTx) by ignoring --- embedded datums (taking only their hash). --- -toShelleyTxOutAny :: C.TxOut C.CtxTx C.BabbageEra -> CLedger.TxOut (Convex.Era.ERA) -toShelleyTxOutAny (C.TxOut addr (C.TxOutValue C.MultiAssetInBabbageEra value) txoutdata refScript) = - let cEra = C.shelleyBasedToCardanoEra C.ShelleyBasedEraBabbage - in Babbage.TxOut (C.toShelleyAddr addr) (C.toMaryValue value) - (toBabbageTxOutDatum' txoutdata) (C.refScriptToShelleyScript cEra refScript) - --- TODO: Consolidate with alonzo function and rename -toBabbageTxOutDatum' - :: C.TxOutDatum C.CtxTx (C.BabbageEra) -> Babbage.Datum (Convex.Era.ERA) -toBabbageTxOutDatum' C.TxOutDatumNone = Babbage.NoDatum -toBabbageTxOutDatum' (C.TxOutDatumHash _ (C.ScriptDataHash dh)) = Babbage.DatumHash dh -toBabbageTxOutDatum' (C.TxOutDatumInTx _ d) = let C.ScriptDataHash hsh = C.hashScriptData d in Babbage.DatumHash hsh -toBabbageTxOutDatum' (C.TxOutDatumInline _ sd) = scriptDataToInlineDatum sd - -scriptDataToInlineDatum :: C.ScriptData -> Babbage.Datum ledgerera -scriptDataToInlineDatum = Babbage.Datum . Alonzo.dataToBinaryData . C.toAlonzoData diff --git a/src/coin-selection/test/Scripts.hs b/src/coin-selection/test/Scripts.hs index 31e1448b..93af1979 100644 --- a/src/coin-selection/test/Scripts.hs +++ b/src/coin-selection/test/Scripts.hs @@ -1,20 +1,18 @@ +{-# OPTIONS_GHC -fobject-code -fno-ignore-interface-pragmas -fno-omit-interface-pragmas -fplugin-opt PlutusTx.Plugin:target-version=1.0.0 #-} -- 1.1.0.0 will be enabled in conway {-# LANGUAGE DataKinds #-} {-# LANGUAGE TemplateHaskell #-} -- | Scripts used for testing module Scripts( + v2SpendingScriptSerialised, v2SpendingScript ) where -import qualified Cardano.Api.Shelley as C -import Convex.Scripts (compiledCodeToScript) -import qualified PlutusTx -import PlutusTx.Builtins (BuiltinData) +import qualified Cardano.Api.Shelley as C +import PlutusLedgerApi.Common (SerialisedScript) +import PlutusLedgerApi.Test.Examples (alwaysSucceedingNAryFunction) -type UntypedValidator = BuiltinData -> BuiltinData -> BuiltinData -> () - -unappliedRewardFeeValidator :: PlutusTx.CompiledCode UntypedValidator -unappliedRewardFeeValidator = $$(PlutusTx.compile [|| \_ _ _ -> () ||]) - --- | Validator that always succeeds v2SpendingScript :: C.PlutusScript C.PlutusScriptV2 -v2SpendingScript = compiledCodeToScript unappliedRewardFeeValidator +v2SpendingScript = C.PlutusScriptSerialised $ alwaysSucceedingNAryFunction 3 + +v2SpendingScriptSerialised :: SerialisedScript +v2SpendingScriptSerialised = alwaysSucceedingNAryFunction 3 diff --git a/src/coin-selection/test/Spec.hs b/src/coin-selection/test/Spec.hs index 555b515d..2a6127c9 100644 --- a/src/coin-selection/test/Spec.hs +++ b/src/coin-selection/test/Spec.hs @@ -4,15 +4,20 @@ module Main(main) where import qualified Cardano.Api.Shelley as C +import Cardano.Ledger.Alonzo.Scripts (AlonzoScript (..), + transProtocolVersion, + validScript) +import Cardano.Ledger.Language (Language (..)) import Control.Lens (_4, mapped, over, view, (&)) import Control.Monad (void) +import Control.Monad.Except (runExcept) import Convex.BuildTx (assetValue, mintPlutusV1, payToAddress, payToPlutusV1, payToPlutusV2, payToPlutusV2Inline, setMinAdaDeposit, setMinAdaDepositAll, - spendPlutusV1, + spendPlutusV1, spendPlutusV2, spendPlutusV2Ref) import Convex.Class (MonadBlockchain (..), MonadMockchain) @@ -27,10 +32,12 @@ import qualified Convex.Wallet as Wallet import qualified Convex.Wallet.MockWallet as Wallet import qualified Data.Map as Map import qualified Data.Set as Set +import qualified PlutusLedgerApi.V2 as PV2 import qualified Scripts import Test.Tasty (TestTree, defaultMain, testGroup) -import Test.Tasty.HUnit (Assertion, testCase) +import Test.Tasty.HUnit (Assertion, assertBool, + testCase) main :: IO () main = defaultMain tests @@ -44,6 +51,8 @@ tests = testGroup "unit tests" , testGroup "scripts" [ testCase "paying to a plutus script" (mockchainSucceeds payToPlutusScript) , testCase "spending a plutus script output" (mockchainSucceeds (payToPlutusScript >>= spendPlutusScript)) + , testCase "spending a plutus script (V2) output" (mockchainSucceeds (payToPlutusV2Script >>= spendPlutusV2Script)) + , testCase "well-formed scripts" wellFormedScripts , testCase "creating a reference script output" (mockchainSucceeds $ putReferenceScript Wallet.w1) , testCase "using a reference script" (mockchainSucceeds (payToPlutusV2Script >>= spendPlutusScriptReference)) , testCase "minting a token" (mockchainSucceeds mintingPlutus) @@ -54,6 +63,13 @@ tests = testGroup "unit tests" spendPublicKeyOutput :: Assertion spendPublicKeyOutput = mockchainSucceeds (Wallet.w2 `paymentTo` Wallet.w1) +wellFormedScripts :: Assertion +wellFormedScripts = do + let protVer = Defaults.protVer Defaults.nodeParams + s = Cardano.Ledger.Alonzo.Scripts.PlutusScript PlutusV2 Scripts.v2SpendingScriptSerialised + either (fail . show) pure (runExcept (PV2.assertScriptWellFormed (transProtocolVersion protVer) Scripts.v2SpendingScriptSerialised)) + assertBool "validScript" (validScript protVer s) + makeSeveralPayments :: Assertion makeSeveralPayments = mockchainSucceeds $ do void $ Wallet.w1 `paymentTo` Wallet.w2 @@ -84,13 +100,18 @@ spendPlutusScript ref = do let tx = emptyTx & spendPlutusV1 ref txInscript () () C.getTxId . C.getTxBody <$> balanceAndSubmit Wallet.w1 tx +spendPlutusV2Script :: C.TxIn -> Mockchain C.TxId +spendPlutusV2Script ref = do + let tx = emptyTx & spendPlutusV2 ref Scripts.v2SpendingScript () () + C.getTxId . C.getTxBody <$> balanceAndSubmit Wallet.w1 tx + putReferenceScript :: Wallet -> Mockchain C.TxIn putReferenceScript wallet = do let hsh = C.hashScript (C.PlutusScript C.PlutusScriptV2 Scripts.v2SpendingScript) addr = C.makeShelleyAddressInEra Defaults.networkId (C.PaymentCredentialByScript hsh) C.NoStakeAddress - let tx = emptyTx + tx = emptyTx & payToPlutusV2Inline addr Scripts.v2SpendingScript (C.lovelaceToValue 10_000_000) - & setMinAdaDepositAll Defaults.ledgerProtocolParameters + & setMinAdaDepositAll Defaults.bundledProtocolParameters txId <- C.getTxId . C.getTxBody <$> balanceAndSubmit wallet tx let outRef = C.TxIn txId (C.TxIx 0) C.UTxO utxo <- utxoByTxIn (Set.singleton outRef) @@ -121,12 +142,12 @@ spendTokens _ = do _ <- nativeAssetPaymentTo 100 Wallet.w2 Wallet.w3 nativeAssetPaymentTo 99 Wallet.w3 Wallet.w1 -nativeAssetPaymentTo :: (MonadBlockchain m, MonadMockchain m, MonadFail m) => C.Quantity -> Wallet -> Wallet -> m C.TxId +nativeAssetPaymentTo :: (MonadMockchain m, MonadFail m) => C.Quantity -> Wallet -> Wallet -> m C.TxId nativeAssetPaymentTo q wFrom wTo = do let vl = assetValue (C.hashScript $ C.PlutusScript C.PlutusScriptV1 mintingScript) "assetName" q tx = emptyTx & payToAddress (Wallet.addressInEra Defaults.networkId wTo) vl - & over (L.txOuts . mapped) (setMinAdaDeposit Defaults.ledgerProtocolParameters) + & over (L.txOuts . mapped) (setMinAdaDeposit Defaults.bundledProtocolParameters) -- create a public key output for the sender to make -- sure that the sender has enough Ada in ada-only inputs void $ wTo `paymentTo` wFrom diff --git a/src/devnet/config/devnet/cardano-node.json b/src/devnet/config/devnet/cardano-node.json index ed78e57d..4d1998fe 100644 --- a/src/devnet/config/devnet/cardano-node.json +++ b/src/devnet/config/devnet/cardano-node.json @@ -4,6 +4,7 @@ "ByronGenesisFile": "genesis-byron.json", "ShelleyGenesisFile": "genesis-shelley.json", "AlonzoGenesisFile": "genesis-alonzo.json", + "ConwayGenesisFile": "genesis-conway.json", "ApplicationName": "cardano-sl", "ApplicationVersion": 1, @@ -74,6 +75,6 @@ } }, - "TestEnableDevelopmentHardForkEras": true, - "TestEnableDevelopmentNetworkProtocols": true + "ExperimentalHardForksEnabled": true, + "ExperimentalProtocolsEnabled": true } diff --git a/src/devnet/config/devnet/genesis-alonzo.json b/src/devnet/config/devnet/genesis-alonzo.json index f0f74e99..0fd90dee 100644 --- a/src/devnet/config/devnet/genesis-alonzo.json +++ b/src/devnet/config/devnet/genesis-alonzo.json @@ -1,365 +1,196 @@ { + "lovelacePerUTxOWord": 34482, + "executionPrices": { + "prSteps": + { + "numerator" : 721, + "denominator" : 10000000 + }, + "prMem": + { + "numerator" : 577, + "denominator" : 10000 + } + }, + "maxTxExUnits": { + "exUnitsMem": 10000000, + "exUnitsSteps": 10000000000 + }, + "maxBlockExUnits": { + "exUnitsMem": 50000000, + "exUnitsSteps": 40000000000 + }, + "maxValueSize": 5000, "collateralPercentage": 150, + "maxCollateralInputs": 3, "costModels": { "PlutusV1": { - "addInteger-cpu-arguments-intercept": 205665, - "addInteger-cpu-arguments-slope": 812, - "addInteger-memory-arguments-intercept": 1, - "addInteger-memory-arguments-slope": 1, - "appendByteString-cpu-arguments-intercept": 1000, - "appendByteString-cpu-arguments-slope": 571, - "appendByteString-memory-arguments-intercept": 0, - "appendByteString-memory-arguments-slope": 1, - "appendString-cpu-arguments-intercept": 1000, - "appendString-cpu-arguments-slope": 24177, - "appendString-memory-arguments-intercept": 4, - "appendString-memory-arguments-slope": 1, - "bData-cpu-arguments": 1000, - "bData-memory-arguments": 32, - "blake2b_256-cpu-arguments-intercept": 117366, - "blake2b_256-cpu-arguments-slope": 10475, - "blake2b_256-memory-arguments": 4, - "cekApplyCost-exBudgetCPU": 23000, - "cekApplyCost-exBudgetMemory": 100, - "cekBuiltinCost-exBudgetCPU": 23000, - "cekBuiltinCost-exBudgetMemory": 100, - "cekConstCost-exBudgetCPU": 23000, - "cekConstCost-exBudgetMemory": 100, - "cekDelayCost-exBudgetCPU": 23000, + "sha2_256-memory-arguments": 4, + "equalsString-cpu-arguments-constant": 1000, "cekDelayCost-exBudgetMemory": 100, - "cekForceCost-exBudgetCPU": 23000, - "cekForceCost-exBudgetMemory": 100, - "cekLamCost-exBudgetCPU": 23000, - "cekLamCost-exBudgetMemory": 100, - "cekStartupCost-exBudgetCPU": 100, - "cekStartupCost-exBudgetMemory": 100, - "cekVarCost-exBudgetCPU": 23000, - "cekVarCost-exBudgetMemory": 100, - "chooseData-cpu-arguments": 19537, + "lessThanEqualsByteString-cpu-arguments-intercept": 103599, + "divideInteger-memory-arguments-minimum": 1, + "appendByteString-cpu-arguments-slope": 621, + "blake2b-cpu-arguments-slope": 29175, + "iData-cpu-arguments": 150000, + "encodeUtf8-cpu-arguments-slope": 1000, + "unBData-cpu-arguments": 150000, + "multiplyInteger-cpu-arguments-intercept": 61516, + "cekConstCost-exBudgetMemory": 100, + "nullList-cpu-arguments": 150000, + "equalsString-cpu-arguments-intercept": 150000, + "trace-cpu-arguments": 150000, + "mkNilData-memory-arguments": 32, + "lengthOfByteString-cpu-arguments": 150000, + "cekBuiltinCost-exBudgetCPU": 29773, + "bData-cpu-arguments": 150000, + "subtractInteger-cpu-arguments-slope": 0, + "unIData-cpu-arguments": 150000, + "consByteString-memory-arguments-intercept": 0, + "divideInteger-memory-arguments-slope": 1, + "divideInteger-cpu-arguments-model-arguments-slope": 118, + "listData-cpu-arguments": 150000, + "headList-cpu-arguments": 150000, "chooseData-memory-arguments": 32, - "chooseList-cpu-arguments": 175354, + "equalsInteger-cpu-arguments-intercept": 136542, + "sha3_256-cpu-arguments-slope": 82363, + "sliceByteString-cpu-arguments-slope": 5000, + "unMapData-cpu-arguments": 150000, + "lessThanInteger-cpu-arguments-intercept": 179690, + "mkCons-cpu-arguments": 150000, + "appendString-memory-arguments-intercept": 0, + "modInteger-cpu-arguments-model-arguments-slope": 118, + "ifThenElse-cpu-arguments": 1, + "mkNilPairData-cpu-arguments": 150000, + "lessThanEqualsInteger-cpu-arguments-intercept": 145276, + "addInteger-memory-arguments-slope": 1, "chooseList-memory-arguments": 32, - "chooseUnit-cpu-arguments": 46417, - "chooseUnit-memory-arguments": 4, - "consByteString-cpu-arguments-intercept": 221973, - "consByteString-cpu-arguments-slope": 511, - "consByteString-memory-arguments-intercept": 0, - "consByteString-memory-arguments-slope": 1, - "constrData-cpu-arguments": 89141, "constrData-memory-arguments": 32, - "decodeUtf8-cpu-arguments-intercept": 497525, - "decodeUtf8-cpu-arguments-slope": 14068, - "decodeUtf8-memory-arguments-intercept": 4, - "decodeUtf8-memory-arguments-slope": 2, - "divideInteger-cpu-arguments-constant": 196500, - "divideInteger-cpu-arguments-model-arguments-intercept": 453240, - "divideInteger-cpu-arguments-model-arguments-slope": 220, - "divideInteger-memory-arguments-intercept": 0, - "divideInteger-memory-arguments-minimum": 1, - "divideInteger-memory-arguments-slope": 1, - "encodeUtf8-cpu-arguments-intercept": 1000, - "encodeUtf8-cpu-arguments-slope": 28662, - "encodeUtf8-memory-arguments-intercept": 4, - "encodeUtf8-memory-arguments-slope": 2, - "equalsByteString-cpu-arguments-constant": 245000, - "equalsByteString-cpu-arguments-intercept": 216773, - "equalsByteString-cpu-arguments-slope": 62, - "equalsByteString-memory-arguments": 1, - "equalsData-cpu-arguments-intercept": 1060367, - "equalsData-cpu-arguments-slope": 12586, + "decodeUtf8-cpu-arguments-intercept": 150000, "equalsData-memory-arguments": 1, - "equalsInteger-cpu-arguments-intercept": 208512, - "equalsInteger-cpu-arguments-slope": 421, - "equalsInteger-memory-arguments": 1, - "equalsString-cpu-arguments-constant": 187000, - "equalsString-cpu-arguments-intercept": 1000, - "equalsString-cpu-arguments-slope": 52998, - "equalsString-memory-arguments": 1, - "fstPair-cpu-arguments": 80436, - "fstPair-memory-arguments": 32, - "headList-cpu-arguments": 43249, + "subtractInteger-memory-arguments-slope": 1, + "appendByteString-memory-arguments-intercept": 0, + "lengthOfByteString-memory-arguments": 4, "headList-memory-arguments": 32, - "iData-cpu-arguments": 1000, - "iData-memory-arguments": 32, - "ifThenElse-cpu-arguments": 80556, - "ifThenElse-memory-arguments": 1, - "indexByteString-cpu-arguments": 57667, - "indexByteString-memory-arguments": 4, - "lengthOfByteString-cpu-arguments": 1000, - "lengthOfByteString-memory-arguments": 10, - "lessThanByteString-cpu-arguments-intercept": 197145, - "lessThanByteString-cpu-arguments-slope": 156, - "lessThanByteString-memory-arguments": 1, - "lessThanEqualsByteString-cpu-arguments-intercept": 197145, - "lessThanEqualsByteString-cpu-arguments-slope": 156, - "lessThanEqualsByteString-memory-arguments": 1, - "lessThanEqualsInteger-cpu-arguments-intercept": 204924, - "lessThanEqualsInteger-cpu-arguments-slope": 473, - "lessThanEqualsInteger-memory-arguments": 1, - "lessThanInteger-cpu-arguments-intercept": 208896, - "lessThanInteger-cpu-arguments-slope": 511, - "lessThanInteger-memory-arguments": 1, - "listData-cpu-arguments": 52467, "listData-memory-arguments": 32, - "mapData-cpu-arguments": 64832, - "mapData-memory-arguments": 32, - "mkCons-cpu-arguments": 65493, - "mkCons-memory-arguments": 32, - "mkNilData-cpu-arguments": 22558, - "mkNilData-memory-arguments": 32, - "mkNilPairData-cpu-arguments": 16563, - "mkNilPairData-memory-arguments": 32, - "mkPairData-cpu-arguments": 76511, - "mkPairData-memory-arguments": 32, - "modInteger-cpu-arguments-constant": 196500, - "modInteger-cpu-arguments-model-arguments-intercept": 453240, - "modInteger-cpu-arguments-model-arguments-slope": 220, - "modInteger-memory-arguments-intercept": 0, - "modInteger-memory-arguments-minimum": 1, - "modInteger-memory-arguments-slope": 1, - "multiplyInteger-cpu-arguments-intercept": 69522, - "multiplyInteger-cpu-arguments-slope": 11687, - "multiplyInteger-memory-arguments-intercept": 0, - "multiplyInteger-memory-arguments-slope": 1, - "nullList-cpu-arguments": 60091, - "nullList-memory-arguments": 32, - "quotientInteger-cpu-arguments-constant": 196500, - "quotientInteger-cpu-arguments-model-arguments-intercept": 453240, - "quotientInteger-cpu-arguments-model-arguments-slope": 220, - "quotientInteger-memory-arguments-intercept": 0, - "quotientInteger-memory-arguments-minimum": 1, - "quotientInteger-memory-arguments-slope": 1, - "remainderInteger-cpu-arguments-constant": 196500, - "remainderInteger-cpu-arguments-model-arguments-intercept": 453240, - "remainderInteger-cpu-arguments-model-arguments-slope": 220, - "remainderInteger-memory-arguments-intercept": 0, - "remainderInteger-memory-arguments-minimum": 1, - "remainderInteger-memory-arguments-slope": 1, - "sha2_256-cpu-arguments-intercept": 806990, - "sha2_256-cpu-arguments-slope": 30482, - "sha2_256-memory-arguments": 4, - "sha3_256-cpu-arguments-intercept": 1927926, - "sha3_256-cpu-arguments-slope": 82523, - "sha3_256-memory-arguments": 4, - "sliceByteString-cpu-arguments-intercept": 265318, - "sliceByteString-cpu-arguments-slope": 0, - "sliceByteString-memory-arguments-intercept": 4, - "sliceByteString-memory-arguments-slope": 0, - "sndPair-cpu-arguments": 85931, - "sndPair-memory-arguments": 32, - "subtractInteger-cpu-arguments-intercept": 205665, - "subtractInteger-cpu-arguments-slope": 812, - "subtractInteger-memory-arguments-intercept": 1, - "subtractInteger-memory-arguments-slope": 1, - "tailList-cpu-arguments": 41182, - "tailList-memory-arguments": 32, - "trace-cpu-arguments": 212342, - "trace-memory-arguments": 32, - "unBData-cpu-arguments": 31220, - "unBData-memory-arguments": 32, - "unConstrData-cpu-arguments": 32696, - "unConstrData-memory-arguments": 32, - "unIData-cpu-arguments": 43357, + "consByteString-cpu-arguments-intercept": 150000, "unIData-memory-arguments": 32, - "unListData-cpu-arguments": 32247, - "unListData-memory-arguments": 32, - "unMapData-cpu-arguments": 38314, - "unMapData-memory-arguments": 32, - "verifyEd25519Signature-cpu-arguments-intercept": 9462713, - "verifyEd25519Signature-cpu-arguments-slope": 1021, - "verifyEd25519Signature-memory-arguments": 10 - }, - "PlutusV2": { - "addInteger-cpu-arguments-intercept": 205665, - "addInteger-cpu-arguments-slope": 812, - "addInteger-memory-arguments-intercept": 1, - "addInteger-memory-arguments-slope": 1, - "appendByteString-cpu-arguments-intercept": 1000, - "appendByteString-cpu-arguments-slope": 571, - "appendByteString-memory-arguments-intercept": 0, - "appendByteString-memory-arguments-slope": 1, - "appendString-cpu-arguments-intercept": 1000, - "appendString-cpu-arguments-slope": 24177, - "appendString-memory-arguments-intercept": 4, - "appendString-memory-arguments-slope": 1, - "bData-cpu-arguments": 1000, + "remainderInteger-memory-arguments-minimum": 1, "bData-memory-arguments": 32, - "blake2b_256-cpu-arguments-intercept": 117366, - "blake2b_256-cpu-arguments-slope": 10475, - "blake2b_256-memory-arguments": 4, - "cekApplyCost-exBudgetCPU": 23000, - "cekApplyCost-exBudgetMemory": 100, - "cekBuiltinCost-exBudgetCPU": 23000, - "cekBuiltinCost-exBudgetMemory": 100, - "cekConstCost-exBudgetCPU": 23000, - "cekConstCost-exBudgetMemory": 100, - "cekDelayCost-exBudgetCPU": 23000, - "cekDelayCost-exBudgetMemory": 100, - "cekForceCost-exBudgetCPU": 23000, - "cekForceCost-exBudgetMemory": 100, - "cekLamCost-exBudgetCPU": 23000, - "cekLamCost-exBudgetMemory": 100, + "lessThanByteString-cpu-arguments-slope": 248, + "encodeUtf8-memory-arguments-intercept": 0, "cekStartupCost-exBudgetCPU": 100, - "cekStartupCost-exBudgetMemory": 100, - "cekVarCost-exBudgetCPU": 23000, - "cekVarCost-exBudgetMemory": 100, - "chooseData-cpu-arguments": 19537, - "chooseData-memory-arguments": 32, - "chooseList-cpu-arguments": 175354, - "chooseList-memory-arguments": 32, - "chooseUnit-cpu-arguments": 46417, - "chooseUnit-memory-arguments": 4, - "consByteString-cpu-arguments-intercept": 221973, - "consByteString-cpu-arguments-slope": 511, - "consByteString-memory-arguments-intercept": 0, - "consByteString-memory-arguments-slope": 1, - "constrData-cpu-arguments": 89141, - "constrData-memory-arguments": 32, - "decodeUtf8-cpu-arguments-intercept": 497525, - "decodeUtf8-cpu-arguments-slope": 14068, - "decodeUtf8-memory-arguments-intercept": 4, - "decodeUtf8-memory-arguments-slope": 2, - "divideInteger-cpu-arguments-constant": 196500, - "divideInteger-cpu-arguments-model-arguments-intercept": 453240, - "divideInteger-cpu-arguments-model-arguments-slope": 220, - "divideInteger-memory-arguments-intercept": 0, - "divideInteger-memory-arguments-minimum": 1, - "divideInteger-memory-arguments-slope": 1, - "encodeUtf8-cpu-arguments-intercept": 1000, - "encodeUtf8-cpu-arguments-slope": 28662, - "encodeUtf8-memory-arguments-intercept": 4, - "encodeUtf8-memory-arguments-slope": 2, - "equalsByteString-cpu-arguments-constant": 245000, - "equalsByteString-cpu-arguments-intercept": 216773, - "equalsByteString-cpu-arguments-slope": 62, - "equalsByteString-memory-arguments": 1, - "equalsData-cpu-arguments-intercept": 1060367, - "equalsData-cpu-arguments-slope": 12586, - "equalsData-memory-arguments": 1, - "equalsInteger-cpu-arguments-intercept": 208512, - "equalsInteger-cpu-arguments-slope": 421, + "multiplyInteger-memory-arguments-intercept": 0, + "unListData-memory-arguments": 32, + "remainderInteger-cpu-arguments-model-arguments-slope": 118, + "cekVarCost-exBudgetCPU": 29773, + "remainderInteger-memory-arguments-slope": 1, + "cekForceCost-exBudgetCPU": 29773, + "sha2_256-cpu-arguments-slope": 29175, "equalsInteger-memory-arguments": 1, - "equalsString-cpu-arguments-constant": 187000, - "equalsString-cpu-arguments-intercept": 1000, - "equalsString-cpu-arguments-slope": 52998, - "equalsString-memory-arguments": 1, - "fstPair-cpu-arguments": 80436, + "indexByteString-memory-arguments": 1, + "addInteger-memory-arguments-intercept": 1, + "chooseUnit-cpu-arguments": 150000, + "sndPair-cpu-arguments": 150000, + "cekLamCost-exBudgetCPU": 29773, + "fstPair-cpu-arguments": 150000, + "quotientInteger-memory-arguments-minimum": 1, + "decodeUtf8-cpu-arguments-slope": 1000, + "lessThanInteger-memory-arguments": 1, + "lessThanEqualsInteger-cpu-arguments-slope": 1366, "fstPair-memory-arguments": 32, - "headList-cpu-arguments": 43249, - "headList-memory-arguments": 32, - "iData-cpu-arguments": 1000, - "iData-memory-arguments": 32, - "ifThenElse-cpu-arguments": 80556, - "ifThenElse-memory-arguments": 1, - "indexByteString-cpu-arguments": 57667, - "indexByteString-memory-arguments": 4, - "lengthOfByteString-cpu-arguments": 1000, - "lengthOfByteString-memory-arguments": 10, - "lessThanByteString-cpu-arguments-intercept": 197145, - "lessThanByteString-cpu-arguments-slope": 156, - "lessThanByteString-memory-arguments": 1, - "lessThanEqualsByteString-cpu-arguments-intercept": 197145, - "lessThanEqualsByteString-cpu-arguments-slope": 156, - "lessThanEqualsByteString-memory-arguments": 1, - "lessThanEqualsInteger-cpu-arguments-intercept": 204924, - "lessThanEqualsInteger-cpu-arguments-slope": 473, + "modInteger-memory-arguments-intercept": 0, + "unConstrData-cpu-arguments": 150000, "lessThanEqualsInteger-memory-arguments": 1, - "lessThanInteger-cpu-arguments-intercept": 208896, - "lessThanInteger-cpu-arguments-slope": 511, - "lessThanInteger-memory-arguments": 1, - "listData-cpu-arguments": 52467, - "listData-memory-arguments": 32, - "mapData-cpu-arguments": 64832, - "mapData-memory-arguments": 32, - "mkCons-cpu-arguments": 65493, + "chooseUnit-memory-arguments": 32, + "sndPair-memory-arguments": 32, + "addInteger-cpu-arguments-intercept": 197209, + "decodeUtf8-memory-arguments-slope": 8, + "equalsData-cpu-arguments-intercept": 150000, + "mapData-cpu-arguments": 150000, + "mkPairData-cpu-arguments": 150000, + "quotientInteger-cpu-arguments-constant": 148000, + "consByteString-memory-arguments-slope": 1, + "cekVarCost-exBudgetMemory": 100, + "indexByteString-cpu-arguments": 150000, + "unListData-cpu-arguments": 150000, + "equalsInteger-cpu-arguments-slope": 1326, + "cekStartupCost-exBudgetMemory": 100, + "subtractInteger-cpu-arguments-intercept": 197209, + "divideInteger-cpu-arguments-model-arguments-intercept": 425507, + "divideInteger-memory-arguments-intercept": 0, + "cekForceCost-exBudgetMemory": 100, + "blake2b-cpu-arguments-intercept": 2477736, + "remainderInteger-cpu-arguments-constant": 148000, + "tailList-cpu-arguments": 150000, + "encodeUtf8-cpu-arguments-intercept": 150000, + "equalsString-cpu-arguments-slope": 1000, + "lessThanByteString-memory-arguments": 1, + "multiplyInteger-cpu-arguments-slope": 11218, + "appendByteString-cpu-arguments-intercept": 396231, + "lessThanEqualsByteString-cpu-arguments-slope": 248, + "modInteger-memory-arguments-slope": 1, + "addInteger-cpu-arguments-slope": 0, + "equalsData-cpu-arguments-slope": 10000, + "decodeUtf8-memory-arguments-intercept": 0, + "chooseList-cpu-arguments": 150000, + "constrData-cpu-arguments": 150000, + "equalsByteString-memory-arguments": 1, + "cekApplyCost-exBudgetCPU": 29773, + "quotientInteger-memory-arguments-slope": 1, + "verifySignature-cpu-arguments-intercept": 3345831, + "unMapData-memory-arguments": 32, "mkCons-memory-arguments": 32, - "mkNilData-cpu-arguments": 22558, - "mkNilData-memory-arguments": 32, - "mkNilPairData-cpu-arguments": 16563, + "sliceByteString-memory-arguments-slope": 1, + "sha3_256-memory-arguments": 4, + "ifThenElse-memory-arguments": 1, "mkNilPairData-memory-arguments": 32, - "mkPairData-cpu-arguments": 76511, - "mkPairData-memory-arguments": 32, - "modInteger-cpu-arguments-constant": 196500, - "modInteger-cpu-arguments-model-arguments-intercept": 453240, - "modInteger-cpu-arguments-model-arguments-slope": 220, - "modInteger-memory-arguments-intercept": 0, - "modInteger-memory-arguments-minimum": 1, - "modInteger-memory-arguments-slope": 1, - "multiplyInteger-cpu-arguments-intercept": 69522, - "multiplyInteger-cpu-arguments-slope": 11687, - "multiplyInteger-memory-arguments-intercept": 0, + "equalsByteString-cpu-arguments-slope": 247, + "appendString-cpu-arguments-intercept": 150000, + "quotientInteger-cpu-arguments-model-arguments-slope": 118, + "cekApplyCost-exBudgetMemory": 100, + "equalsString-memory-arguments": 1, "multiplyInteger-memory-arguments-slope": 1, - "nullList-cpu-arguments": 60091, - "nullList-memory-arguments": 32, - "quotientInteger-cpu-arguments-constant": 196500, - "quotientInteger-cpu-arguments-model-arguments-intercept": 453240, - "quotientInteger-cpu-arguments-model-arguments-slope": 220, - "quotientInteger-memory-arguments-intercept": 0, - "quotientInteger-memory-arguments-minimum": 1, - "quotientInteger-memory-arguments-slope": 1, - "remainderInteger-cpu-arguments-constant": 196500, - "remainderInteger-cpu-arguments-model-arguments-intercept": 453240, - "remainderInteger-cpu-arguments-model-arguments-slope": 220, + "cekBuiltinCost-exBudgetMemory": 100, "remainderInteger-memory-arguments-intercept": 0, - "remainderInteger-memory-arguments-minimum": 1, - "remainderInteger-memory-arguments-slope": 1, - "serialiseData-cpu-arguments-intercept": 1159724, - "serialiseData-cpu-arguments-slope": 392670, - "serialiseData-memory-arguments-intercept": 0, - "serialiseData-memory-arguments-slope": 2, - "sha2_256-cpu-arguments-intercept": 806990, - "sha2_256-cpu-arguments-slope": 30482, - "sha2_256-memory-arguments": 4, - "sha3_256-cpu-arguments-intercept": 1927926, - "sha3_256-cpu-arguments-slope": 82523, - "sha3_256-memory-arguments": 4, - "sliceByteString-cpu-arguments-intercept": 265318, - "sliceByteString-cpu-arguments-slope": 0, - "sliceByteString-memory-arguments-intercept": 4, - "sliceByteString-memory-arguments-slope": 0, - "sndPair-cpu-arguments": 85931, - "sndPair-memory-arguments": 32, - "subtractInteger-cpu-arguments-intercept": 205665, - "subtractInteger-cpu-arguments-slope": 812, - "subtractInteger-memory-arguments-intercept": 1, - "subtractInteger-memory-arguments-slope": 1, - "tailList-cpu-arguments": 41182, + "sha2_256-cpu-arguments-intercept": 2477736, + "remainderInteger-cpu-arguments-model-arguments-intercept": 425507, + "lessThanEqualsByteString-memory-arguments": 1, "tailList-memory-arguments": 32, - "trace-cpu-arguments": 212342, - "trace-memory-arguments": 32, - "unBData-cpu-arguments": 31220, + "mkNilData-cpu-arguments": 150000, + "chooseData-cpu-arguments": 150000, "unBData-memory-arguments": 32, - "unConstrData-cpu-arguments": 32696, + "blake2b-memory-arguments": 4, + "iData-memory-arguments": 32, + "nullList-memory-arguments": 32, + "cekDelayCost-exBudgetCPU": 29773, + "subtractInteger-memory-arguments-intercept": 1, + "lessThanByteString-cpu-arguments-intercept": 103599, + "consByteString-cpu-arguments-slope": 1000, + "appendByteString-memory-arguments-slope": 1, + "trace-memory-arguments": 32, + "divideInteger-cpu-arguments-constant": 148000, + "cekConstCost-exBudgetCPU": 29773, + "encodeUtf8-memory-arguments-slope": 8, + "quotientInteger-cpu-arguments-model-arguments-intercept": 425507, + "mapData-memory-arguments": 32, + "appendString-cpu-arguments-slope": 1000, + "modInteger-cpu-arguments-constant": 148000, + "verifySignature-cpu-arguments-slope": 1, "unConstrData-memory-arguments": 32, - "unIData-cpu-arguments": 43357, - "unIData-memory-arguments": 32, - "unListData-cpu-arguments": 32247, - "unListData-memory-arguments": 32, - "unMapData-cpu-arguments": 38314, - "unMapData-memory-arguments": 32, - "verifyEcdsaSecp256k1Signature-cpu-arguments": 20000000000, - "verifyEcdsaSecp256k1Signature-memory-arguments": 20000000000, - "verifyEd25519Signature-cpu-arguments-intercept": 9462713, - "verifyEd25519Signature-cpu-arguments-slope": 1021, - "verifyEd25519Signature-memory-arguments": 10, - "verifySchnorrSecp256k1Signature-cpu-arguments-intercept": 20000000000, - "verifySchnorrSecp256k1Signature-cpu-arguments-slope": 0, - "verifySchnorrSecp256k1Signature-memory-arguments": 20000000000 + "quotientInteger-memory-arguments-intercept": 0, + "equalsByteString-cpu-arguments-constant": 150000, + "sliceByteString-memory-arguments-intercept": 0, + "mkPairData-memory-arguments": 32, + "equalsByteString-cpu-arguments-intercept": 112536, + "appendString-memory-arguments-slope": 1, + "lessThanInteger-cpu-arguments-slope": 497, + "modInteger-cpu-arguments-model-arguments-intercept": 425507, + "modInteger-memory-arguments-minimum": 1, + "sha3_256-cpu-arguments-intercept": 0, + "verifySignature-memory-arguments": 1, + "cekLamCost-exBudgetMemory": 100, + "sliceByteString-cpu-arguments-intercept": 150000 } - }, - "executionPrices": { - "prMem": 5.77e-2, - "prSteps": 7.21e-5 - }, - "lovelacePerUTxOWord": 34482, - "maxBlockExUnits": { - "exUnitsMem": 62000000, - "exUnitsSteps": 40000000000 - }, - "maxCollateralInputs": 3, - "maxTxExUnits": { - "exUnitsMem": 14000000, - "exUnitsSteps": 10000000000 - }, - "maxValueSize": 5000 + } } diff --git a/src/devnet/config/devnet/genesis-conway.json b/src/devnet/config/devnet/genesis-conway.json new file mode 100644 index 00000000..c4e3a5bf --- /dev/null +++ b/src/devnet/config/devnet/genesis-conway.json @@ -0,0 +1,4 @@ +{ + "genDelegs": {} + } + \ No newline at end of file diff --git a/src/devnet/convex-devnet.cabal b/src/devnet/convex-devnet.cabal index fb3d3888..7c83b187 100644 --- a/src/devnet/convex-devnet.cabal +++ b/src/devnet/convex-devnet.cabal @@ -22,6 +22,7 @@ data-files: config/devnet/cardano-node.json config/devnet/genesis-alonzo.json config/devnet/genesis-byron.json + config/devnet/genesis-conway.json config/devnet/genesis-shelley.json config/devnet/kes.skey config/devnet/opcert.cert @@ -66,8 +67,9 @@ library , convex-base , convex-coin-selection , mtl + , stm + , si-timers , prettyprinter - , transformers -- cardano-node deps. , cardano-api diff --git a/src/devnet/lib/Convex/Devnet/CardanoNode.hs b/src/devnet/lib/Convex/Devnet/CardanoNode.hs index 9017879e..efc8c241 100644 --- a/src/devnet/lib/Convex/Devnet/CardanoNode.hs +++ b/src/devnet/lib/Convex/Devnet/CardanoNode.hs @@ -90,6 +90,7 @@ data CardanoNodeArgs = CardanoNodeArgs , nodeByronGenesisFile :: FilePath , nodeShelleyGenesisFile :: FilePath , nodeAlonzoGenesisFile :: FilePath + , nodeConwayGenesisFile :: FilePath , nodeTopologyFile :: FilePath , nodeDatabaseDir :: FilePath , nodeDlgCertFile :: Maybe FilePath @@ -108,6 +109,7 @@ defaultCardanoNodeArgs = , nodeByronGenesisFile = "genesis-byron.json" , nodeShelleyGenesisFile = "genesis-shelley.json" , nodeAlonzoGenesisFile = "genesis-alonzo.json" + , nodeConwayGenesisFile = "genesis-conway.json" , nodeTopologyFile = "topology.json" , nodeDatabaseDir = "db" , nodeDlgCertFile = Nothing @@ -320,6 +322,9 @@ withCardanoNodeDevnet tracer stateDirectory action = do readConfigFile ("devnet" "genesis-alonzo.json") >>= BS.writeFile (stateDirectory nodeAlonzoGenesisFile args) + readConfigFile ("devnet" "genesis-conway.json") + >>= BS.writeFile + (stateDirectory nodeConwayGenesisFile args) writeTopology peers args = Aeson.encodeFile (stateDirectory nodeTopologyFile args) $ @@ -354,6 +359,7 @@ refreshSystemStart stateDirectory args = do byronGenesisHash <- computeGenesisHash (stateDirectory nodeByronGenesisFile args) shelleyGenesisHash <- computeGenesisHash (stateDirectory nodeShelleyGenesisFile args) alonzoGenesisHash <- computeGenesisHash (stateDirectory nodeAlonzoGenesisFile args) + conwayGenesisHash <- computeGenesisHash (stateDirectory nodeConwayGenesisFile args) config <- unsafeDecodeJsonFile (stateDirectory nodeConfigFile args) @@ -362,6 +368,7 @@ refreshSystemStart stateDirectory args = do <&> addField "ShelleyGenesisFile" (nodeShelleyGenesisFile args) <&> addField "ShelleyGenesisHash" shelleyGenesisHash <&> addField "AlonzoGenesisHash" alonzoGenesisHash + <&> addField "ConwayGenesisHash" conwayGenesisHash Aeson.encodeFile (stateDirectory nodeConfigFile args) config diff --git a/src/devnet/lib/Convex/Devnet/Logging.hs b/src/devnet/lib/Convex/Devnet/Logging.hs index 26d8966e..096ef75c 100644 --- a/src/devnet/lib/Convex/Devnet/Logging.hs +++ b/src/devnet/lib/Convex/Devnet/Logging.hs @@ -33,15 +33,15 @@ module Convex.Devnet.Logging ( import Cardano.BM.Tracing (ToObject (..), TracingVerbosity (..)) +import Control.Concurrent.STM.TBQueue (flushTBQueue, newTBQueueIO, + readTBQueue, writeTBQueue) +import Control.Concurrent.STM.TVar (TVar, modifyTVar, newTVarIO, + readTVarIO) import Control.Monad (forM_, forever, (>=>)) import Control.Monad.Class.MonadAsync (withAsync) import Control.Monad.Class.MonadFork (MonadFork, myThreadId) import Control.Monad.Class.MonadSay (MonadSay, say) -import Control.Monad.Class.MonadSTM (MonadSTM, TVar, atomically, - flushTBQueue, modifyTVar, - newTBQueueIO, newTVarIO, - readTBQueue, readTVarIO, - writeTBQueue) +import Control.Monad.Class.MonadSTM (MonadSTM, atomically) import Control.Monad.Class.MonadThrow (MonadCatch, finally, onException) import Control.Monad.Class.MonadTime (MonadTime, getCurrentTime) @@ -113,7 +113,7 @@ withTracerOutputTo :: (Tracer m msg -> IO a) -> IO a withTracerOutputTo hdl namespace action = do - msgQueue <- newTBQueueIO @_ @(Envelope msg) defaultQueueSize + msgQueue <- liftIO (newTBQueueIO @(Envelope msg) defaultQueueSize) withAsync (writeLogs msgQueue) $ \_ -> action (tracer msgQueue) `finally` flushLogs msgQueue where @@ -137,21 +137,21 @@ withTracerOutputTo hdl namespace action = do -- given 'action'. This tracer is wrapping 'msg' into an 'Envelope' with -- metadata. showLogsOnFailure :: - (MonadSTM m, MonadCatch m, MonadFork m, MonadTime m, MonadSay m, ToJSON msg) => + (MonadSTM m, MonadCatch m, MonadIO m, MonadFork m, MonadTime m, MonadSay m, ToJSON msg) => (Tracer m msg -> m a) -> m a showLogsOnFailure action = do - tvar <- newTVarIO [] + tvar <- liftIO (newTVarIO []) action (traceInTVar tvar) - `onException` (readTVarIO tvar >>= mapM_ (say . TL.unpack . decodeUtf8 . Aeson.encode) . reverse) + `onException` (liftIO (readTVarIO tvar) >>= mapM_ (say . TL.unpack . decodeUtf8 . Aeson.encode) . reverse) traceInTVar :: - (MonadFork m, MonadTime m, MonadSTM m) => - TVar m [Envelope msg] -> + (MonadIO m, MonadTime m, MonadFork m) => + TVar [Envelope msg] -> Tracer m msg traceInTVar tvar = Tracer $ \msg -> do envelope <- mkEnvelope "" msg - atomically $ modifyTVar tvar (envelope :) + liftIO $ atomically $ modifyTVar tvar (envelope :) -- * Internal functions mkEnvelope :: (MonadFork m, MonadTime m) => Text -> msg -> m (Envelope msg) diff --git a/src/devnet/lib/Convex/Devnet/NodeQueries.hs b/src/devnet/lib/Convex/Devnet/NodeQueries.hs index 8713d45c..7cfa45ca 100644 --- a/src/devnet/lib/Convex/Devnet/NodeQueries.hs +++ b/src/devnet/lib/Convex/Devnet/NodeQueries.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE GADTs #-} -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE ViewPatterns #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE NamedFieldPuns #-} +{-# LANGUAGE ViewPatterns #-} {-| Helper functions for querying a local @cardano-node@ using the socket interface -} module Convex.Devnet.NodeQueries( @@ -22,6 +23,7 @@ import Cardano.Api (Address, BlockNo, CardanoMode, EraHistory (..), + LocalNodeConnectInfo (..), NetworkId, QueryInMode, ShelleyAddr, @@ -83,7 +85,12 @@ queryLocalState query networkId socket = do localNodeConnectInfo :: NetworkId -> FilePath -> C.LocalNodeConnectInfo C.CardanoMode -localNodeConnectInfo = C.LocalNodeConnectInfo cardanoModeParams +localNodeConnectInfo localNodeNetworkId (C.File -> localNodeSocketPath) = + C.LocalNodeConnectInfo + { localConsensusModeParams = cardanoModeParams + , localNodeNetworkId + , localNodeSocketPath + } cardanoModeParams :: C.ConsensusModeParams C.CardanoMode cardanoModeParams = C.CardanoModeParams $ C.EpochSlots defaultByronEpochSlots diff --git a/src/devnet/lib/Convex/Devnet/Utils.hs b/src/devnet/lib/Convex/Devnet/Utils.hs index 29b19cc8..1b140147 100644 --- a/src/devnet/lib/Convex/Devnet/Utils.hs +++ b/src/devnet/lib/Convex/Devnet/Utils.hs @@ -17,7 +17,7 @@ import Cardano.Api (AsType, NetworkId, PaymentKey, import qualified Cardano.Api as C import Control.Exception (catch, onException) import Control.Monad.Class.MonadThrow (MonadThrow, throwIO) -import Control.Monad.Class.MonadTimer (DiffTime, MonadTimer, timeout) +import Control.Monad.Class.MonadTimer.SI (DiffTime, MonadTimer, timeout) import Control.Monad.IO.Class (MonadIO (..)) import qualified Data.Aeson as Aeson import Data.Bifunctor (Bifunctor (..)) diff --git a/src/devnet/test/Spec.hs b/src/devnet/test/Spec.hs index 7218e469..81b70fbf 100644 --- a/src/devnet/test/Spec.hs +++ b/src/devnet/test/Spec.hs @@ -35,7 +35,7 @@ main = do checkCardanoNode :: IO () checkCardanoNode = - let expectedVersion = "1.35.4" + let expectedVersion = "8.1.1" in getCardanoNodeVersion >>= assertBool ("cardano-node version should be " <> expectedVersion) . isInfixOf expectedVersion startLocalNode :: IO () diff --git a/src/mockchain/convex-mockchain.cabal b/src/mockchain/convex-mockchain.cabal index 762d2de4..f5c1017d 100644 --- a/src/mockchain/convex-mockchain.cabal +++ b/src/mockchain/convex-mockchain.cabal @@ -40,22 +40,22 @@ library lens, containers, time, - array, data-default, mtl, - strict-containers, HUnit, bytestring -- cardano dependencies build-depends: cardano-api, + cardano-ledger-babbage, cardano-slotting -any, + cardano-ledger-binary, ouroboros-consensus -any, + ouroboros-consensus-cardano -any, cardano-ledger-core -any, cardano-ledger-shelley -any, + cardano-ledger-alonzo -any, cardano-ledger-babbage -any, plutus-core -any, plutus-ledger-api -any, - cardano-ledger-alonzo -any, - cardano-ledger-shelley-ma -any diff --git a/src/mockchain/lib/Convex/MockChain.hs b/src/mockchain/lib/Convex/MockChain.hs index 175b36ec..58822175 100644 --- a/src/mockchain/lib/Convex/MockChain.hs +++ b/src/mockchain/lib/Convex/MockChain.hs @@ -1,6 +1,7 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE DerivingStrategies #-} {-# LANGUAGE GADTs #-} +{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeApplications #-} @@ -53,49 +54,34 @@ import Cardano.Api.Shelley (AddressInEra, ShelleyLedgerEra, SlotNo) import qualified Cardano.Api.Shelley as Cardano.Api -import Cardano.Ledger.Alonzo.Data (Data) -import qualified Cardano.Ledger.Alonzo.Data as Ledger import Cardano.Ledger.Alonzo.Language (Language (..)) import Cardano.Ledger.Alonzo.PlutusScriptApi (CollectError, collectTwoPhaseScriptInputs, evalScripts) -import Cardano.Ledger.Alonzo.Scripts (CostModel, CostModels, - ExUnits, Script, - unCostModels) -import Cardano.Ledger.Alonzo.Tools (TransactionScriptFailure) -import qualified Cardano.Ledger.Alonzo.Tools -import Cardano.Ledger.Alonzo.Tx (ValidatedTx (..)) -import Cardano.Ledger.Alonzo.TxInfo (ExtendedUTxO, - ScriptResult (..), - TranslationError) +import Cardano.Ledger.Alonzo.Scripts (CostModel, ExUnits) +import Cardano.Ledger.Alonzo.Scripts.Data (Data) +import qualified Cardano.Ledger.Alonzo.Scripts.Data as Ledger +import Cardano.Ledger.Alonzo.TxInfo (ScriptResult (..)) import qualified Cardano.Ledger.Alonzo.TxInfo as Ledger -import Cardano.Ledger.Alonzo.TxWitness (RdmrPtr) -import qualified Cardano.Ledger.Alonzo.TxWitness as Alonzo -import Cardano.Ledger.Babbage.PParams (PParams' (..)) -import Cardano.Ledger.Babbage.Tx (IsValid (..)) +import Cardano.Ledger.Babbage (Babbage) +import Cardano.Ledger.Babbage.Tx (AlonzoTx (..), + IsValid (..)) import Cardano.Ledger.BaseTypes (Globals (systemStart), ProtVer, epochInfo) import qualified Cardano.Ledger.Core as Core import Cardano.Ledger.Crypto (StandardCrypto) -import Cardano.Ledger.Era (Crypto, Era, - ValidateScript) import Cardano.Ledger.Shelley.API (AccountState (..), ApplyTxError, Coin (..), GenDelegs (..), LedgerEnv (..), MempoolEnv, - MempoolState, TxIn, - UTxO (..), UtxoEnv (..), - Validated, + MempoolState, UTxO (..), + UtxoEnv (..), Validated, initialFundsPseudoTxIn) import qualified Cardano.Ledger.Shelley.API -import Cardano.Ledger.Shelley.Constraints (UsesTxOut (..)) -import Cardano.Ledger.Shelley.LedgerState (DPState (..), - LedgerState (..), +import Cardano.Ledger.Shelley.LedgerState (LedgerState (..), UTxOState (..), smartUTxOState) -import Cardano.Ledger.Shelley.TxBody (DCert, Wdrl) -import Cardano.Ledger.ShelleyMA.Timelocks (ValidityInterval) import qualified Cardano.Ledger.Val as Val import Control.Lens (_1, over, set, to, view, (&), (.~), (^.)) @@ -121,19 +107,15 @@ import Convex.Utxos (UtxoSet (..), onlyCredential) import Convex.Wallet (Wallet, addressInEra, paymentCredential) -import Data.Array (array) import Data.Bifunctor (Bifunctor (..)) import Data.ByteString.Short (ShortByteString) import Data.Default (Default (def)) import Data.Functor.Identity (Identity (..)) import qualified Data.Map as Map -import Data.Proxy (Proxy (..)) -import Data.Sequence.Strict (StrictSeq) -import Data.Set (Set) -import GHC.Records (HasField (..)) -import Plutus.ApiCommon (mkTermToEvaluate) -import qualified Plutus.ApiCommon as Plutus +import Ouroboros.Consensus.Shelley.Eras (EraCrypto) import qualified PlutusCore as PLC +import PlutusLedgerApi.Common (mkTermToEvaluate) +import qualified PlutusLedgerApi.Common as Plutus import qualified UntypedPlutusCore as UPLC {-| All the information needed to evaluate a Plutus script: The script itself, the @@ -141,23 +123,19 @@ script language, redeemers and datums, execution units required, and the cost mo -} type ScriptContext era = (ShortByteString, Language, [Data era], ExUnits, CostModel) - -- let pv = Ledger.transProtocolVersion (_protocolVersion pp) - -- pArgs = Ledger.getPlutusData <$> arguments - -- appliedTerm <- left show $ mkTermToEvaluate Plutus.PlutusV2 pv script pArgs - -- pure $ UPLC.Program () (PLC.defaultVersion ()) appliedTerm - {-| Apply the plutus script to all its arguments and return a plutus program -} fullyAppliedScript :: NodeParams -> ScriptContext ERA -> Either String (UPLC.Program UPLC.NamedDeBruijn UPLC.DefaultUni UPLC.DefaultFun ()) fullyAppliedScript params (script, lang, arguments, _, _) = do - let pv = Ledger.transProtocolVersion (_protocolVersion $ Defaults.pParams params) + let pv = Ledger.transProtocolVersion (Defaults.protVer params) pArgs = Ledger.getPlutusData <$> arguments lng = case lang of PlutusV1 -> Plutus.PlutusV1 PlutusV2 -> Plutus.PlutusV2 + PlutusV3 -> Plutus.PlutusV3 appliedTerm <- first show $ mkTermToEvaluate lng pv script pArgs - pure $ UPLC.Program () (PLC.defaultVersion ()) appliedTerm + pure $ UPLC.Program () PLC.latestVersion appliedTerm data MockChainState = MockChainState @@ -177,7 +155,7 @@ initialState params = initialStateFor params [] genesisUTxO :: forall era capiEra. - (Era era, UsesTxOut era, Crypto era ~ StandardCrypto) => + (EraCrypto era ~ StandardCrypto, Core.EraTxOut era) => [(AddressInEra capiEra, Coin)] -> UTxO era genesisUTxO utxos = @@ -186,7 +164,7 @@ genesisUTxO utxos = [ (txIn, txOut) | (Cardano.Api.toShelleyAddr -> addr, amount) <- utxos, let txIn = initialFundsPseudoTxIn addr - txOut = makeTxOut (Proxy @era) addr (Val.inject amount) + txOut = Core.mkBasicTxOut addr (Val.inject amount) ] type InitialUTXOs = [(Wallet, Coin)] @@ -208,27 +186,27 @@ initialStateFor params@NodeParams{npNetworkId} utxos = , ledgerAccount = AccountState (Coin 0) (Coin 0) } , mcsPoolState = LedgerState - { lsUTxOState = smartUTxOState utxo (Coin 0) (Coin 0) def - , lsDPState = DPState def def + { lsUTxOState = smartUTxOState (Defaults.pParams params) utxo (Coin 0) (Coin 0) def + , lsCertState = def } , mcsTransactions = [] } utxoEnv :: NodeParams -> SlotNo -> UtxoEnv ERA -utxoEnv params slotNo = UtxoEnv slotNo (Defaults.pParams params) mempty (GenDelegs mempty) +utxoEnv params slotNo = UtxoEnv slotNo (Defaults.pParams params) def (GenDelegs mempty) data ExUnitsError = - Phase1Error (TranslationError StandardCrypto) - | Phase2Error (TransactionScriptFailure StandardCrypto) - deriving (Eq, Show) + Phase1Error Cardano.Api.TransactionValidityError + | Phase2Error Cardano.Api.ScriptExecutionError + deriving (Show) makePrisms ''ExUnitsError data ValidationError = VExUnits ExUnitsError - | PredicateFailures [CollectError (Crypto ERA)] + | PredicateFailures [CollectError ERA] | ApplyTxFailure (ApplyTxError ERA) - deriving (Eq, Show) + deriving (Show) makePrisms ''ValidationError @@ -238,24 +216,18 @@ getTxExUnits :: NodeParams -> UTxO ERA -> Cardano.Api.Tx Cardano.Api.BabbageEra -> - Either ExUnitsError (Map.Map RdmrPtr ExUnits) -getTxExUnits nodeParams utxo (Cardano.Api.ShelleyTx _ tx) = - let pParams = Defaults.pParams nodeParams - globals = Defaults.globals nodeParams - ei = epochInfo globals - ss = systemStart globals - costmdls = array (minBound, maxBound) . Map.toList $ unCostModels $ getField @"_costmdls" pParams - in - case Cardano.Ledger.Alonzo.Tools.evaluateTransactionExecutionUnits pParams tx utxo ei ss costmdls of - Left e -> Left (Phase1Error e) - Right rdmrs -> traverse (either (Left . Phase2Error) Right) rdmrs + Either ExUnitsError (Map.Map Cardano.Api.ScriptWitnessIndex Cardano.Api.ExecutionUnits) +getTxExUnits NodeParams{npSystemStart, npEraHistory, npProtocolParameters} utxo (Cardano.Api.getTxBody -> tx) = + case Cardano.Api.evaluateTransactionExecutionUnits npSystemStart (Cardano.Api.toLedgerEpochInfo npEraHistory) npProtocolParameters (fromLedgerUTxO Cardano.Api.ShelleyBasedEraBabbage utxo) tx of + Left e -> Left (Phase1Error e) + Right rdmrs -> traverse (either (Left . Phase2Error) Right) rdmrs applyTransaction :: NodeParams -> MockChainState -> Cardano.Api.Tx Cardano.Api.BabbageEra -> Either ValidationError (MockChainState, Validated (Core.Tx ERA)) applyTransaction params state tx'@(Cardano.Api.ShelleyTx _era tx) = do let currentSlot = state ^. env . L.slot utxoState_ = state ^. poolState . L.utxoState - utxo = utxoState_ ^. L._UTxOState . _1 - (vtx, scripts) <- first PredicateFailures (constructValidated (Defaults.globals params) (utxoEnv params currentSlot) utxoState_ tx) + utxo = utxoState_ ^. L._UTxOState (unbundleLedgerShelleyBasedProtocolParams Cardano.Api.ShelleyBasedEraBabbage $ npProtocolParameters params) . _1 + (vtx, scripts) <- first PredicateFailures (constructValidated (Defaults.protVer params) (Defaults.globals params) (utxoEnv params currentSlot) utxoState_ tx) result <- applyTx params state vtx scripts -- Not sure if this step is needed. @@ -267,14 +239,14 @@ applyTransaction params state tx'@(Cardano.Api.ShelleyTx _era tx) = do -} evaluateTx :: NodeParams -> SlotNo -> UTxO ERA -> Cardano.Api.Tx Cardano.Api.BabbageEra -> Either ValidationError [ScriptContext ERA] evaluateTx params slotNo utxo (Cardano.Api.ShelleyTx _ tx) = do - (vtx, scripts) <- first PredicateFailures (constructValidated (Defaults.globals params) (utxoEnv params slotNo) (lsUTxOState (mcsPoolState state)) tx) + (vtx, scripts) <- first PredicateFailures (constructValidated (Defaults.protVer params) (Defaults.globals params) (utxoEnv params slotNo) (lsUTxOState (mcsPoolState state)) tx) _ <- applyTx params state vtx scripts pure scripts where state = initialState params & env . L.slot .~ slotNo - & poolState . L.utxoState . L._UTxOState . _1 .~ utxo + & poolState . L.utxoState . L._UTxOState (unbundleLedgerShelleyBasedProtocolParams Cardano.Api.ShelleyBasedEraBabbage $ npProtocolParameters params) . _1 .~ utxo -- | Construct a 'ValidatedTx' from a 'Core.Tx' by setting the `IsValid` -- flag. @@ -286,38 +258,29 @@ evaluateTx params slotNo utxo (Cardano.Api.ShelleyTx _ tx) = do -- Copied from cardano-ledger as it was removed there -- in https://github.com/input-output-hk/cardano-ledger/commit/721adb55b39885847562437a6fe7e998f8e48c03 constructValidated :: - forall era m. - ( MonadError [CollectError (Crypto era)] m, - Core.Script era ~ Script era, - Core.Witnesses era ~ Alonzo.TxWitness era, - ValidateScript era, - HasField "inputs" (Core.TxBody era) (Set (TxIn (Crypto era))), - HasField "certs" (Core.TxBody era) (StrictSeq (DCert (Crypto era))), - HasField "_costmdls" (Core.PParams era) CostModels, - HasField "_protocolVersion" (Core.PParams era) ProtVer, - HasField "wdrls" (Core.TxBody era) (Wdrl (Crypto era)), - HasField "vldt" (Core.TxBody era) ValidityInterval, - ExtendedUTxO era + forall m. + ( MonadError [CollectError Babbage] m ) => + ProtVer -> Globals -> - UtxoEnv era -> - UTxOState era -> - Core.Tx era -> - m (ValidatedTx era, [ScriptContext era]) -constructValidated globals (UtxoEnv _ pp _ _) st tx = + UtxoEnv Babbage -> + UTxOState Babbage -> + Core.Tx Babbage -> + m (AlonzoTx Babbage, [ScriptContext Babbage]) +constructValidated pv globals (UtxoEnv _ pp _ _) st tx = case collectTwoPhaseScriptInputs ei sysS pp tx utxo of Left errs -> throwError errs Right sLst -> - let scriptEvalResult = evalScripts @era (getField @"_protocolVersion" pp) tx sLst + let scriptEvalResult = evalScripts @Babbage pv tx sLst vTx = - ValidatedTx - (getField @"body" tx) - (getField @"wits" tx) + AlonzoTx + (body tx) + (wits tx) -- (getField @"wits" tx) (IsValid (lift scriptEvalResult)) - (getField @"auxiliaryData" tx) + (auxiliaryData tx) -- (getField @"auxiliaryData" tx) in pure (vTx, sLst) where - utxo = _utxo st + utxo = utxosUtxo st sysS = systemStart globals ei = epochInfo globals lift (Passes _) = True @@ -339,7 +302,7 @@ newtype MockchainT m a = MockchainT (ReaderT NodeParams (StateT MockChainState ( data MockchainError = MockchainValidationFailed ValidationError | FailWith String - deriving (Eq, Show) + deriving (Show) instance Monad m => MonadFail (MockchainT m) where fail = MockchainT . throwError . FailWith @@ -354,10 +317,11 @@ instance Monad m => MonadBlockchain (MockchainT m) where let Cardano.Api.Tx body _ = tx in put st' >> return (Cardano.Api.getTxId body) utxoByTxIn txIns = MockchainT $ do - Cardano.Api.UTxO mp <- gets (view $ poolState . L.utxoState . L._UTxOState . _1 . to (fromLedgerUTxO Cardano.Api.ShelleyBasedEraBabbage)) + nps <- ask + Cardano.Api.UTxO mp <- gets (view $ poolState . L.utxoState . L._UTxOState (Defaults.pParams nps) . _1 . to (fromLedgerUTxO Cardano.Api.ShelleyBasedEraBabbage)) let mp' = Map.restrictKeys mp txIns pure (Cardano.Api.UTxO mp') - queryProtocolParameters = MockchainT ((,) <$> asks npProtocolParameters <*> asks npLedgerParams) + queryProtocolParameters = MockchainT (asks npProtocolParameters) queryStakePools = MockchainT (asks npStakePools) networkId = MockchainT (asks npNetworkId) querySystemStart = MockchainT (asks npSystemStart) @@ -376,9 +340,10 @@ instance Monad m => MonadMockchain (MockchainT m) where modify (set (env . L.slot) s') pure a modifyUtxo f = MockchainT $ do - u <- gets (view $ poolState . L.utxoState . L._UTxOState . _1) + nps <- ask + u <- gets (view $ poolState . L.utxoState . L._UTxOState (Defaults.pParams nps) . _1) let (u', a) = f u - modify (set (poolState . L.utxoState . L._UTxOState . _1) u') + modify (set (poolState . L.utxoState . L._UTxOState (Defaults.pParams nps) . _1) u') pure a {-| All transaction outputs @@ -430,7 +395,7 @@ execMockchain0 dist action = execMockchain action Defaults.nodeParams (initialSt -- not exported by cardano-api 1.35.3 (though it seems like it's exported in 1.36) fromLedgerUTxO :: ShelleyLedgerEra era ~ ledgerera - => Crypto ledgerera ~ StandardCrypto + => EraCrypto ledgerera ~ StandardCrypto => Cardano.Api.ShelleyBasedEra era -> UTxO ledgerera -> Cardano.Api.UTxO era @@ -440,3 +405,16 @@ fromLedgerUTxO era (UTxO utxo) = . map (bimap Cardano.Api.fromShelleyTxIn (Cardano.Api.fromShelleyTxOut era)) . Map.toList $ utxo + +-- not exported by cardano-api +unbundleLedgerShelleyBasedProtocolParams + :: Cardano.Api.ShelleyBasedEra era + -> Cardano.Api.BundledProtocolParameters era + -> Core.PParams (ShelleyLedgerEra era) +unbundleLedgerShelleyBasedProtocolParams = \case + Cardano.Api.ShelleyBasedEraShelley -> \(Cardano.Api.BundleAsShelleyBasedProtocolParameters _ _ lpp) -> lpp + Cardano.Api.ShelleyBasedEraAllegra -> \(Cardano.Api.BundleAsShelleyBasedProtocolParameters _ _ lpp) -> lpp + Cardano.Api.ShelleyBasedEraMary -> \(Cardano.Api.BundleAsShelleyBasedProtocolParameters _ _ lpp) -> lpp + Cardano.Api.ShelleyBasedEraAlonzo -> \(Cardano.Api.BundleAsShelleyBasedProtocolParameters _ _ lpp) -> lpp + Cardano.Api.ShelleyBasedEraBabbage -> \(Cardano.Api.BundleAsShelleyBasedProtocolParameters _ _ lpp) -> lpp + Cardano.Api.ShelleyBasedEraConway -> \(Cardano.Api.BundleAsShelleyBasedProtocolParameters _ _ lpp) -> lpp diff --git a/src/mockchain/lib/Convex/MockChain/Defaults.hs b/src/mockchain/lib/Convex/MockChain/Defaults.hs index 278aaabf..52b77d30 100644 --- a/src/mockchain/lib/Convex/MockChain/Defaults.hs +++ b/src/mockchain/lib/Convex/MockChain/Defaults.hs @@ -5,57 +5,67 @@ module Convex.MockChain.Defaults( epochSize, slotLength, protocolParameters, + bundledProtocolParameters, ledgerProtocolParameters, networkId, systemStart, globals, genesisDefaultsFromParams, pParams, + protVer, nodeParams ) where -import Cardano.Api.Shelley (AnyPlutusScriptVersion (..), - CardanoMode, - ConsensusMode (..), - CostModel (..), - EpochNo (..), - EraHistory (EraHistory), - ExecutionUnitPrices (..), - ExecutionUnits (..), - Lovelace (..), - NetworkId (..), - NetworkMagic (..), - PlutusScriptVersion (..), - ProtocolParameters (..), - ShelleyBasedEra (..), - shelleyGenesisDefaults, - toLedgerPParams) -import Cardano.Ledger.Babbage.PParams (retractPP) -import Cardano.Ledger.Babbage.Translation (coinsPerUTxOWordToCoinsPerUTxOByte) -import Cardano.Ledger.BaseTypes (boundRational) -import Cardano.Ledger.Core (PParams) -import Cardano.Ledger.Shelley.API (Coin (..), Globals, - ShelleyGenesis (..), - mkShelleyGlobals) -import qualified Cardano.Ledger.Shelley.API as C.Ledger -import Cardano.Ledger.Slot (EpochSize (..)) -import Cardano.Slotting.EpochInfo (fixedEpochInfo) -import Cardano.Slotting.Time (SlotLength, - SystemStart (..), - mkSlotLength) -import Convex.Era (ERA) -import Convex.NodeParams (NodeParams (..)) -import Data.Map (fromList) -import Data.Maybe (fromMaybe) -import Data.Ratio ((%)) -import Data.SOP.Strict (K (K), NP (..)) -import Data.Time.Calendar (fromGregorian) -import Data.Time.Clock (UTCTime (..)) -import qualified Ouroboros.Consensus.HardFork.History as Ouroboros -import qualified Ouroboros.Consensus.Util.Counting as Ouroboros -import PlutusCore (defaultCostModelParams) - -type MockchainEra = ERA +import qualified Cardano.Api as C +import Cardano.Api.Shelley (AnyPlutusScriptVersion (..), + CardanoMode, + ConsensusMode (..), + EpochNo (..), + EraHistory (EraHistory), + ExecutionUnitPrices (..), + ExecutionUnits (..), + Lovelace (..), + NetworkId (..), + NetworkMagic (..), + PlutusScriptVersion (..), + ProtocolParameters (..), + ShelleyBasedEra (..), + shelleyGenesisDefaults, + toLedgerPParams) +import Cardano.Ledger.Alonzo.PParams (DowngradeAlonzoPParams (..)) +import Cardano.Ledger.Babbage (Babbage) +import Cardano.Ledger.Babbage.Core (CoinPerByte (..), + CoinPerWord (..)) +import Cardano.Ledger.Babbage.PParams (DowngradeBabbagePParams (..), + coinsPerUTxOWordToCoinsPerUTxOByte) +import Cardano.Ledger.BaseTypes (ProtVer, + boundRational) +import qualified Cardano.Ledger.Binary.Version as Version +import Cardano.Ledger.Core (PParams, + downgradePParams) +import Cardano.Ledger.Crypto (StandardCrypto) +import Cardano.Ledger.Shelley.API (Coin (..), + Globals, + ShelleyGenesis (..), + mkShelleyGlobals) +import qualified Cardano.Ledger.Shelley.API as C.Ledger +import Cardano.Ledger.Slot (EpochSize (..)) +import Cardano.Slotting.EpochInfo (fixedEpochInfo) +import Cardano.Slotting.Time (SlotLength, + SystemStart (..), + mkSlotLength) +import Convex.NodeParams (NodeParams (..)) +import Data.Map (fromList) +import Data.Maybe (fromMaybe) +import Data.Ratio ((%)) +import Data.SOP.Counting (Exactly (..), + nonEmptyHead) +import Data.SOP.Strict (K (K), + NP (..)) +import Data.Time.Calendar (fromGregorian) +import Data.Time.Clock (UTCTime (..)) +import qualified Ouroboros.Consensus.HardFork.History as Ouroboros +import Ouroboros.Consensus.Shelley.Eras (StandardBabbage) networkId :: NetworkId networkId = Testnet (NetworkMagic 0) @@ -70,10 +80,10 @@ systemStart = SystemStart startTime eraHistory :: EraHistory CardanoMode eraHistory = - EraHistory CardanoMode (Ouroboros.mkInterpreter $ Ouroboros.summaryWithExactly list) + EraHistory CardanoMode (Ouroboros.mkInterpreter $ Ouroboros.summaryWithExactly list) -- $ Ouroboros.summaryWithExactly list) where - one = Ouroboros.nonEmptyHead $ Ouroboros.getSummary $ Ouroboros.neverForksSummary epochSize slotLength - list = Ouroboros.Exactly $ K one :* K one :* K one :* K one :* K one :* K one :* Nil + one = nonEmptyHead $ Ouroboros.getSummary $ Ouroboros.neverForksSummary epochSize slotLength + list = Exactly $ K one :* K one :* K one :* K one :* K one :* K one :* K one :* Nil -- | A sensible default 'EpochSize' value for the emulator epochSize :: EpochSize @@ -85,61 +95,107 @@ slotLength = mkSlotLength 1_000 -- 1 second protocolParameters :: ProtocolParameters protocolParameters = - ProtocolParameters - { protocolParamProtocolVersion = (6,0) - , protocolParamDecentralization = Just (3 % 5) - , protocolParamExtraPraosEntropy = Nothing - , protocolParamMaxBlockHeaderSize = 1_100 - , protocolParamMaxBlockBodySize = 65_536 - , protocolParamMaxTxSize = 16_384 - , protocolParamTxFeeFixed = 155_381 - , protocolParamTxFeePerByte = 44 - , protocolParamMinUTxOValue = Just (Lovelace 1_500_000) - , protocolParamStakeAddressDeposit = Lovelace 2_000_000 - , protocolParamStakePoolDeposit = Lovelace 500_000_000 - , protocolParamMinPoolCost = Lovelace 340_000_000 - , protocolParamPoolRetireMaxEpoch = EpochNo 18 - , protocolParamStakePoolTargetNum = 150 - , protocolParamPoolPledgeInfluence = 3 % 10 - , protocolParamMonetaryExpansion = 3 % 1_000 - , protocolParamTreasuryCut = 1 % 5 - , protocolParamUTxOCostPerWord = Nothing -- Obsolete from babbage onwards - , protocolParamCostModels = fromList - [ (AnyPlutusScriptVersion PlutusScriptV1, CostModel $ fromMaybe (error "Ledger.Params: defaultCostModelParams is broken") defaultCostModelParams) - , (AnyPlutusScriptVersion PlutusScriptV2, CostModel $ fromMaybe (error "Ledger.Params: defaultCostModelParams is broken") defaultCostModelParams) ] - , protocolParamPrices = Just (ExecutionUnitPrices {priceExecutionSteps = 721 % 10_000_000, priceExecutionMemory = 577 % 10_000}) - , protocolParamMaxTxExUnits = Just (ExecutionUnits {executionSteps = 1_0000_000_000, executionMemory = 16_000_000}) - , protocolParamMaxBlockExUnits = Just (ExecutionUnits {executionSteps = 4_0000_000_000, executionMemory = 80_000_000}) - , protocolParamMaxValueSize = Just 5_000 - , protocolParamCollateralPercent = Just 150 - , protocolParamMaxCollateralInputs = Just 3 - , protocolParamUTxOCostPerByte = - let (Coin coinsPerUTxOByte) = coinsPerUTxOWordToCoinsPerUTxOByte $ Coin 34_482 - in Just $ Lovelace coinsPerUTxOByte - } -ledgerProtocolParameters :: PParams MockchainEra -ledgerProtocolParameters = toLedgerPParams ShelleyBasedEraBabbage protocolParameters + -- cost models from https://github.com/input-output-hk/cardano-node/blob/master/cardano-testnet/src/Testnet/Defaults.hs + let defaultV1CostModel = C.CostModel + [ 205665, 812, 1, 1, 1000, 571, 0, 1, 1000, 24177, 4, 1, 1000, 32, 117366, 10475, 4 + , 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 100, 100 + , 23000, 100, 19537, 32, 175354, 32, 46417, 4, 221973, 511, 0, 1, 89141, 32, 497525 + , 14068, 4, 2, 196500, 453240, 220, 0, 1, 1, 1000, 28662, 4, 2, 245000, 216773, 62 + , 1, 1060367, 12586, 1, 208512, 421, 1, 187000, 1000, 52998, 1, 80436, 32, 43249, 32 + , 1000, 32, 80556, 1, 57667, 4, 1000, 10, 197145, 156, 1, 197145, 156, 1, 204924, 473 + , 1, 208896, 511, 1, 52467, 32, 64832, 32, 65493, 32, 22558, 32, 16563, 32, 76511, 32 + , 196500, 453240, 220, 0, 1, 1, 69522, 11687, 0, 1, 60091, 32, 196500, 453240, 220, 0 + , 1, 1, 196500, 453240, 220, 0, 1, 1, 806990, 30482, 4, 1927926, 82523, 4, 265318, 0 + , 4, 0, 85931, 32, 205665, 812, 1, 1, 41182, 32, 212342, 32, 31220, 32, 32696, 32, 43357 + , 32, 32247, 32, 38314, 32, 57996947, 18975, 10 + ] + defaultV2CostModel = C.CostModel + [ 205665, 812, 1, 1, 1000, 571, 0, 1, 1000, 24177, 4, 1, 1000, 32, 117366, 10475, 4 + , 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 23000, 100, 100, 100 + , 23000, 100, 19537, 32, 175354, 32, 46417, 4, 221973, 511, 0, 1, 89141, 32, 497525 + , 14068, 4, 2, 196500, 453240, 220, 0, 1, 1, 1000, 28662, 4, 2, 245000, 216773, 62 + , 1, 1060367, 12586, 1, 208512, 421, 1, 187000, 1000, 52998, 1, 80436, 32, 43249, 32 + , 1000, 32, 80556, 1, 57667, 4, 1000, 10, 197145, 156, 1, 197145, 156, 1, 204924, 473 + , 1, 208896, 511, 1, 52467, 32, 64832, 32, 65493, 32, 22558, 32, 16563, 32, 76511, 32 + , 196500, 453240, 220, 0, 1, 1, 69522, 11687, 0, 1, 60091, 32, 196500, 453240, 220, 0 + , 1, 1, 196500, 453240, 220, 0, 1, 1, 1159724, 392670, 0, 2, 806990, 30482, 4, 1927926 + , 82523, 4, 265318, 0, 4, 0, 85931, 32, 205665, 812, 1, 1, 41182, 32, 212342, 32, 31220 + , 32, 32696, 32, 43357, 32, 32247, 32, 38314, 32, 35892428, 10, 9462713, 1021, 10, 38887044 + , 32947, 10 + ] + + in ProtocolParameters + { protocolParamProtocolVersion = (7,0) + , protocolParamDecentralization = Just (3 % 5) + , protocolParamExtraPraosEntropy = Nothing + , protocolParamMaxBlockHeaderSize = 1_100 + , protocolParamMaxBlockBodySize = 65_536 + , protocolParamMaxTxSize = 16_384 + , protocolParamTxFeeFixed = 155_381 + , protocolParamTxFeePerByte = 44 + , protocolParamMinUTxOValue = Just (Lovelace 1_500_000) + , protocolParamStakeAddressDeposit = Lovelace 2_000_000 + , protocolParamStakePoolDeposit = Lovelace 500_000_000 + , protocolParamMinPoolCost = Lovelace 340_000_000 + , protocolParamPoolRetireMaxEpoch = EpochNo 18 + , protocolParamStakePoolTargetNum = 150 + , protocolParamPoolPledgeInfluence = 3 % 10 + , protocolParamMonetaryExpansion = 3 % 1_000 + , protocolParamTreasuryCut = 1 % 5 + , protocolParamUTxOCostPerWord = Nothing -- Obsolete from babbage onwards + , protocolParamCostModels = fromList + [ (AnyPlutusScriptVersion PlutusScriptV1, defaultV1CostModel) + , (AnyPlutusScriptVersion PlutusScriptV2, defaultV2CostModel) ] + , protocolParamPrices = Just (ExecutionUnitPrices {priceExecutionSteps = 721 % 10_000_000, priceExecutionMemory = 577 % 10_000}) + , protocolParamMaxTxExUnits = Just (ExecutionUnits {executionSteps = 1_0000_000_000, executionMemory = 16_000_000}) + , protocolParamMaxBlockExUnits = Just (ExecutionUnits {executionSteps = 4_0000_000_000, executionMemory = 80_000_000}) + , protocolParamMaxValueSize = Just 5_000 + , protocolParamCollateralPercent = Just 150 + , protocolParamMaxCollateralInputs = Just 3 + , protocolParamUTxOCostPerByte = + let (CoinPerByte (Coin coinsPerUTxOByte)) = coinsPerUTxOWordToCoinsPerUTxOByte $ CoinPerWord $ Coin 34_482 + in Just $ Lovelace coinsPerUTxOByte + } + +ledgerProtocolParameters :: PParams StandardBabbage +ledgerProtocolParameters = + either (error . (<>) "ledgerProtocolParameters: toLedgerPParams failed with " . show) id $ toLedgerPParams ShelleyBasedEraBabbage protocolParameters globals :: NodeParams -> Globals globals params@NodeParams { npProtocolParameters, npSlotLength } = mkShelleyGlobals (genesisDefaultsFromParams params) (fixedEpochInfo epochSize npSlotLength) - (fst $ protocolParamProtocolVersion npProtocolParameters) + (fromMaybe (error "globals: Invalid version") $ Version.mkVersion $ fst $ protocolParamProtocolVersion $ C.unbundleProtocolParams npProtocolParameters) -genesisDefaultsFromParams :: NodeParams -> ShelleyGenesis MockchainEra +protVer :: NodeParams -> ProtVer +protVer = lederPPProtVer . C.unbundleProtocolParams . npProtocolParameters + +lederPPProtVer :: ProtocolParameters -> ProtVer +lederPPProtVer k = + let (majorProtVer, minorProtVer) = protocolParamProtocolVersion k + in fromMaybe (error $ "globals: Invalid major protocol version: " <> show majorProtVer) $ + (`C.Ledger.ProtVer` minorProtVer) <$> Version.mkVersion majorProtVer + +genesisDefaultsFromParams :: NodeParams -> ShelleyGenesis StandardCrypto genesisDefaultsFromParams params@NodeParams { npNetworkId } = shelleyGenesisDefaults { sgSystemStart = startTime , sgNetworkMagic = case npNetworkId of Testnet (NetworkMagic nm) -> nm; _ -> 0 , sgNetworkId = case npNetworkId of Testnet _ -> C.Ledger.Testnet; Mainnet -> C.Ledger.Mainnet - , sgProtocolParams = retractPP (Coin 0) d C.Ledger.NeutralNonce $ pParams params + , sgProtocolParams = + downgradePParams () + $ downgradePParams () + $ downgradePParams DowngradeAlonzoPParams{dappMinUTxOValue=Coin 0} + $ downgradePParams DowngradeBabbagePParams{dbppD=d, dbppExtraEntropy=C.Ledger.NeutralNonce} + $ pParams params } where d = fromMaybe (error "3 % 5 should be valid UnitInterval") $ boundRational (3 % 5) -- | Convert `Params` to cardano-ledger `PParams` -pParams :: NodeParams -> PParams MockchainEra -pParams NodeParams { npLedgerParams } = npLedgerParams +pParams :: NodeParams -> PParams Babbage +pParams NodeParams { npProtocolParameters } = case npProtocolParameters of + C.BundleAsShelleyBasedProtocolParameters _ _ p -> p {-| 'NodeParams' with default values for testing -} @@ -147,10 +203,12 @@ nodeParams :: NodeParams nodeParams = NodeParams { npNetworkId = networkId - , npProtocolParameters = protocolParameters - , npLedgerParams = ledgerProtocolParameters + , npProtocolParameters = bundledProtocolParameters , npSystemStart = systemStart , npEraHistory = eraHistory , npStakePools = mempty , npSlotLength = slotLength } + +bundledProtocolParameters :: C.BundledProtocolParameters C.BabbageEra +bundledProtocolParameters = either (error . (<>) "nodeParams: bundleProtocolParams failed: " . show) id (C.bundleProtocolParams C.BabbageEra protocolParameters) diff --git a/src/mockchain/lib/Convex/NodeParams.hs b/src/mockchain/lib/Convex/NodeParams.hs index 179dac53..af0dfac4 100644 --- a/src/mockchain/lib/Convex/NodeParams.hs +++ b/src/mockchain/lib/Convex/NodeParams.hs @@ -4,27 +4,23 @@ module Convex.NodeParams( NodeParams(..), networkId, protocolParameters, - ledgerProtocolParameters, systemStart, eraHistory, stakePools, slotLength ) where -import Cardano.Api.Shelley (CardanoMode, EraHistory, - NetworkId (..), PoolId, - ProtocolParameters (..)) -import Cardano.Ledger.Babbage.PParams (PParams) -import Cardano.Slotting.Time (SlotLength, SystemStart) -import Control.Lens.TH (makeLensesFor) -import Convex.Era (ERA) -import Data.Set as Set (Set) +import Cardano.Api (BabbageEra, BundledProtocolParameters) +import Cardano.Api.Shelley (CardanoMode, EraHistory, NetworkId (..), + PoolId) +import Cardano.Slotting.Time (SlotLength, SystemStart) +import Control.Lens.TH (makeLensesFor) +import Data.Set as Set (Set) data NodeParams = NodeParams { npNetworkId :: NetworkId - , npProtocolParameters :: ProtocolParameters - , npLedgerParams :: PParams ERA + , npProtocolParameters :: BundledProtocolParameters BabbageEra , npSystemStart :: SystemStart , npEraHistory :: EraHistory CardanoMode , npStakePools :: Set PoolId @@ -38,5 +34,4 @@ makeLensesFor , ("npEraHistory", "eraHistory") , ("npStakePools", "stakePools") , ("npSlotLength", "slotLength") - , ("npLedgerParams", "ledgerProtocolParameters") ] ''NodeParams diff --git a/src/node-client/convex-node-client.cabal b/src/node-client/convex-node-client.cabal index 738d339e..6b5eec66 100644 --- a/src/node-client/convex-node-client.cabal +++ b/src/node-client/convex-node-client.cabal @@ -51,5 +51,6 @@ library cardano-slotting, ouroboros-consensus, ouroboros-network, + ouroboros-network-protocols, typed-protocols diff --git a/src/wallet/convex-wallet.cabal b/src/wallet/convex-wallet.cabal index 957d1506..41551566 100644 --- a/src/wallet/convex-wallet.cabal +++ b/src/wallet/convex-wallet.cabal @@ -62,7 +62,7 @@ executable convex-wallet import: lang main-is: Main.hs build-depends: - base ^>=4.14.3.0, + base >=4.14.3.0, convex-wallet hs-source-dirs: app default-language: Haskell2010