microledger: forging blocks

In the previous log, we have designed a ledger able to create and sign transactions based on both public keys (UTxO) and smart contracts (eUTxO) spending.

The idea is that, at some point, a transaction is submitted to a node, which creates, forges, a block, which will be shared between nodes.

One thing to consider is the fact that running a node is not cheap. To incentivize node owners, we can add a fee in the transaction, which will be transferred to the node forging the block as a reward, which gives us the following code:

data TxBody = TxBody
  { txInputs :: [TxIn],
    txOutputs :: [TxOut],
    validRange :: Range Slot,
    fee :: Ada
  }
  deriving stock (Eq, Show, Generic)

The next step is to ensure no money is created or lost, updating applyTx as follows:

applyTx :: Env -> Transaction -> UTxO -> Maybe UTxO
applyTx env tx (UTxO utxo) = do
  -- ...
  -- 4. Verify conservation of value
  -- ...
  guard $ inputsValue == outputsValue <> tx.txBody.fee
  -- ...

See the full source.

Note: see also this intermediate version fixing the Address format.

The next step consists of enabling submitting a transaction to a node.

We need to keep an UTxO map and, if the transaction is valid against it, add the transaction in a mempool, which is a staging area for transactions before they get forged in a block.

Which gives the following snippet:

data NodeState = NodeState
  { currentUtxo :: UTxO,
    env :: Env,
    mempool :: [Transaction] -- LIFO
  }
  deriving stock (Eq, Show, Generic)

submitTx :: Transaction -> NodeState -> NodeState
submitTx tx node =
  case applyTx node.env tx node.currentUtxo of
    Just _ -> node {mempool = tx : node.mempool}
    Nothing -> node

Notes:

  • mempool accumulate transactions last-in/first-out due to the nature of ists in Haskell; it is more efficient to prepend than to append an element to a list
  • We only update the UTxO map on block update.See the full source.

Once we have a list of transactions, we should forge the block. We can start by creating the id by hashing the included transactions, as follows:

newtype BlockId
  = BlockId {unBlockId :: Hash.Hash}
  deriving newtype (Eq, Ord, Show)

computeBlockId :: [TxId] -> BlockId
computeBlockId =
  BlockId
    . Hash.hashByteString
    . BSL.toStrict
    . BSB.toLazyByteString
    . foldMap (BSB.byteString . Hash.hashToBinary . (.unTxId))

Then, we should pick the node in charge of forging the block.

Cardano uses proof of stake (PoS), which is a bit involved currently. We will simply associate an Wallet to the node, picking a wallet from all of them, the leader, so we will restrict the forging later, as follows:

electLeader :: Slot -> Map.Map (Address Wallet) Wallet -> Wallet
electLeader slot wallets =
  snd $ fromIntegral (random `mod` fromIntegral (Map.size wallets)) `Map.elemAt` wallets
  where
    random = bsToWord64 $ Hash.hashToBinary $ Hash.hashByteString $ word64ToBS slot.unSlot

Then we should put everything together to forge the block as follows:

data NodeState = NodeState
  { currentUtxo :: UTxO,
    env :: Env,
    mempool :: [Transaction], -- LIFO
    nodeWallet :: Address Wallet,
    wallets :: Map.Map (Address Wallet) Wallet
  }
  deriving stock (Eq, Show, Generic)

forgeBlock :: NodeState -> Maybe Block
forgeBlock node = do
  let leader = electLeader node.env.slot node.wallets
  guard $ deriveAddress leader.key == node.nodeWallet
  let txs = reverse node.mempool
      block = Block (computeBlockId $ computeTxId . (.txBody) <$> txs) txs
  void $ applyBlock node.env block node.currentUtxo
  return block

Notes:

  • We should reverse the mempool as transactions are accumulated in LIFO
  • We run applyBlock to make sure the produced Block is sound (no double spending, etc.)

See the full source.

The last part of this log is to sign the newly created block.

blockSign :: SecretKey -> BlockId -> IO Signature
blockSign = signatureSignOn (.unBlockId)

blockVerifySignature :: PublicKey -> Signature -> BlockId -> Bool
blockVerifySignature = signatureVerifyOn (.unBlockId)

signatureSignOn :: (a -> Hash.Hash) -> SecretKey -> a -> IO Signature
signatureSignOn extract sek x = Signature <$> Sign.signMessage (Hash.hashToBinary $ extract x) sek.unSecretKey

