{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE NoFieldSelectors #-} {-# OPTIONS_GHC -Wno-x-unsafe-serialization #-} module Main (main) where import Control.Monad (foldM, guard) import Data.Bifunctor import qualified Data.ByteString as BS import qualified Data.ByteString.Builder as BSB import qualified Data.ByteString.Char8 as BSC import qualified Data.ByteString.Lazy as BSL import Data.Fixed import Data.Int (Int64) import qualified Data.Map.Strict as Map import Data.Maybe (isJust, isNothing) import Data.Monoid import Data.Word (Word64) import GHC.Generics import qualified Sel import qualified Sel.Hashing.SHA512 as Hash import qualified Sel.PublicKey.Signature as Sign import Test.Hspec main :: IO () main = Sel.secureMain $ hspec spec spec :: Spec spec = do let dummyTx s = Transaction (TxBody [] [] (Range (Just $ Slot s) Nothing)) [] Map.empty dummyTxId s = computeTxId (dummyTx s).txBody describe "Cryptography Helpers" $ do it "verifies a correctly signed transaction" $ do (pubKey, secKey) <- generateKeyPair let tx = dummyTx 0 txId = computeTxId tx.txBody sig <- signTx secKey tx.txBody verifySignature pubKey sig txId `shouldBe` True it "rejects a signature for a modified transaction ID" $ do (pubKey, secKey) <- generateKeyPair let tx1 = dummyTx 0 tx2 = dummyTx 1 txId2 = computeTxId tx2.txBody sig <- signTx secKey tx1.txBody verifySignature pubKey sig txId2 `shouldBe` False it "rejects a valid signature verified against the wrong public key" $ do (_pubKey1, secKey1) <- generateKeyPair (pubKey2, _secKey2) <- generateKeyPair let tx = dummyTx 0 txId = computeTxId tx.txBody sig <- signTx secKey1 tx.txBody verifySignature pubKey2 sig txId `shouldBe` False it "derives consistent addresses from public keys" $ do (pubKey, _) <- generateKeyPair deriveAddress pubKey `shouldBe` deriveAddress pubKey describe "Transaction Application (applyTx) - PKH Spends" $ do it "successfully applies a valid standard transaction" $ do (pubKey, secKey) <- generateKeyPair let addr = deriveAddress pubKey txIdOrigin = computeTxId $ TxBody [] [] rangeOpen outRef = TxOutRef txIdOrigin (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr (Ada 100) Nothing) txIn = TxIn outRef txOut = TxOut addr (Ada 100) Nothing txBodyNew = TxBody [txIn] [txOut] rangeOpen sig <- signTx secKey txBodyNew let tx = Transaction txBodyNew [] (Map.singleton outRef (UnlockBySignature pubKey sig)) applyTx (Env (Slot 0)) tx utxo `shouldSatisfy` isJust it "fails to apply a transaction with an invalid signature" $ do (pubKey1, _secKey1) <- generateKeyPair (_pubKey2, secKey2) <- generateKeyPair let addr1 = deriveAddress pubKey1 txIdOrigin = computeTxId $ TxBody [] [] rangeOpen outRef = TxOutRef txIdOrigin (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr1 (Ada 100) Nothing) txIn = TxIn outRef txOut = TxOut addr1 (Ada 100) Nothing txBodyNew = TxBody [txIn] [txOut] rangeOpen sig <- signTx secKey2 txBodyNew let tx = Transaction txBodyNew [] (Map.singleton outRef (UnlockBySignature pubKey1 sig)) applyTx (Env (Slot 0)) tx utxo `shouldSatisfy` isNothing describe "Transaction Application (applyTx) - Script Spends" $ do it "successfully unlocks a script output with the correct password" $ do let scriptAddr = Address $ Hash.hashByteString "dummy" -- Dummy script address txIdOrigin = computeTxId $ TxBody [] [] rangeOpen outRef = TxOutRef txIdOrigin (TxOutIdx 0) -- The output is locked with the hash of the password "secret" hashedPassword = Hash.hashByteString "secret" lockedDatum = DBytes (Hash.hashToBinary hashedPassword) utxo = UTxO $ Map.singleton outRef (TxOut scriptAddr (Ada 100) (Just lockedDatum)) -- The spender provides the plaintext password "secret" correctRedeemer = Redeemer (DBytes "secret") txIn = TxIn outRef txOut = TxOut scriptAddr (Ada 100) Nothing -- Sending it somewhere else tx = Transaction (TxBody [txIn] [txOut] rangeOpen) [] (Map.singleton outRef (UnlockByScript passwordValidator correctRedeemer)) applyTx (Env (Slot 0)) tx utxo `shouldSatisfy` isJust it "fails to unlock a script output with the wrong password" $ do let scriptAddr = Address $ Hash.hashByteString "dummy" txIdOrigin = computeTxId $ TxBody [] [] rangeOpen outRef = TxOutRef txIdOrigin (TxOutIdx 0) hashedPassword = Hash.hashByteString "secret" lockedDatum = DBytes (Hash.hashToBinary hashedPassword) utxo = UTxO $ Map.singleton outRef (TxOut scriptAddr (Ada 100) (Just lockedDatum)) -- The spender provides the wrong password wrongRedeemer = Redeemer (DBytes "wrong_password") txIn = TxIn outRef txOut = TxOut scriptAddr (Ada 100) Nothing tx = Transaction (TxBody [txIn] [txOut] rangeOpen) [] (Map.singleton outRef (UnlockByScript passwordValidator wrongRedeemer)) applyTx (Env (Slot 0)) tx utxo `shouldSatisfy` isNothing describe "Transaction Application (applyTx) - Beneficiary Script" $ do it "successfully unlocks when the designated beneficiary signs the transaction" $ do (beneficiaryPubKey, beneficiarySecKey) <- generateKeyPair let scriptAddr = Address $ Hash.hashByteString "vesting_script" txIdOrigin = computeTxId $ TxBody [] [] rangeOpen outRef = TxOutRef txIdOrigin (TxOutIdx 0) -- The Datum locks the output to the beneficiary's exact public key bytes beneficiaryBytes = Sign.publicKeyToBinary beneficiaryPubKey.unPublicKey lockedDatum = DBytes beneficiaryBytes utxo = UTxO $ Map.singleton outRef (TxOut scriptAddr (Ada 100) (Just lockedDatum)) -- The redeemer doesn't matter here, the context provides the proof txIn = TxIn outRef txOut = TxOut scriptAddr (Ada 100) Nothing txBodyNew = (TxBody [txIn] [txOut] rangeOpen) -- The beneficiary signs the transaction and attaches it to txSignatures sig <- signTx beneficiarySecKey txBodyNew let tx = Transaction txBodyNew [(beneficiaryPubKey, sig)] (Map.singleton outRef (UnlockByScript authorizedBeneficiaryValidator (Redeemer (DBytes "")))) applyTx (Env (Slot 0)) tx utxo `shouldSatisfy` isJust it "fails to unlock when a non-beneficiary signs the transaction" $ do (beneficiaryPubKey, _) <- generateKeyPair (attackerPubKey, attackerSecKey) <- generateKeyPair let scriptAddr = Address $ Hash.hashByteString "vesting_script" txIdOrigin = computeTxId $ TxBody [] [] rangeOpen outRef = TxOutRef txIdOrigin (TxOutIdx 0) -- Locked to the true beneficiary beneficiaryBytes = Sign.publicKeyToBinary beneficiaryPubKey.unPublicKey lockedDatum = DBytes beneficiaryBytes utxo = UTxO $ Map.singleton outRef (TxOut scriptAddr (Ada 100) (Just lockedDatum)) txIn = TxIn outRef txOut = TxOut scriptAddr (Ada 100) Nothing txBodyNew = TxBody [txIn] [txOut] rangeOpen -- The attacker signs the transaction with their own key attackerSig <- signTx attackerSecKey txBodyNew let -- Attacker attaches their valid signature, but it doesn't match the Datum tx = Transaction txBodyNew [(attackerPubKey, attackerSig)] (Map.singleton outRef (UnlockByScript authorizedBeneficiaryValidator (Redeemer (DBytes "")))) applyTx (Env (Slot 0)) tx utxo `shouldSatisfy` isNothing describe "Transaction Application (applyTx) - Vesting Script (Time & Identity)" $ do it "successfully unlocks when signed by the beneficiary AFTER the vesting period" $ do (benefPubKey, benefSecKey) <- generateKeyPair let scriptAddr = Address $ Hash.hashByteString "vesting_script" outRef = TxOutRef (dummyTxId 0) (TxOutIdx 0) -- Datum: Beneficiary PubKey and Slot 100 benefBytes = Sign.publicKeyToBinary benefPubKey.unPublicKey lockedDatum = DList [DBytes benefBytes, DInt 100] utxo = UTxO $ Map.singleton outRef (TxOut scriptAddr (Ada 100) (Just lockedDatum)) txIn = TxIn outRef txOut = TxOut scriptAddr (Ada 100) Nothing -- The transaction is valid from Slot 105 onwards (after the Slot 100 requirement) validTime = Range (Just (Slot 105)) Nothing txBodyNew = TxBody [txIn] [txOut] validTime sig <- signTx benefSecKey txBodyNew let tx = Transaction txBodyNew [(benefPubKey, sig)] (Map.singleton outRef (UnlockByScript vestingValidator (Redeemer (DBytes "")))) applyTx (Env (Slot 105)) tx utxo `shouldSatisfy` isJust it "fails to unlock when signed by the beneficiary BEFORE the vesting period" $ do (benefPubKey, benefSecKey) <- generateKeyPair let scriptAddr = Address $ Hash.hashByteString "vesting_script" outRef = TxOutRef (dummyTxId 0) (TxOutIdx 0) -- Datum: Beneficiary PubKey and Slot 100 benefBytes = Sign.publicKeyToBinary benefPubKey.unPublicKey lockedDatum = DList [DBytes benefBytes, DInt 100] utxo = UTxO $ Map.singleton outRef (TxOut scriptAddr (Ada 100) (Just lockedDatum)) txIn = TxIn outRef txOut = TxOut scriptAddr (Ada 100) Nothing -- The transaction is only valid from Slot 90 to 95 (BEFORE the Slot 100 requirement) earlyTime = Range (Just (Slot 90)) (Just (Slot 95)) txBodyNew = (TxBody [txIn] [txOut] earlyTime) sig <- signTx benefSecKey txBodyNew let tx = Transaction txBodyNew [(benefPubKey, sig)] (Map.singleton outRef (UnlockByScript vestingValidator (Redeemer (DBytes "")))) applyTx (Env (Slot 0)) tx utxo `shouldSatisfy` isNothing it "fails to unlock when signed by an attacker AFTER the vesting period" $ do (benefPubKey, _) <- generateKeyPair (attackerPubKey, attackerSecKey) <- generateKeyPair let scriptAddr = Address $ Hash.hashByteString "vesting_script" outRef = TxOutRef (dummyTxId 0) (TxOutIdx 0) -- Datum: Beneficiary PubKey and Slot 100 benefBytes = Sign.publicKeyToBinary benefPubKey.unPublicKey lockedDatum = DList [DBytes benefBytes, DInt 100] utxo = UTxO $ Map.singleton outRef (TxOut scriptAddr (Ada 100) (Just lockedDatum)) txIn = TxIn outRef txOut = TxOut scriptAddr (Ada 100) Nothing -- Time is correct, but signature is wrong validTime = Range (Just (Slot 105)) Nothing txBodyNew = TxBody [txIn] [txOut] validTime attackerSig <- signTx attackerSecKey txBodyNew let tx = Transaction txBodyNew [(attackerPubKey, attackerSig)] (Map.singleton outRef (UnlockByScript vestingValidator (Redeemer (DBytes "")))) applyTx (Env (Slot 0)) tx utxo `shouldSatisfy` isNothing describe "Ledger-Level Time Validation (applyTx)" $ do it "accepts a transaction when the environment slot is within the valid range" $ do (pubKey, secKey) <- generateKeyPair let addr = deriveAddress pubKey outRef = TxOutRef (dummyTxId 0) (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr (Ada 100) Nothing) txIn = TxIn outRef txOut = TxOut addr (Ada 100) Nothing -- Transaction is only valid between slots 10 and 20 txTime = Range (Just (Slot 10)) (Just (Slot 20)) txBodyNew = TxBody [txIn] [txOut] txTime sig <- signTx secKey txBodyNew let tx = Transaction txBodyNew [] (Map.singleton outRef (UnlockBySignature pubKey sig)) -- Current ledger time is 15 (Inside) applyTx (Env (Slot 15)) tx utxo `shouldSatisfy` isJust -- Edge cases: exactly 10 and 20 should also pass based on your rangeIncludes logic applyTx (Env (Slot 10)) tx utxo `shouldSatisfy` isJust applyTx (Env (Slot 20)) tx utxo `shouldSatisfy` isJust it "rejects a transaction when the environment slot is BEFORE the valid range" $ do (pubKey, secKey) <- generateKeyPair let addr = deriveAddress pubKey outRef = TxOutRef (dummyTxId 0) (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr (Ada 100) Nothing) txIn = TxIn outRef txOut = TxOut addr (Ada 100) Nothing txTime = Range (Just (Slot 10)) (Just (Slot 20)) txBodyNew = TxBody [txIn] [txOut] txTime sig <- signTx secKey txBodyNew let tx = Transaction txBodyNew [] (Map.singleton outRef (UnlockBySignature pubKey sig)) -- Current ledger time is 9 (Too early) applyTx (Env (Slot 9)) tx utxo `shouldSatisfy` isNothing it "rejects a transaction when the environment slot is AFTER the valid range" $ do (pubKey, secKey) <- generateKeyPair let addr = deriveAddress pubKey outRef = TxOutRef (dummyTxId 0) (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr (Ada 100) Nothing) txIn = TxIn outRef txOut = TxOut addr (Ada 100) Nothing txTime = Range (Just (Slot 10)) (Just (Slot 20)) txBodyNew = TxBody [txIn] [txOut] txTime sig <- signTx secKey txBodyNew let tx = Transaction txBodyNew [] (Map.singleton outRef (UnlockBySignature pubKey sig)) -- Current ledger time is 21 (Too late) applyTx (Env (Slot 21)) tx utxo `shouldSatisfy` isNothing -- The UTxO set maps these references to the actual locked outputs. newtype UTxO = UTxO {unUTxO :: Map.Map TxOutRef TxOut} deriving newtype (Eq, Show) -- | --------------------------------------------------------------------------- -- | TxOut -- | --------------------------------------------------------------------------- data TxOut = TxOut { address :: Address Wallet, value :: Ada, datum :: Maybe Datum } deriving stock (Eq, Show, Generic) -- An output reference uniquely identifies a specific unspent output. data TxOutRef = TxOutRef { txId :: TxId, txOutIdx :: TxOutIdx } deriving stock (Eq, Ord, Show, Generic) newtype TxId = TxId {unTxId :: Hash.Hash} deriving newtype (Eq, Ord, Show) computeTxId :: TxBody -> TxId computeTxId body = TxId $ Hash.hashByteString (BSC.pack $ show body) newtype TxOutIdx = TxOutIdx {unTxOutIdx :: Int} deriving newtype (Eq, Ord, Show, Num, Enum) newtype Ada = Ada {unAda :: Fixed E6} deriving newtype (Eq, Ord, Show) deriving (Semigroup, Monoid) via (Sum (Fixed E6)) -- | --------------------------------------------------------------------------- -- | --------------------------------------------------------------------------- -- | EXTENDED UTXO TYPES -- | --------------------------------------------------------------------------- type Validator = Datum -> Redeemer -> ScriptContext -> Bool data Datum = DInt Int64 | DDouble Double | DBytes BS.StrictByteString | DBool Bool | DList [Datum] deriving stock (Eq, Show, Generic) newtype Redeemer = Redeemer {unRedeemer :: Datum} deriving stock (Eq, Show, Generic) newtype ScriptContext = ScriptContext {transaction :: Transaction} deriving stock (Eq, Show, Generic) -- A transaction input now specifies how it intends to unlock the output data UnlockMethod = UnlockBySignature PublicKey Signature | UnlockByScript Validator Redeemer instance Show UnlockMethod where show (UnlockBySignature _ _) = "UnlockBySignature " show (UnlockByScript _ _) = "UnlockByScript " instance Eq UnlockMethod where (UnlockBySignature p1 s1) == (UnlockBySignature p2 s2) = p1 == p2 && s1 == s2 (UnlockByScript _ r1) == (UnlockByScript _ r2) = r1 == r2 -- | --------------------------------------------------------------------------- -- | --------------------------------------------------------------------------- -- | TxIn -- | --------------------------------------------------------------------------- newtype TxIn = TxIn { txOutRef :: TxOutRef } deriving stock (Eq, Show, Generic) -- | --------------------------------------------------------------------------- -- | --------------------------------------------------------------------------- -- | Tx -- | --------------------------------------------------------------------------- data Transaction = Transaction { txBody :: TxBody, txSignatures :: [(PublicKey, Signature)], txUnlockers :: Map.Map TxOutRef UnlockMethod } deriving stock (Eq, Show, Generic) data TxBody = TxBody { txInputs :: [TxIn], txOutputs :: [TxOut], validRange :: Range Slot } deriving stock (Eq, Show, Generic) newtype Slot = Slot {unSlot :: Int64} deriving newtype (Eq, Ord, Show) newtype Env = Env {slot :: Slot} deriving stock (Eq, Ord, Show) applyTx :: Env -> Transaction -> UTxO -> Maybe UTxO applyTx env tx (UTxO utxo) = do -- 1. Check if the transaction is in a valid slot guard $ rangeIncludes tx.txBody.validRange env.slot -- 2. Lookup all consumed outputs and pair them with their inputs consumed <- mapM (\txIn -> (txIn,) <$> utxo Map.!? txIn.txOutRef) tx.txBody.txInputs -- 3. Verify authorization guard $ all (uncurry $ verifyTxPair tx) consumed -- 4. Verify conservation of value let inputsValue = foldMap ((.value) . snd) consumed outputsValue = foldMap (.value) tx.txBody.txOutputs guard $ inputsValue == outputsValue -- 5. Update the UTxO map let utxoMinusInputs = foldl' (flip Map.delete) utxo ((.txOutRef) <$> tx.txBody.txInputs) txId = computeTxId tx.txBody return $ UTxO $ foldl' (\u (idx, out) -> Map.insert (TxOutRef txId idx) out u) utxoMinusInputs (zip [0 ..] tx.txBody.txOutputs) verifyTxPair :: Transaction -> TxIn -> TxOut -> Bool verifyTxPair tx txIn txOut = case Map.lookup txIn.txOutRef tx.txUnlockers of Just (UnlockBySignature pubKey sig) -> isNothing txOut.datum && verifyAddress pubKey txOut.address && verifySignature pubKey sig (computeTxId tx.txBody) Just (UnlockByScript validator redeemer) -> case txOut.datum of Just d -> validator d redeemer (ScriptContext tx) Nothing -> False Nothing -> False -- | --------------------------------------------------------------------------- -- | --------------------------------------------------------------------------- -- | Wallet -- | --------------------------------------------------------------------------- data Wallet = Wallet { key :: PublicKey, balance :: Ada } deriving stock (Eq, Show, Generic) newtype WalletId = WalletId {unWalletId :: Address Wallet} deriving newtype (Eq, Ord, Show) newtype Address a = Address {unAddress :: Hash.Hash} deriving newtype (Eq, Ord, Show) newtype PublicKey = PublicKey {unPublicKey :: Sign.PublicKey} deriving newtype (Eq) instance Show PublicKey where show _ = "" -- A basic cryptographic signature newtype Signature = Signature {unSignaure :: Sign.SignedMessage} deriving newtype (Eq) instance Show Signature where show _ = "" -- | Hashes a public key to produce a standard Wallet Address. deriveAddress :: PublicKey -> Address a deriveAddress pub = Address $ Hash.hashByteString (Sign.publicKeyToBinary pub.unPublicKey) signTx :: SecretKey -> TxBody -> IO Signature signTx sek txBody = Signature <$> Sign.signMessage (Hash.hashToBinary (computeTxId txBody).unTxId) sek.unSecretKey -- | Verifies an Ed25519 signature against a PublicKey and the expected TxId payload. verifySignature :: PublicKey -> Signature -> TxId -> Bool verifySignature pub sig txid = Sign.openMessage sig.unSignaure pub.unPublicKey == Just (Hash.hashToBinary txid.unTxId) -- | Checks if a given PublicKey mathematically hashes to the provided Address. verifyAddress :: PublicKey -> Address a -> Bool verifyAddress pub addr = deriveAddress pub == addr newtype SecretKey = SecretKey {unSecretKey :: Sign.SecretKey} deriving newtype (Eq) instance Show SecretKey where show _ = "" -- | Generates a new Ed25519 key pair using Sel. generateKeyPair :: IO (PublicKey, SecretKey) generateKeyPair = bimap PublicKey SecretKey <$> Sign.generateKeyPair -- | --------------------------------------------------------------------------- -- | --------------------------------------------------------------------------- -- | Block -- | --------------------------------------------------------------------------- data Block = Block { blId :: BlockId, blTxs :: [Transaction] } newtype BlockId = BlockId {unBlockId :: Int} deriving newtype (Eq, Ord, Show) applyBlock :: Env -> Block -> UTxO -> Maybe UTxO applyBlock env block utxo = foldM (flip $ applyTx env) utxo block.blTxs -- | --------------------------------------------------------------------------- -- | --------------------------------------------------------------------------- -- | Range (lib) -- | --------------------------------------------------------------------------- data Range a = Range { lower :: Maybe a, upper :: Maybe a } deriving stock (Eq, Show, Generic) rangeOpen :: Range a rangeOpen = Range Nothing Nothing rangeIncludes :: (Ord a) => Range a -> a -> Bool rangeIncludes Range {..} x = maybe True (x >=) lower && maybe True (x <=) upper -- | --------------------------------------------------------------------------- -- | Sample validator passwordValidator :: Validator passwordValidator datum (Redeemer redeemerData) _context = case (datum, redeemerData) of (DBytes orig, DBytes provided) -> orig == Hash.hashToBinary (Hash.hashByteString provided) _ -> False -- | Sample validator (inspect context) authorizedBeneficiaryValidator :: Validator authorizedBeneficiaryValidator datum _ (ScriptContext tx) = case datum of DBytes beneficiaryBytes -> -- Check if ANY of the provided transaction signatures belong to the beneficiary -- AND are cryptographically valid for this transaction. any ( \(pub, sig) -> Sign.publicKeyToBinary pub.unPublicKey == beneficiaryBytes && verifySignature pub sig (computeTxId tx.txBody) ) tx.txSignatures _ -> False -- | Sample validator (slot) vestingValidator :: Validator vestingValidator datum _ (ScriptContext tx) = case datum of DList [DBytes beneficiaryBytes, DInt unlockSlot] -> -- 1. Identity Check any ( \(pub, sig) -> Sign.publicKeyToBinary pub.unPublicKey == beneficiaryBytes && verifySignature pub sig (computeTxId tx.txBody) ) tx.txSignatures -- 2. Temporal Check: The start of the tx's valid range must be AFTER the unlock slot. && case tx.txBody.validRange.lower of Just (Slot txStart) -> txStart >= unlockSlot Nothing -> False -- If the tx has no lower bound, it could execute before the unlock slot, so reject it. _ -> False