microledger: eUTxO

In the previous log, we have designed a simple ledger focused enabling only spending with a secret key.

Cardano follows the eUTxO model; e stands for extended, allowing spending conditionally.

Each output comes with some data, called Datum, which is given to a script, alongside some redeemer data.

We can start drafting the payload, as follows:

data Datum
  = DInt Int64
  | DDouble Double
  | DBytes BS.StrictByteString
  | DBool Bool
  | DList [Datum]
  deriving stock (Eq, Show, Generic)

Note: it looks like aeson's Value, it could be squeezed even more, but that's enough.We can then decorate TxOut with it, as follows:

data TxOut = TxOut
  { address :: Address Wallet,
    value :: Ada,
    datum :: Maybe Datum
  }
  deriving stock (Eq, Show, Generic)

The next step is to have a dedicated way to distinguish how outputs should be spent, as follows:

data TxIn = TxIn
  { txOutRef :: TxOutRef,
    unlocker :: UnlockMethod
  }

data UnlockMethod
  = UnlockBySignature PublicKey Signature
  | UnlockByScript Validator Redeemer

We should continue to diverge from Cardano's implementation, representing Validator as plain functions, as follows:

type Validator = Datum -> Redeemer -> ScriptContext -> Bool

newtype Redeemer
  = Redeemer {unRedeemer :: Datum}
  deriving stock (Eq, Show, Generic)

newtype ScriptContext
  = ScriptContext {transaction :: Transaction}

This structural change forces us to rework how transactions are verified, as follows:

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

See the full source.

This enables us to craft a simple password validator, as follows:

passwordValidator :: Validator
passwordValidator datum (Redeemer redeemerData) _context =
  case (datum, redeemerData) of
    (DBytes orig, DBytes provided) ->
      orig == Hash.hashToBinary (Hash.hashByteString provided)
    _ -> False

Validator classically rely on the signatures attached to a transaction and its validity range (block slot).

We can craft a small type, as follows:

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

Then we should extend transactions, as follows:

data Transaction = Transaction
  { txId :: TxId,
    txInputs :: [TxIn],
    txOutputs :: [TxOut],
    txSignatures :: [(PublicKey, Signature)],
    validRange :: Range Slot
  }
  deriving stock (Eq, Show, Generic)

And we should update how transactions are checked, as follows:

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

  -- ...

One of the first classical validators is to restrict the unlocking to transactions signed by a specific key, as follows:

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

Another one is to only do it after some slot, as follows:

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

See the full source of the snippets above and this one, which includes small improvements.