signatureVerifyOn :: (a -> Hash.Hash) -> PublicKey -> Signature -> a -> Bool
signatureVerifyOn extract pub sig x =
  Sign.openMessage sig.unSignaure pub.unPublicKey == Just (Hash.hashToBinary $ extract x)

We should continue by adding the public key signing the block (for the node's wallet) and the actual signature to the Block, so it is verified in applyBlock, as follows:

data Block = Block
  { blId :: BlockId,
    blTxs :: [Transaction],
    blIssuer :: PublicKey,
    blSignature :: Signature
  }
  deriving stock (Eq, Show, Generic)

applyBlock :: Env -> Map.Map (Address Wallet) Wallet -> Block -> UTxO -> IO (Maybe UTxO)
applyBlock env wallets block utxo =
  runMaybeT $ do
    -- 1. Leader Verification
    let expectedLeader = electLeader env.slot wallets
    guard $ block.blIssuer == expectedLeader.key

    -- 2. Cryptographic Verification
    guard $ blockVerifySignature block.blIssuer block.blSignature block.blId

    -- 3. Apply Transactions
    hoistMaybe $ foldM (flip $ applyTx env) utxo block.blTxs

Then we can actually fill the signature during block forging, as follows:

forgeBlock :: SecretKey -> NodeState -> IO (Maybe Block)
forgeBlock sek node =
  runMaybeT $ do
    let leader = electLeader node.env.slot node.wallets
    guard $ deriveAddress leader.key == node.nodeWallet

    let txs = reverse node.mempool
        blId = computeBlockId $ computeTxId . (.txBody) <$> txs

    sign <- lift $ blockSign sek blId

    let block = Block blId txs leader.key sign

    void $ MaybeT $ applyBlock node.env node.wallets block node.currentUtxo
    return block

Note: I could have added the SecretKey directly in NodeState, but it is quite sensitive and would have been given to all functions relying on NodeState.

See the full source.

Something worth mentioning, and drafting smart contract signing, which is not currently handled.

Valiators are pure functions for the moment, consequently, to avoid having a huge log, we will only give “unique” names.

We start by defining a plain Script, as follows:

data Script = Script
  { scriptId :: ScriptId,
    validator :: Validator
  }

-- Eq and Show instances just rely on the scriptId
instance Eq Script where
  s1 == s2 = s1.scriptId == s2.scriptId

instance Show Script where
  show s = "Script " <> BSC.unpack s.scriptId.unScriptId

newtype ScriptId
  = ScriptId {unScriptId :: BS.StrictByteString}
  deriving newtype (Eq, Show, IsString)

scriptAddress :: Script -> Address Script
scriptAddress = Address . Hash.hashByteString . (.scriptId.unScriptId)

It leads us to promote our existing Validators to Scripts, as in the following one:

passwordScript :: Script
passwordScript =
  Script "password_script_v1" $ \datum (Redeemer redeemerData) _context ->
    case (datum, redeemerData) of
      (DBytes orig, DBytes provided) ->
        orig == Hash.hashToBinary (Hash.hashByteString provided)
      _ -> False

We can leverage it in UnlockMethod, as follows:

data UnlockMethod
  = UnlockBySignature PublicKey Signature
  | UnlockByScript Script Redeemer

As a reminder, Address is a phantom type specifying the type of address represented, which is a bit constraining for TxOut, because it could be either a Wallet or a Script.

We have to come up with a universal address holder, as follows:

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

data AnyAddress = forall a. AnyAddress (Address a)

instance Eq AnyAddress where
  AnyAddress x == AnyAddress y =
    x.unAddress == y.unAddress

instance Show AnyAddress where
  show (AnyAddress x) = show x

withAddress :: AnyAddress -> (forall a. Address a -> b) -> b
withAddress (AnyAddress addr) f = f addr

It enables us to verify that the provided script is the right one in verifyTxPair, as follows:

verifyTxPair :: Transaction -> TxIn -> TxOut -> Bool
verifyTxPair tx txIn txOut =
  case Map.lookup txIn.txOutRef tx.txUnlockers of
    Just (UnlockBySignature pubKey sig) ->
      isNothing txOut.datum
        && withAddress txOut.address (verifyAddress pubKey)
        && verifySignatureTx pubKey sig (computeTxId tx.txBody)
    Just (UnlockByScript script redeemer) ->
      let expectedAddress = AnyAddress $ Address (Hash.hashByteString script.scriptId.unScriptId)
       in txOut.address == expectedAddress
            && case txOut.datum of
              Just d -> script.validator d redeemer (ScriptContext tx)
              Nothing -> False
    Nothing -> False

See the full source.