{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE NoFieldSelectors #-} 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 describe "Cryptography Helpers" $ do it "verifies a correctly signed transaction" $ do (pubKey, secKey) <- generateKeyPair let txId = TxId 1 sig <- signTx secKey txId verifySignature pubKey sig txId `shouldBe` True it "rejects a signature for a modified transaction ID" $ do (pubKey, secKey) <- generateKeyPair let txId1 = TxId 1 txId2 = TxId 2 sig <- signTx secKey txId1 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 txId = TxId 1 sig <- signTx secKey1 txId 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 = TxId 0 outRef = TxOutRef txIdOrigin (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr (Ada 100) Nothing) txIdNew = TxId 1 sig <- signTx secKey txIdNew let txIn = TxIn outRef (UnlockBySignature pubKey sig) txOut = TxOut addr (Ada 100) Nothing tx = Transaction txIdNew [txIn] [txOut] [] rangeOpen 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 = TxId 0 outRef = TxOutRef txIdOrigin (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr1 (Ada 100) Nothing) txIdNew = TxId 1 sig <- signTx secKey2 txIdNew let txIn = TxIn outRef (UnlockBySignature pubKey1 sig) txOut = TxOut addr1 (Ada 100) Nothing tx = Transaction txIdNew [txIn] [txOut] [] rangeOpen 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 = TxId 0 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)) txIdNew = TxId 1 -- The spender provides the plaintext password "secret" correctRedeemer = Redeemer (DBytes "secret") txIn = TxIn outRef (UnlockByScript passwordValidator correctRedeemer) txOut = TxOut scriptAddr (Ada 100) Nothing -- Sending it somewhere else tx = Transaction txIdNew [txIn] [txOut] [] rangeOpen 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 = TxId 0 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)) txIdNew = TxId 1 -- The spender provides the wrong password wrongRedeemer = Redeemer (DBytes "wrong_password") txIn = TxIn outRef (UnlockByScript passwordValidator wrongRedeemer) txOut = TxOut scriptAddr (Ada 100) Nothing tx = Transaction txIdNew [txIn] [txOut] [] rangeOpen 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 = TxId 0 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)) txIdNew = TxId 1 -- The beneficiary signs the transaction and attaches it to txSignatures sig <- signTx beneficiarySecKey txIdNew let -- The redeemer doesn't matter here, the context provides the proof txIn = TxIn outRef (UnlockByScript authorizedBeneficiaryValidator (Redeemer (DBytes ""))) txOut = TxOut scriptAddr (Ada 100) Nothing tx = Transaction txIdNew [txIn] [txOut] [(beneficiaryPubKey, sig)] rangeOpen 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 = TxId 0 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)) txIdNew = TxId 1 -- The attacker signs the transaction with their own key attackerSig <- signTx attackerSecKey txIdNew let txIn = TxIn outRef (UnlockByScript authorizedBeneficiaryValidator (Redeemer (DBytes ""))) txOut = TxOut scriptAddr (Ada 100) Nothing -- Attacker attaches their valid signature, but it doesn't match the Datum tx = Transaction txIdNew [txIn] [txOut] [(attackerPubKey, attackerSig)] rangeOpen 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 (TxId 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)) txIdNew = TxId 1 sig <- signTx benefSecKey txIdNew let txIn = TxIn outRef (UnlockByScript vestingValidator (Redeemer (DBytes ""))) 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 tx = Transaction txIdNew [txIn] [txOut] [(benefPubKey, sig)] validTime 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 (TxId 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)) txIdNew = TxId 1 sig <- signTx benefSecKey txIdNew let txIn = TxIn outRef (UnlockByScript vestingValidator (Redeemer (DBytes ""))) 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)) tx = Transaction txIdNew [txIn] [txOut] [(benefPubKey, sig)] earlyTime 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 (TxId 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)) txIdNew = TxId 1 attackerSig <- signTx attackerSecKey txIdNew let txIn = TxIn outRef (UnlockByScript vestingValidator (Redeemer (DBytes ""))) txOut = TxOut scriptAddr (Ada 100) Nothing -- Time is correct, but signature is wrong validTime = Range (Just (Slot 105)) Nothing tx = Transaction txIdNew [txIn] [txOut] [(attackerPubKey, attackerSig)] validTime 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 (TxId 0) (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr (Ada 100) Nothing) txIdNew = TxId 1 sig <- signTx secKey txIdNew let txIn = TxIn outRef (UnlockBySignature pubKey sig) txOut = TxOut addr (Ada 100) Nothing -- Transaction is only valid between slots 10 and 20 txTime = Range (Just (Slot 10)) (Just (Slot 20)) tx = Transaction txIdNew [txIn] [txOut] [] txTime -- 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 (TxId 0) (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr (Ada 100) Nothing) txIdNew = TxId 1 sig <- signTx secKey txIdNew let txIn = TxIn outRef (UnlockBySignature pubKey sig) txOut = TxOut addr (Ada 100) Nothing txTime = Range (Just (Slot 10)) (Just (Slot 20)) tx = Transaction txIdNew [txIn] [txOut] [] txTime -- 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 (TxId 0) (TxOutIdx 0) utxo = UTxO $ Map.singleton outRef (TxOut addr (Ada 100) Nothing) txIdNew = TxId 1 sig <- signTx secKey txIdNew let txIn = TxIn outRef (UnlockBySignature pubKey sig) txOut = TxOut addr (Ada 100) Nothing txTime = Range (Just (Slot 10)) (Just (Slot 20)) tx = Transaction txIdNew [txIn] [txOut] [] txTime -- 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 :: Word64} deriving newtype (Eq, Ord, Show) 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 -- | --------------------------------------------------------------------------- data TxIn = TxIn { txOutRef :: TxOutRef, unlocker :: UnlockMethod } deriving stock (Eq, Show, Generic) -- | --------------------------------------------------------------------------- -- | --------------------------------------------------------------------------- -- | Tx -- | --------------------------------------------------------------------------- -- A Transaction is simply a list of inputs being consumed and new outputs being created. data Transaction = Transaction { txId :: TxId, -- The hash of this transaction txInputs :: [TxIn], txOutputs :: [TxOut], txSignatures :: [(PublicKey, Signature)], 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.validRange env.slot -- 2. Lookup all consumed outputs and pair them with their inputs consumed <- mapM (\txIn -> (txIn,) <$> utxo Map.!? txIn.txOutRef) tx.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.txOutputs guard $ inputsValue == outputsValue -- 5. Update the UTxO map let utxoMinusInputs = foldl' (flip Map.delete) utxo ((.txOutRef) <$> tx.txInputs) return $ UTxO $ foldl' (\u (idx, out) -> Map.insert (TxOutRef tx.txId idx) out u) utxoMinusInputs (zip [0 ..] tx.txOutputs) verifyTxPair :: Transaction -> TxIn -> TxOut -> Bool verifyTxPair tx txIn txOut = case txIn.unlocker of UnlockBySignature pubKey sig -> isNothing txOut.datum && verifyAddress pubKey txOut.address && verifySignature pubKey sig tx.txId UnlockByScript validator redeemer -> case txOut.datum of Just d -> validator d redeemer (ScriptContext tx) 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) -- | Signs a payload (the TxId) using the sender's Ed25519 SecretKey. signTx :: SecretKey -> TxId -> IO Signature signTx sek txid = Signature <$> Sign.signMessage (bsTxId txid) 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 (bsTxId txid) -- | 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 bsTxId :: TxId -> BS.StrictByteString bsTxId = BSL.toStrict . BSB.toLazyByteString . BSB.word64Hex . (.unTxId) -- | --------------------------------------------------------------------------- -- | --------------------------------------------------------------------------- -- | 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 tx.txId ) 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 tx.txId ) tx.txSignatures -- 2. Temporal Check: The start of the tx's valid range must be AFTER the unlock slot. && case tx.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