diff --git a/default.nix b/default.nix index 1681f61a3da..112838822d7 100644 --- a/default.nix +++ b/default.nix @@ -59,6 +59,7 @@ let core-to-plc = doHaddockHydra (addRealTimeTestLogs (filterSource super.core-to-plc)); plutus-th = doHaddockHydra (addRealTimeTestLogs (filterSource super.plutus-th)); plutus-use-cases = addRealTimeTestLogs (filterSource super.plutus-use-cases); + wallet-api = doHaddockHydra (addRealTimeTestLogs (filterSource super.wallet-api)); }; }; other = rec { diff --git a/pkgs/default.nix b/pkgs/default.nix index e26fc5ec28b..5df698bc880 100644 --- a/pkgs/default.nix +++ b/pkgs/default.nix @@ -78275,6 +78275,51 @@ homepage = "http://github.com/yesodweb/wai"; description = "Provide a bridge between WAI and the websockets package"; license = stdenv.lib.licenses.mit; +}) {}; +"wallet-api" = callPackage +({ + mkDerivation +, base +, bytestring +, containers +, free +, ghc +, language-plutus-core +, mmorph +, mtl +, operational +, plutus-th +, prettyprinter +, stdenv +, template-haskell +, text +, transformers +}: +mkDerivation { + +pname = "wallet-api"; +version = "0.1.0.0"; +src = ./../wallet-api; +libraryHaskellDepends = [ +base +bytestring +containers +free +ghc +language-plutus-core +mmorph +mtl +operational +plutus-th +prettyprinter +template-haskell +text +transformers +]; +doHaddock = false; +description = "Wallet API"; +license = stdenv.lib.licenses.bsd3; + }) {}; "warp" = callPackage ({ diff --git a/release.nix b/release.nix index 7401303b3ed..dcd7d56eed5 100644 --- a/release.nix +++ b/release.nix @@ -21,6 +21,7 @@ let core-to-plc = supportedSystems; plutus-th = supportedSystems; plutus-use-cases = supportedSystems; + wallet-api = supportedSystems; # don't need to build the spec on anything other than one platform plutus-core-spec = [ "x86_64-linux" ]; }; diff --git a/stack.yaml b/stack.yaml index 50cd57bc60b..037564646d0 100644 --- a/stack.yaml +++ b/stack.yaml @@ -8,6 +8,7 @@ packages: - core-to-plc - plutus-th - plutus-use-cases +- wallet-api - location: git: https://github.com/input-output-hk/cardano-crypto diff --git a/wallet-api/LICENSE b/wallet-api/LICENSE new file mode 100644 index 00000000000..a94365be350 --- /dev/null +++ b/wallet-api/LICENSE @@ -0,0 +1,11 @@ +Copyright Input Output (c) 2018 + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/wallet-api/README.md b/wallet-api/README.md new file mode 100644 index 00000000000..818dfb91193 --- /dev/null +++ b/wallet-api/README.md @@ -0,0 +1,3 @@ +## Wallet API + +This contains a draft of the Plutus wallet API and an emulator for testing contracts. diff --git a/wallet-api/shell.nix b/wallet-api/shell.nix new file mode 100644 index 00000000000..f94505abf88 --- /dev/null +++ b/wallet-api/shell.nix @@ -0,0 +1 @@ +(import ../. {}).wallet-api.env diff --git a/wallet-api/src/Wallet/Emulator/Types.hs b/wallet-api/src/Wallet/Emulator/Types.hs new file mode 100644 index 00000000000..2113872ed8c --- /dev/null +++ b/wallet-api/src/Wallet/Emulator/Types.hs @@ -0,0 +1,132 @@ +{-# LANGUAGE ConstraintKinds #-} +{-# LANGUAGE FlexibleContexts #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedStrings #-} +module Wallet.Emulator.Types where + +import Control.Monad.Except +import Control.Monad.Operational as Op +import Control.Monad.State +import Control.Monad.Writer +import Data.Map as Map +import Data.Maybe +import Data.Text as T + +-- Basic types (should be replaced by "real" types later) + +-- don’t care what these are, some data to allow typeclasses +data Tx = Tx Int + deriving (Show, Eq, Ord) +-- agents/wallets +data Wallet = Wallet Int + deriving (Show, Eq, Ord) + +type Block = [Tx] +type Chain = [Block] +type TxPool = [Tx] + +data Notification = BlockValidated Block + | BlockHeight Int + deriving (Show, Eq, Ord) + +-- Wallet code + +data WalletState = WalletState + deriving (Show, Eq, Ord) + +emptyWalletState :: WalletState +emptyWalletState = WalletState + +-- manually records the list of transactions to be submitted +newtype EmulatedWalletApi a = EmulatedWalletApi { runEmulatedWalletApi :: StateT WalletState (Writer [Tx]) a } + deriving (Functor, Applicative, Monad, MonadState WalletState, MonadWriter [Tx]) + +handleNotifications :: [Notification] -> EmulatedWalletApi () +handleNotifications = undefined -- TODO + +instance WalletAPI EmulatedWalletApi where + submitTxn txn = tell [txn] + +-- TODO: richer interface +class WalletAPI m where + submitTxn :: Tx -> m () + +-- Emulator code + +type Assertion = EmulatorState -> Maybe AssertionError +data AssertionError = AssertionError T.Text + deriving Show + +isValidated :: Tx -> Assertion +isValidated txn emState = + if notElem txn (join $ emChain emState) then Just $ AssertionError $ "Txn not validated: " <> T.pack (show txn) else Nothing + +-- | The type of events in the emulator. @n@ is the type (usually a monad) in which wallet actions +-- take place. +data Event n a where + -- | An direct action performed by a wallet. Usually represents a "user action", as it is + -- triggered externally. + WalletAction :: Wallet -> n () -> Event n [Tx] + -- | A wallet receiving some notifications, and reacting to them. + WalletRecvNotification :: Wallet -> [Notification] -> Event n [Tx] + -- | The blockchain performing actions, resulting in a validated block. + BlockchainActions :: Event n Block + -- | An assertion in the event stream, which can inspect the current state. + Assertion :: Assertion -> Event n () + +-- Program is like Free, except it makes the Functor for us so we can have a nice GADT +type Trace = Op.Program (Event EmulatedWalletApi) + +data EmulatorState = EmulatorState { emChain :: Chain, emTxPool :: TxPool, emWalletState :: Map Wallet WalletState } + deriving (Show, Eq, Ord) + +emptyEmulatorState :: EmulatorState +emptyEmulatorState = EmulatorState { emChain = [], emTxPool = [], emWalletState = Map.empty } + +type MonadEmulator m = (MonadState EmulatorState m, MonadError AssertionError m) + +-- TODO: actual validation +validate :: (MonadEmulator m) => Tx -> m (Maybe Tx) +validate txn = pure $ Just txn + +liftEmulatedWallet :: (MonadEmulator m) => Wallet -> EmulatedWalletApi a -> m ([Tx], a) +liftEmulatedWallet wallet act = do + emState <- get + let walletState = fromMaybe emptyWalletState $ Map.lookup wallet $ emWalletState emState + let ((out, newState), txns) = runWriter $ runStateT (runEmulatedWalletApi act) walletState + put emState { + emTxPool = txns ++ emTxPool emState, + emWalletState = Map.insert wallet newState $ emWalletState emState + } + pure (txns, out) + +eval :: (MonadEmulator m) => Event EmulatedWalletApi a -> m a +eval = \case + WalletAction wallet action -> fst <$> liftEmulatedWallet wallet action + WalletRecvNotification wallet trigger -> fst <$> liftEmulatedWallet wallet (handleNotifications trigger) + BlockchainActions -> do + emState <- get + processed <- forM (emTxPool emState) validate + let validated = catMaybes processed + let block = validated + put emState { + emChain = block : emChain emState + } + pure block + Assertion assertion -> do + s <- get + case assertion s of + Just err -> throwError err + Nothing -> pure () + +process :: (MonadState EmulatorState m, MonadError AssertionError m) => Trace a -> m a +process = interpretWithMonad eval + +-- Example + +trace :: Trace () +trace = do + [txn] <- Op.singleton $ WalletAction (Wallet 1) $ submitTxn (Tx 1) + _ <- Op.singleton $ BlockchainActions + Op.singleton $ Assertion $ isValidated txn diff --git a/wallet-api/wallet-api.cabal b/wallet-api/wallet-api.cabal new file mode 100644 index 00000000000..7bc7b7e9234 --- /dev/null +++ b/wallet-api/wallet-api.cabal @@ -0,0 +1,52 @@ +cabal-version: 1.18 +name: wallet-api +version: 0.1.0.0 +license: BSD3 +license-file: LICENSE +copyright: Copyright: (c) 2018 Input Output +maintainer: michael.peyton-jones@iohk.io +author: Michael Peyton Jones, Jann Mueller +synopsis: Wallet API +description: + Wallet API and emulator +category: Language +build-type: Simple +extra-doc-files: README.md + +source-repository head + type: git + location: https://github.com/input-output-hk/plutus-prototype + +library + exposed-modules: + Wallet.Emulator.Types + other-modules: + hs-source-dirs: src + default-language: Haskell2010 + default-extensions: ExplicitForAll ScopedTypeVariables + DeriveGeneric StandaloneDeriving DeriveLift + GeneralizedNewtypeDeriving DeriveFunctor DeriveFoldable + DeriveTraversable + other-extensions: DeriveAnyClass FlexibleContexts FlexibleInstances + MultiParamTypeClasses TypeFamilies OverloadedStrings + MonadComprehensions ConstrainedClassMethods TupleSections GADTs + RankNTypes TemplateHaskell QuasiQuotes TypeApplications + ExistentialQuantification + ghc-options: -Wall -Wnoncanonical-monad-instances + -Wincomplete-uni-patterns -Wincomplete-record-updates + -Wredundant-constraints -Widentities + build-depends: + base >=4.9 && <5, + ghc -any, + template-haskell -any, + language-plutus-core -any, + plutus-th -any, + containers -any, + free -any, + operational -any, + mtl -any, + transformers -any, + bytestring -any, + text -any, + prettyprinter -any, + mmorph -any