\documentclass[11pt, a4paper]{article}

\usepackage{tikz}
\usetikzlibrary{shapes,arrows}
\usetikzlibrary{datavisualization}
\usetikzlibrary{datavisualization.formats.functions}
\usepackage{placeins}
\usepackage{amsmath}
\usepackage{booktabs}

\begin{document}

\title{ADABOOST}
\date{}
\maketitle

Boosting is a powerful technique to combine several `weak' classifiers into a `strong' classifier. $AdaBoost$, short for `Adaptive Boosting' is one of the most frequently used boosting algorithms.

\section{Weak and Strong Learners}

A weak learner is a classification algorithm which is only slightly better than random guessing. On the other hand, a strong learner is one which almost always provides the true classification.
Given training data of the form $(x_1, y_1),\ (x_2, y_2),\ ...\ , (x_n, y_n)$ where $y_i \in \{+1, -1\}\ \forall\ x_i \in \mathbf{X}\ [1]$  and a learner $h$ the error $\epsilon$ is defined as,

\begin{align*}
	\epsilon = \frac{1}{N} \times \left\{
	\begin{array}{ll}
	0\ if\ y_i = h(x_i)                   \\
	1\ if\ y_i \neq h(x_i)                \\
	\end{array}
	\right.
\end{align*}

The error rate $\epsilon$ is related to the strength of a learner as shown below:

\FloatBarrier
\begin{figure}[htbp]
	\centering
	\begin{tikzpicture}
		\draw[thick] (-3,0) -- (3,0);
		\foreach \x in  {-3, 0 , 3}
		\draw[shift={(\x,0)},color=black] (0pt,3pt) -- (0pt,-3pt);

		\draw[shift={(-3,0)},color=black] (0pt,0pt) -- (0pt,-3pt) node[below] {0};
		\draw[shift={(0,0)},color=black] (0pt,0pt) -- (0pt,-3pt) node[below] {0.5};
		\draw[shift={(3,0)},color=black] (0pt,0pt) -- (0pt,-3pt) node[below] {1};

		\node at (5, 0)   {Error rate ($\epsilon$)};
		\node at (0.45, 2)   (wl) {Weak Learner};
		\node at (-2.55, -2)   (sl) {Strong Learner};

		\draw[thick,->, >=stealth] (wl) -- (0.45, 0);
		\draw[thick,->, >=stealth] (sl) -- (-2.55, 0);
	\end{tikzpicture}
\end{figure}

\section{Algorithm}

Given training data of the form [1] in the preceding section and weak learners $h_1,\ h_2,\ ...\ h_m$, the goal is to iteratively come up with a strong learner $H$. AdaBoost's algorithmic flowchart is as follows:

\tikzstyle{startstop} = [ellipse, inner sep = 0.1em, thick, text centered, draw=black]
\tikzstyle{process} = [rectangle, thick, text centered, draw=black]
\tikzstyle{decision} = [diamond, inner sep=0.1em, aspect = 2, thick, text centered, draw=black]
\tikzstyle{line} = [draw, thick, ->, >=stealth]

\FloatBarrier
\begin{figure}
	\centering
	\begin{tikzpicture}
		\node [startstop] (initWeights) {\begin{tabular}{c}Initialize equal weights \\ for each datapoint \\ $w_i = \frac{1}{N}$\end{tabular}};
		\node [process, below of=initWeights, node distance=8em] (calcError) {\begin{tabular}{c} Calculate error \\
			for each weak classifier $h_j$\\
			$\epsilon_j = \sum\limits_{wrong} w_i$ \\

			\end{tabular}};
		\node [process, below of=calcError, node distance = 8em] (pickClsfr) {\begin{tabular}{c} Pick the best \\
			weak classifier $h_{best}$  \\
			$best = \operatorname*{argmax}_{j}\left\{|\frac{1}{2} - \epsilon_j| \right.$

			\end{tabular}} ;
		\node [process, right of=pickClsfr, node distance = 15em] (calcAlpha) {\begin{tabular}{c} Calculate $\alpha$ \\
			$\alpha=\frac{1}{2}\times\ln(\frac{1 - \epsilon_{best}}{\epsilon_{best}})$

			\end{tabular}} ;
		\node [decision, below of=pickClsfr, node distance = 13em] (stop) {\begin{tabular}{c}
			Is $H$ good enough? \\
			Exhausted number of rounds? \\
			No good weak classifier left?

			\end{tabular}} ;

		\node [process, below of=stop, node distance = 15em] (updateWeights) {\begin{tabular}{c}
			Update weights \\
			$w_{new} = \left\{
			\begin{array}{ll}
				\frac{1}{2}\times \frac{1}{1-\epsilon_{best}}\times w_{old} \\
				\text{if point is}                                          \\
				\text{classified correctly}                                 \\
				                                                            \\
				\frac{1}{2}\times \frac{1}{\epsilon_{best}}\times w_{old}   \\
				\text {otherwise}                                           \\
			\end{array}
			\right. $
			\end{tabular}} ;

		\node [startstop, right of=updateWeights, node distance = 18em] (outputClsfr) {\begin{tabular}{c}
			Output the \\
			final classifier \\
			$H(x) = $ \\
			$sign(\sum\limits_{rounds}\alpha\times h_{best}(x))$
			\end{tabular}} ;

		\path [line] (initWeights) -- (calcError);
		\path [line] (calcError) -- (pickClsfr);
		\path [line] (pickClsfr) -- (stop);
		\path [line] (pickClsfr) -- (calcAlpha);
		\path [line] (stop) -- node [left] {No} (updateWeights);
		\path [line] (updateWeights) --++ (-12em,0em) |- (calcError);
		\path [line] (stop) -| node [below, near start] {Yes} (outputClsfr.north);

	\end{tikzpicture}
\end{figure}

\section{Example}

\begin{figure}[htbp]
	\centering
	\begin{tikzpicture}
		\tikzstyle {point line} = [line width=0.15em]

		\draw[-latex] (0,0) -- (6.5,0) node[right]{x};
		\draw[-latex] (0,0) -- (0,4.5) node[left]{y};

		\draw[help lines] (0,0) grid (6.5,4.5);

		\foreach \x in {1, 3, 5}
		\foreach \y in {1, 3}
		{
			\pgfmathsetmacro{\l}{\x - 0.3}
			\pgfmathsetmacro{\r}{\x + 0.3}

			\draw[point line] (\l,\y) -- (\r,\y);
		}

		\foreach \x in {1, 3, 5}
		{
			\draw[point line] (\x,3.3) -- (\x, 2.7);
		}

		\draw[point line] (1,1.3) -- (1, 0.7);

		\draw (1, 3) node [below right] {\textbf{A}};
		\draw (3, 3) node [below right] {\textbf{B}};
		\draw (5, 3) node [below right] {\textbf{C}};
		\draw (1, 1) node [below right] {\textbf{D}};
		\draw (3, 1) node [below right] {\textbf{E}};
		\draw (5, 1) node [below right] {\textbf{F}};

		\foreach \x in {1, 2, 3, 4, 5, 6}
		{
			\draw (\x, 0) node [below] {$\x$}	    ;
		}

		\foreach \y in {1, 2, 3, 4}
		{
			\draw (0, \y) node [left] {$\y$}	    ;
		}

	\end{tikzpicture}

\end{figure}

Following weak classifiers are considered. Their error points are shown below:

\FloatBarrier
\begin{table}[htbp]
	\centering
	\begin{tabular}{|c|c|}
		\toprule
		\textbf{Weak Classifier} & \textbf{Error Points}  \\
		\midrule
		$x >= 2$                 & \textbf{A, D, E, F}    \\
		$x < 2$                  & \textbf{B, C}          \\
		$x >= 4$                 & \textbf{A, B, D, F}    \\
		$x < 4$                  & \textbf{C, E}          \\
		$x >= 6$                 & \textbf{A, B, C, D}    \\
		$x < 6$                  & \textbf{E, F}          \\
		$y >= 2$                 & \textbf{D}             \\
		$y < 2$                  & \textbf{A, B, C, E, F} \\
		$y >= 4$                 & \textbf{A, B, C, D}    \\
		$y < 4$                  & \textbf{E, F}          \\
		\hline
	\end{tabular}
\end{table}

\newcommand*\circled[1]{\tikz[baseline=(char.base)]{
	\node[shape=circle,draw,inner sep=2pt] (char) {#1};}}

\subsection{Iteration 1}
At the start, each point has an equal weight of $1/6$ since there are 6 points.

\FloatBarrier
\begin{table}[htbp]
	\centering
	\begin{tabular}{|c|c|c|c|c|c|c|}
		\toprule
		\textbf{Point} & \textbf{A} & \textbf{B} & \textbf{C} & \textbf{D} & \textbf{E} & \textbf{F} \\
		\midrule
		\textbf{Error} & 1/6        & 1/6        & 1/6        & 1/6        & 1/6        & 1/6        \\
		\hline
	\end{tabular}
\end{table}
~\\

The error points and their corresponding weights determine the error rate of a particular weak classifier. The error rate for each classifier is shown below.

\FloatBarrier \clearpage
\begin{table}[htbp]
	\centering
	\begin{tabular}{|c|c|}
		\toprule
		\textbf{Weak Classifier} & \textbf{Error Rate} \\
		\midrule
		$x >= 2$                 & 2/3                 \\
		$x < 2$                  & 1/3                 \\
		$x >= 4$                 & 2/3                 \\
		$x < 4$                  & 1/3                 \\
		$x >= 6$                 & 2/3                 \\
		$x < 6$                  & 1/3                 \\
		$y >= 2$                 & \circled{1/6}       \\
		$y < 2$                  & 5/6                 \\
		$y >= 4$                 & 2/3                 \\
		$y < 4$                  & 1/3                 \\
		\hline
	\end{tabular}
\end{table}

$y >= 2$ is chosen as the best weak classifier since it has the minimum error rate. $\alpha_1$ is calculated as follows:
\begin{align*}
	\alpha_1 & = \frac{1}{2} \times ln(\frac{1-1/6}{1/6}) \\
	         & = \frac{1}{2} \times ln(5)
\end{align*}

\subsection{Iteration 2}
The weights are now updated as per flow chart above,

\FloatBarrier
\begin{table}[htbp]
	\centering
	\begin{tabular}{|c|c|c|c|c|c|c|}
		\toprule
		\textbf{Point} & \textbf{A} & \textbf{B} & \textbf{C} & \textbf{D} & \textbf{E} & \textbf{F} \\
		\midrule
		\textbf{Error} & 1/10       & 1/10       & 1/10       & 1/2        & 1/10       & 1/10       \\
		\hline
	\end{tabular}
\end{table}

An interesting fact is that the sum of updated weights of the points misclassified by the chosen classifier $y >= 2$ (\textbf{D}) is equal to 1/2 and so the sum of updated weights of the points correctly classified (\textbf{A, B, C, E, F}) is also 1/2.
\begin{align*}
	Error(\textbf{D})                                      & = 1/2                              \\
	\sum\limits_{P \in \{\textbf{A, B, C, E, F}\}}Error(P) & = 1/10 + 1/10 + 1/10 + 1/10 + 1/10 \\
	                                                       & = 1/2
\end{align*}

Error rates are updated as follows:

\FloatBarrier\clearpage
\begin{table}[htbp]
	\centering
	\begin{tabular}{|c|c|}
		\toprule
		\textbf{Weak Classifier} & \textbf{Error Rate} \\
		\midrule
		$x >= 2$                 & 4/5                 \\
		$x < 2$                  & \circled{1/5}       \\
		$x >= 4$                 & 4/5                 \\
		$x < 4$                  & 1/5                 \\
		$x >= 6$                 & 4/5                 \\
		$x < 6$                  & 1/5                 \\
		$y >= 2$                 & 1/2                 \\
		$y < 2$                  & 1/2                 \\
		$y >= 4$                 & 4/5                 \\
		$y < 4$                  & 1/5                 \\
		\hline
	\end{tabular}
\end{table}

$x < 2$ is chosen as the best weak classifier since it has the minimum error rate (for breaking tie, classifier occuring first in the above list is chosen).
$\alpha_2$ is calculated as follows,
\begin{align*}
	\alpha_2 & = \frac{1}{2} \times ln(\frac{1-1/5}{1/5}) \\
	         & = \frac{1}{2} \times ln(4)
\end{align*}

\subsection{Iteration 3}

Weights are again updated as follows:

\FloatBarrier
\begin{table}[htbp]
	\centering
	\begin{tabular}{|c|c|c|c|c|c|c|}
		\toprule
		\textbf{Point} & \textbf{A} & \textbf{B} & \textbf{C} & \textbf{D} & \textbf{E} & \textbf{F} \\
		\midrule
		\textbf{Error} & 1/16       & 1/4        & 1/4        & 5/16       & 1/16       & 1/16       \\
		\hline
	\end{tabular}
\end{table}

Given that (\textbf{B, C}) are misclassified by $x<2$ and points (\textbf{A, D, E, F}) are correctly classified; notice again that,

\begin{align*}
	\sum\limits_{P \in \{\textbf{B, C}\}}Error(P)       & = 1/4 + 1/4                 \\
	                                                    & = 1/2                       \\
	\sum\limits_{P \in \{\textbf{A, D, E, F}\}}Error(P) & = 1/16 + 5/16 + 1/16 + 1/16 \\
	                                                    & = 1/2
\end{align*}

Updated error rates look like this,

\FloatBarrier\clearpage
\begin{table}[htbp]
	\centering
	\begin{tabular}{|c|c|}
		\toprule
		\textbf{Weak Classifier} & \textbf{Error Rate} \\
		\midrule
		$x >= 2$                 & 1/2                 \\
		$x < 2$                  & 1/2                 \\
		$x >= 4$                 & 11/16               \\
		$x < 4$                  & 5/16                \\
		$x >= 6$                 & 7/8                 \\
		$x < 6$                  & \circled{1/8}       \\
		$y >= 2$                 & 5/16                \\
		$y < 2$                  & 11/16               \\
		$y >= 4$                 & 7/8                 \\
		$y < 4$                  & 1/8                 \\
		\hline
	\end{tabular}
\end{table}

$x < 6$ is chosen as the best weak classifier since it has the minimum error rate.
$\alpha_3$ is calculated as follows,
\begin{align*}
	\alpha_3 & = \frac{1}{2} \times ln(\frac{1-1/8}{1/8}) \\
	         & = \frac{1}{2} \times ln(7)
\end{align*}

After three iterations, the resultant strong classifier is

\begin{align*}
	H = & sign(\frac{1}{2} \times ln(5) \times (y>=2) \\
	    & + \frac{1}{2} \times ln(4) \times (x<2)     \\
	    & + \frac{1}{2} \times ln(7) \times (x<6) )
\end{align*}

The classification of $H$ for each point is as follows,

\FloatBarrier
\begin{table}[htbp]
	\centering
	\begin{tabular}{|c|c|c|}
		\toprule
		\textbf{Point}   & \textbf{Calculation}                      & \textbf{Classification} \\
		\midrule
		\rule{0pt}{1ex}A & $sign(1/2 \times ln(5\times 4 \times 7))$ & $+$                     \\
		\rule{0pt}{1ex}B & $sign(1/2 \times ln((5 \times 7) / 4))$   & $+$                     \\
		\rule{0pt}{1ex}C & $sign(1/2 \times ln((5 \times 7) / 4))$   & $+$                     \\
		\rule{0pt}{1ex}D & $sign(1/2 \times ln((4 \times 7) / 5))$   & $+$                     \\
		\rule{0pt}{1ex}E & $sign(1/2 \times ln(7 / (5 \times 4)))$   & $-$                     \\
		\rule{0pt}{1ex}F & $sign(1/2 \times ln(7 / (5 \times 4)))$   & $-$                     \\
		\hline
	\end{tabular}
\end{table}

It is evident the $H$ classifies each point correctly after 3 iterations. Further iterations are hence terminated.

\section{Mathematics}

\subsection{Upper bound on training error}
\subsubsection{Step 1}

\begin{align*}
	Error(H_T) = \frac{1}{N} \times \sum\limits_{i} \left\{
	\begin{array}{ll}
	1 \text{\ if\ } y_i \neq H_T(x_i)                       \\
	0 \text{\ else}
	\end{array}
	\right.
\end{align*}

Let $H_T(x_i) = sign(f_T(x_i))$ where $f_T(x_i) = \sum\limits_{t}\alpha_t \times h_t(x_i)$

\begin{align*}
	Error(H_T) = \frac{1}{N} \times \sum\limits_{i} \left\{
	\begin{array}{ll}
	1 \text{\ if\ } y_i \times f_T(x_i) <= 0                \\
	0 \text{\ else}
	\end{array}
	\right.
\end{align*}

\FloatBarrier
\begin{figure}[htbp]
	\centering
	\begin{tikzpicture}
		\datavisualization [school book axes,
			visualize as smooth line/.list={func},
			func={style={line width=0.15em}},
			y axis={label={y}},
		x axis={label={x = $y_i \times f_T(x_i)$}} ]

		data [set=func, format=function] {
			var x : interval [-1:3] samples 100;
			func y = e^(-\value{x});
		};
		\draw [line width=0.15em] (-1.25, 1) -- (0, 1);
		\draw [line width=0.15em, <-, >=stealth] (0, 0) -- (3, 0);

		\node at (-3, 1) {\begin{tabular}{c}
			$y = 1\ \text{if}\ x \leq 0$ \\
			$0\ \text{else}$
			\end{tabular}};
		\node at (-1, 3) {$y=e^{-x})$};
	\end{tikzpicture}
\end{figure}

\begin{align}
	Error(H_T) \leq \frac{1}{N} \times \sum\limits_{i} e^{-y_i \times f_T(x_i)}
\end{align}

\subsubsection{Step 2}

\begin{align*}
	w_{t+1}(i) = \frac{1}{2} \times w_t(i) \left\{
	\begin{array}{ll}
	\frac{1}{1-\epsilon_{t}}\ \text{if}\ y_i = h_t(x_i) \\
	\frac{1}{\epsilon_{t}}\ \ \ \ \text{else}           \\
	\end{array}
	\right.
\end{align*}

\begin{align*}
	w_{t+1}(i) = \frac{w_t(i)}{2\times \sqrt[]{\epsilon_t \times (1- \epsilon_t)}} \left\{
	\begin{array}{ll}
	\sqrt[]{\frac{\epsilon_t}{1-\epsilon_t}}\ \text{if}\ y_i = h_t(x_i)                    \\
	\sqrt[]{\frac{1-\epsilon_t}{\epsilon_t}}\ \text{else}                                  \\
	\end{array}
	\right.
\end{align*}

\begin{align*}
	w_{t+1}(i) = \frac{w_t(i)}{2\times \sqrt[]{\epsilon_t \times (1- \epsilon_t)}} \times e^{-\alpha_t \times y_i \times h_t(x_i)}
\end{align*}

\begin{align*}
	w_{t+1}(i) = \frac{1}{2\times \prod\limits_t{\sqrt[]{\epsilon_t \times (1- \epsilon_t}})} \times e^{-y_i \times f_t(x_i)} \times \frac{1}{N}
\end{align*}

Transposing and replacing $t$ by $T$,

\begin{align*}
	\frac{1}{N} \times e^{-y_i \times f_T(x_i)}  = 2 \times w_{T+1}(i) \times \prod\limits_t{\sqrt[]{\epsilon_t \times (1- \epsilon_t}})
\end{align*}

Summing over i,

\begin{align*}
	\sum\limits_i \frac{1}{N} \times e^{-y_i \times f_T(x_i)}  = 2 \times \prod\limits_t{\sqrt[]{\epsilon_t \times (1- \epsilon_t}}) \times \sum\limits_i w_{T+1}(i)
\end{align*}

Since sum of weights is one at every round,

\begin{align}
	\frac{1}{N} \times \sum\limits_i  e^{-y_i \times f_T(x_i)}  = 2 \times \prod\limits_t{\sqrt[]{\epsilon_t \times (1- \epsilon_t}})
\end{align}

\subsubsection{Step 3}

Using (1) and (2)

\begin{align*}
	Error(H_T) \leq 2 \times \prod\limits_t{\sqrt[]{\epsilon_t \times (1- \epsilon_t}})
\end{align*}

Using $\gamma_t = (1/2 - \epsilon_t)$

\begin{align*}
	Error(H_T) \leq 2 \times \prod\limits_t{\sqrt[]{1/4 - \gamma_t^2}}
\end{align*}

\begin{align*}
	Error(H_T) \leq \prod\limits_t{\sqrt[]{1 - 4\gamma_t^2}}
\end{align*}

Since $e^x \geq (1+x)$ for all real values of $x$,

\begin{align*}
	Error(H_T) \leq \prod\limits_t{e^{-2\gamma_t^2}}
\end{align*}

\begin{align*}
	Error(H_T) \leq e^{-2\sum\limits_t{\gamma_t^2}}
\end{align*}

Since $\sum\limits_t{\gamma_t^2}$ monotonically increases with each iteration, $Error(H_t)$ monotonically decreases exponentially.

\end{document}


\documentclass[compsoc,conference,a4paper,10pt,times]{IEEEtran}
\IEEEoverridecommandlockouts
% The preceding line is only needed to identify funding in the first footnote. If that is unneeded, please comment it out.
\usepackage{cite}
\usepackage{amsmath,amssymb,amsfonts}
\usepackage{algorithmic}
\usepackage{graphicx}
\usepackage{textcomp}
\usepackage{bmpsize}
\usepackage{xcolor}
\usepackage{lipsum}
\usepackage{minted}
\usepackage[colorlinks=true,urlcolor=black]{hyperref}
\def\BibTeX{{\rm B\kern-.05em{\sc i\kern-.025em b}\kern-.08em
    T\kern-.1667em\lower.7ex\hbox{E}\kern-.125emX}}
\begin{document}

\title{Machine Checked Properties of the Schulze Method}

\author{\IEEEauthorblockN{Mukesh Tiwari}
\IEEEauthorblockA{\textit{ School of Computing and Information Systems} \\
\textit{University of Melbourne}\\
Melbourne, Australia \\
mukesh.tiwari@unimelb.edu.au}
\and
\IEEEauthorblockN{Dirk Pattinson}
\IEEEauthorblockA{\textit{Research School of Computer Science} \\
\textit{Australian National University}\\
Canberra, Australia\\
dirk.pattinson@anu.edu.au}
}

\maketitle

\begin{abstract}
The correctness of electronic vote-counting software is
crucial in establishing the trust in electronic voting.
However, most vote-counting programs, used in
various jurisdiction for legally binding election, establish
correctness by means of testing which is not sufficient, and often
fails to identify rare corner cases.
We argue that legally binding vote-counting software
should be formally verified and their correctness should be
evaluated against some well established framework from social choice theory.
\footnote{DP: I don't see the relation to arrow's theorem here? \textcolor{ blue}{MT: I was trying to give an example of one such possible
framework to evaluate preferential voting schemes, but I have removed to avoid any potential confusion. }}

In this work,
we give machine checked formal proofs that our Coq implementation of the Schulze method,
a preferential voting method,
follows the Condorcet winner property. We leave the formal machine-checked proof of
other properties, e.g., reversal symmetry, Pareto, monotonicity, etc., for future work.
This is, to the best of our knowledge, the first machine-checked proof of
properties of the Schulze method implementation, and in fact, any preferential vote-counting
implementation.

\end{abstract}

\begin{IEEEkeywords}
formal method, electronic voting, Schulze method,
Condorcet winner, Coq theorem prover
\end{IEEEkeywords}

\section{Introduction}
    The Schulze method \cite{Schulze:2011:NMC}, a preferential
    voting method, has gained popularity in recent years
   when it comes to electing the candidates of many open source
    software communities, Wikipedia, and the Pirate Parties in
    various countries. At the time of writing,
    is used by more  than  60 organizations  with  more  than  900,000  eligible
    members  in  total \cite{schulze2020schulze}. One particular reason for this popularity is that it
    enjoys many desirable properties that have been  formulated in
    social choice theory.
    Many of these are already established in the Schulze's original paper \cite{Schulze:2011:NMC}, e.g., Condorcet winner, Pareto, reversal symmetry, monotonicty,
    etc. Moreover, it fails on independence of
    irrelevant alternatives (IIA) criterion, a consequence of the impossibility theorem \cite{arrow1950difficulty} which states that no preferential voting
    method can have all the properties.

    In this work, we establish that our implementation of Schulze method \cite{Pattinson:2017:SVE}
    conforms to the Condorcet winning criterion. It is ongoing work and in
    future, we would like to establish that our implementation follows all the other properties,
    e.g. reversal symmetry, Pareto, monotonicity, etc.
    More importantly, it would be interesting to establish that our implementation
    fails on IIA criterion. The
    source code for this ongoing work can be accessed from the GitHub
    repo\footnote{\url{https://github.com/mukeshtiwari/Schulzeproperties/blob/master/Schulzeprop.v}}

    \section{The Schulze Method}
    In this section, we give a brief overview of the Schulze method and
    necessary formalisation details to make it self-contained. We invite the
    curious reader to read our paper \cite{Pattinson:2017:SVE} for more details.

    The  method itself rests on the relative margins between two
    candidates, i.e. the number of voters that prefer one candidate
    over another. The margin induces an ordering between candidates,
    where a candidate $c$ is more preferred than $d$ if more voters
    prefer $c$ over $d$ than vice versa. One can construct simple
    examples (see e.g. \cite{Rivest:2010:OSW}) where this order does
    not have a maximal element (a so-called Condorcet Winner).
    Schulze’s observation is that this ordering can be made
    transitive by considering sequences of candidates (called
    paths).  Given candidates $c$ and $d$, a path between $c$ and
    $d$ is a
    sequence of candidates $p= (c,c_{1}, \dots ,c_{n},d)$ that joins
    $c$ and $d$, and the \emph{strength} of a path is the minimal margin
    between adjacent nodes. This induces the generalised margin
    between candidates $c$ and $d$ as the strength of the strongest path
    that joins $c$ and $d$.  A candidate $c$ then wins a Schulze count if
    the generalised margin between $c$
    and any other candidate $d$ is at least as large as the
    generalised margin between $d$ and $c$. It is known that every
    election has a winner, but the winner may not be uniquely
    determined (e.g. in the case where no votes have been cast at
    all).
    In more detail:

\begin{enumerate}

\item Consider an election with a set of $t$ candidates
    $C$ = $\{c_1,\dots,c_t\}$ and
	a set of $n$ votes $P$ = $\{b_1,\dots,b_n\}$. A vote
	is a function $b: C \rightarrow \mathbb{N}$ that
	assigns a natural
	number (the preference) to each candidate.  Note that two
  candidates may receive the same preference.
	We recover a strict total
	preorder $<_b$ on the candidates by setting $c <_b d$ if $b(c) > b(d)$, i.e.
	candidate $c$ is less preferred over candidate $d$ if the natural number $b(c)$ is greater
	than the natural number $b(d)$.

\item We construct a margin matrix $\mathrm{marg} : C \times C \to \mathbb{Z}$ as follows:
    given two candidates $c, d \in C$, the \emph{margin} of $c$ over $d$ is
    the number of voters that prefer $c$ over $d$ minus the number of voters
    that prefer $d$ over $c$. In symbols:
\[
  \mathit{marg} (c, d) = \sharp \lbrace b \in P \mid c >_b d \rbrace -
            \sharp \lbrace b \in P \mid d >_b c \rbrace
\] where $\sharp$ denotes cardinality.

\item A directed \emph{path} from
candidate $c$ to candidate $d$ is a sequence $p \equiv c_0, \dots, c_{w+1}$
of candidates with $c_0 = c$ and $c_{w+1} = d$ ($w \geq 0$), and the
\emph{strength}, $\mathrm{st}$, of path $p$ is the minimum margin of adjacent
nodes, i.e.
\[ \mathrm{st}(c_0, \dots, c_{w+1}) = \min \lbrace \mathrm{marg} (c_i, c_{i+1}) \mid 0
\leq i \leq w \rbrace. \]
\item  A generalised margin matrix, $M$, denote the strength of the strongest path
	between two candidates, i.e.
	\[ M(c, d) = \max \lbrace \mathrm{st} (p) : p \text{ is path from } c \text{ to } d\rbrace \]

\item The winning set  is defined as
 \[ W =  \lbrace c \in C : \forall d \in C \setminus \{c\}, M (c, d) \geq M (d, c) \rbrace\]

\end{enumerate}

Our Coq formalisation models the set of candidates as a type.
Moreover, it postulates that the type of candidates
is finite and non-empty with decidable equality. For our purpose,
the easiest way of stipulating that a type be finite is to require existence of a
list containing all inhabitants of this type \cite{10.1145/2808098.2808102}.

 \begin{minted}{coq}
Parameter cand : Type.
Parameter cand_all : list cand.
Hypothesis cand_fin :
 forall c: cand, In c cand_all.
Hypothesis cand_not_nil :
 cand_all <> nil.
Hypothesis dec_cand :
 forall n m : cand, {n = m} + {n <> m}.

\end{minted}

One easy way to achieve all of the above is to implement
\texttt{cand} as an indictive type with one nullary constructor for
each candidate.

We define a boolean function (step 5) that determines
(the Schulze) election winners based on
the generalised margin matrix (step 4). ($M \text{ } \mathrm{marg} \text{ }
(\mathrm{length} \text{ } \mathrm{cand\_all}) \text{ } c \text{ } d$
in the $\mathrm{schulze\_winner}$ definition is Coq encoding of the generalised margin matrix,
$M \text{ } (c, \text{ }d)$, defined in step 4. The syntactic differences between these two
notations do not matter for this discussion.)
\footnote{DP: which syntactic differences? \textcolor{ blue}{MT: I am talking about $M \text{ } \mathrm{marg} \text{ }
(\mathrm{length} \text{ } \mathrm{cand\_all}) \text{ } c \text{ } d$  and  $M \text{ } (c, \text{ }d)$}}
\footnote{DP: why a boolean function and not a proposition? \textcolor{blue}{MT: Nothing specific about the boolean function but I preferred it
because it defines the Schulze winner in terms of generalised margin matrix, which is already explained above (step 4).  Therefore, the reader can
clearly establish the Coq definition and the explanation we gave in step 4, which may or may not be the case in Prop definition.}}
 \begin{minted}{coq}
Definition schulze_winner
  (marg : cand * cand -> Z)
  (c : cand) := forallb (fun d =>
  (M marg (length cand_all) d c) <=?
  (M marg (length cand_all) c d))
  cand_all.
\end{minted}

\section{Properties of Schulze Method}
	 We have a boolean function,  \textit{schulze\_winner},  that
	 elects the winner,  the key question is that how do we know that
	 this winner is indeed the real winner,  intended by the voters, and
	 not because of the software bug in the implemetation.  In our
	 original paper, we have given two definitions of
	 winners, one in Prop (logical) and one in Type (computational) and
	 proved that both implemetations are equivalent.
   \footnote{DP: How do they relate to the boolean function above? \textcolor{ blue}{MT:  It seems that this section is edited but previously in this section,
   I had explained the rationale for Prop level and Type level.  Moreover,  there was a paragraph explaining the connection between boolean function, schulze\_winner, and
   type-level function,  wins\_type. }}
   \footnote{DP: the typle level definition can't be understood
   without context, e.g. what does co-closed mean?  \textcolor{blue}{MT: I have written a very abstract explanation of coclosed, but we want to expand on it, then it would be better to explain the whole thing and I should retract the claim
   about inviting the reader to read our paper from ITP.}}

\begin{minted}{coq}
Definition wins_prop (c: cand) : Prop :=
 forall d: cand, exists k: Z,
  Path k c d /\
 (forall l, Path l d c -> l <= k)

Definition wins_type c : Type :=
 forall d : cand, existsT (k : Z),
 ((PathT k c d) *
  (existsT (f : (cand * cand) -> bool),
  f (d, c) = true /\ coclosed (k + 1) f))
\end{minted}

\noindent
The definition of \textit{coclosed} asserts that
paths from every candidate to the winner
is not stronger than the vice versa, i.e.
if a candidate $c$ is the winner and the strength
of the strongest path from $c$ to a candidate,  say, $d$ is $k$,
then all the paths from $d$ to $c$ will less than or equal to $k$.

\begin{minted}{coq}
Lemma wins_prop_type : forall c,
 wins_prop c -> wins_type c.
Proof.  ... Qed.

Lemma wins_type_prop : forall c,
 wins_type c -> wins_prop c.
Proof.  ... Qed.
\end{minted}

The reason for two (rather than one) definitions of winning is that
the propositional formulation is easier to inspect for correctness.
Then again, the type level definition carries more information that
can be extracted, whereas the type-level definition carries
enough information that can be individually verified to corroborate
the correctness of the run of the algorithm, given the initial
datas\footnote{\textcolor{ blue}{MT: It is very condensed version of what I wrote previously, but  I did not understand, "given the initial datas". What is initial datas?}.}.
of\footnote{\textcolor{ blue}{MT: It does not make any sense from here and possibly can go away because you have already given the
 rationale for having two definitions, one in Prop and one in Type, above, though very condensed.}} our formalisation was two fold: i) extracting an OCaml
code from it and using the OCaml code
to count the ballots from real world elections and ii)
making it accessible to everyone.
\footnote{DP: What do you mean by this? \textcolor{ blue}{MT:  You have edited this section and the point, I am trying to convey by saying that
 our goal is make the formalisation accessible for everyone,  is  that the reader, having some basic understanding of logic,
 has to inspect our definitions in the Prop and convince herself that it indeed captures the notion of winner (or loser).  } }
To achieve the
first goal, we use an elaborate  definition of winning at the type
level,
and for the second goal, we have a (simple) definition in Prop.
All the reader has to do is inspect the simple logical defintion
\textit{wins\_prop} to ensure that it correctly captures the notion
of winner,  without understanding the more complex
definition of \textit{wins\_type}.  The proof that these two definitions
are equivalent is established in Coq, so the reader
has to do is replay the proofs of  \textit{wins\_prop\_type} and
\textit{wins\_type\_prop}.  Coq's extraction mechanism erases all the (logical) terms in sort Prop while
keeps all the (computational) terms in sort Type.

 \subsection{Condorcet Winner}
	A (weak) \textit{Condorcet winner} is a candidate who beats or ties every other candidate in a
	pairwise comparison, also known as head to head competition.
	Recall from the previous section that the margin matrix,
  $\mathrm{marg}$,
	stores exactly this data for every pair of candidates.
	Therefore, we define the Condorcet winner in Coq:

\begin{minted}{coq}
Definition condorcet_winner
 (marg : cand * cand -> Z)
 (c : cand) := forall d,
 marg (c, d) >= 0.
\end{minted}
\footnote{DP: comment on strict Condorcet vs weak Condorcet
relatively to the margin $\geq$ or $>$? \textcolor{blue}{MT: I tweaked it to say that we are talking about weak Condorcet winner.}}

  Informally, the definition,  $\mathrm{condorcet\_winner}$ states that
  if a candidate $c$  is the Condorcet winner, then they are
  ranked equal or higher against
  every other candidate in more ballots than the vice versa.
  Our goal is to establish that if there is a
  Condorcet winner, then the Schulze method
  elects it. We formally state our intent
  in Coq as:

\begin{minted}{coq}
 Lemma condorcet_winner_implies_winner
    (marg : cand * cand -> Z)
    (c : cand) :
    condorcet_winner marg c ->
    schulze_winner marg c = true.
Proof.  ... Qed.
\end{minted}
\footnote{DP: Why use the boolean function? And if the boolean
function is used, why are the propositional and type level functions
given earlier? \textcolor{ blue}{MT: There is nothing specific about boolean function and we can replace it by the Prop definition (or the Type definition).  The reason for
boolean fuction is that in the beginning I introduced the definition of Schulze's Winner as a boolean function to the reader, so I continued with it to let the reader make a connection
between the definition,  schulze\_winner, I gave previously and Condorcet winner (but I see that our definition of Condorcet winner is in Prop). }}
\footnote{DP: Proof terms omitted can be omitted :-) \textcolor{ blue}{MT:  Replaced by triple dots to convey the proof terms}}

 The proof of $condorcet\_winner\_implies\_winner$ hinges on the two key observations:

 \begin{enumerate}
  \item If a candidate $c$ is the Condorcet winner, then the generalised margin (matrix)
  between $c$
  and every other candidate, say, $d$ would be greater than or equal to 0, i.e.
  $M \text{ } (c, \text{ }d) \geq 0$.

  \item If a candidate $c$ is the Condorcet winner, then the generalised margin  (matrix)
  between every other candidate, say, $d$ and $c$ would be less than or equal to 0,
  $M \text{ } (d, \text{ }c) \leq 0$.
 \end{enumerate}

 These two key observations make the proof of the lemma
 $\mathrm{condorcet\_winner\_implies\_winner}$
 trivial because we have $M \text{ } (d, \text{ }c) \leq 0$  and
  $M \text{ } (c, \text{ }d) \geq 0$, hence $M \text{ } (d, \text{ }c)  \leq
   M \text{ } (c, \text{ }d)$. Intuitively,
 if a candidate $c$ is the Condorcet winner, then the strongest path between her and every other
 candidate, say, $d$ would be either a direct path or a more stronger path
 via some other intermediate candidates (proof by induction on the path length).
 In both cases, we have the generalised margin between
 $c$ and the other candidate $d$ is greater than or equal to 0.
 Similarly, for the second observation. We encode these two key observations in
 Coq:

 \begin{minted}{coq}
Lemma first_key_observation :
 forall c d n marg,
 condorcet_winner c marg ->
 M marg n c d >= 0.
Proof.   ...  Qed.

Lemma second_key_observation :
 forall c d n marg,
 condorcet_winner c marg ->
 M marg n d c <= 0.
Proof.  ...  Qed.
 \end{minted}

 \footnote{DP: again 'proof terms omitted' doesn't convey
 information.  \textcolor{blue}{ MT:  Addressed }}

Proof of the last two lemmas is by induction on the path length, i.e. n \cite{Carre:1971:ANR}.

\subsection{Reversal Symmetry}\footnote{It is not complete and still ongoing.}
 \textit{Reversal symmetry} is a voting method criterion which states that if the
 voting method has produced a unique
  winner, say, $c$ based on the cast ballots, then $c$ should not be elected if the
 individual choices were reversed.
 In context of the Schulze method, we first need to define the unique winner, and ballot reversal.

 \begin{minted}{coq}
 Definition unique_winner
 (marg : cand * cand -> Z)
 (c : cand) :=
 schulze_winner marg  c = true /\
 (forall d, d <> c ->
  schulze_winner marg d = false).
\end{minted}
\noindent
Informally, the definition of \textit{unique\_winner} states that a
candidate $c$ is a unique winner
if it wins the election and every candidate
other than $c$ loses the election.
We capture the ballot reversal in terms of margin matrix. For any given ballot set $P$,
the margin between two candidates $c$ and $d$ is:
\[
  \mathrm{marg}(c, d) = \sharp \lbrace b \in P \mid c >_b d \rbrace -
            \sharp \lbrace b \in P \mid d >_b c \rbrace
\]

\noindent
If we reverse the individual choices in every ballot, the new margin
matrix, denoted as $\mathrm{rev\_marg}$, would be:

\[
  \mathrm{rev\_marg}(c, d) = -  \mathrm{marg} (c, d)
\]

\noindent
The connection between $\mathrm{rev\_marg}$ and $\mathrm{marg}$ is very intuitive, but it can be understood
by considering a hypothetical single ballot election. Let's assume that we have
a single ballot $(A, 1); (B, 2); (C, 3)$ and the interpretation is
that $A$ is strictly preferred over $B$, and $B$ is strictly preferred over $C$
(but we do not need strict preferences to have this property).  The margin matrix
constructed from this ballot is:

\[
\bordermatrix{ & A & B & C \cr
      A & 0 & 1 & 1 \cr
      B & -1 & 0 & 1 \cr
      C & -1 & -1 & 0 }
      \]

\noindent
After reversing the original ballot, we get $(A, 3); (B, 2); (C, 1)$ and
the margin matrix is:
\[
\bordermatrix{ & A & B & C \cr
      A & 0 & -1 & -1 \cr
      B & 1 & 0 & -1 \cr
      C & 1 & 1 & 0 }
      \]

\noindent
It is clearly evident from this example that the
connection between $\mathrm{rev\_marg}$ and $\mathrm{marg}$  holds.
We capture this connection in Coq as:

\begin{minted}{coq}
Definition rev_marg
   (marg : cand -> cand -> Z)
   (c d : cand) := -marg c d.
\end{minted}

\noindent

Finally, the reversal symmetry property can be expressed in Coq as:
\begin{minted}{coq}
Lemma reversal_symmetry : forall marg c,
  unique_winner marg c ->
  schulze_winner (rev_marg marg) c =
  false.
Proof.
 (* still ongoing *)
\end{minted}

\noindent
The lemma $\mathrm{reversal\_symmetry}$ expresses that if a candidate $c$ is the unique
winner, with respect to $\mathrm{marg}$ computed from some ballot set $P$, then she is
a loser with respect to $\mathrm{rev\_marg}$, computed from reversing all the entries
in the ballot set $P$.

\noindent
The proof this lemma is fairly straight forward \cite{Schulze:2011:NMC}, but
Schulze's original paper assumes a key property which turns out to be very difficult to prove,
at least in our encoding, in Coq. The key property is: if $M$
is the generalised margin
matrix (step 4), computed using the margin matrix $\mathrm{marg}$
and $\mathrm{M\_rev}$ is the generalised
margin matrix, computed using the margin matrix $\mathrm{rev\_marg}$, then
$M\_M\_\mathrm{rev}: \forall \text{ } c \text{ } d,  M(c, d) =
M\_\mathrm{rev} (d, c)$ holds. Currently,
we do not have the proof of $M\_M\_\mathrm{rev}$ in Coq, but we managed to prove
another property, $\mathrm{path\_with\_rev\_marg}$
\footnote{DP: more detail. \textcolor{blue}{MT: explained more about it in the next line.}}.  It states that if there is a path from
$c$ to $d$ of strength $k$, with respect to $\mathrm{marg}$, then we have
a path of same strength $k$ from $d$ to $c$, with respect to
$\mathrm{rev\_marg}$.
If this path from $c$ to $d$ happens to be the strongest path (step 4),
then we can prove $M\_M\_\mathrm{rev}$ \footnote{The challenge in our encoding
is proving that the strength of the strongest path is $\geq  M(c, d)$ and
the strength of all paths is $\leq M(c, d)$ to infer the equality,
i.e. strength of the strongest path $= M(c, d)$}.  The lemma $\mathrm{path\_with\_rev\_marg}$ can be
combined with
some other properties to complete the proof of $M\_M\_\mathrm{rev}$.

\begin{minted}{coq}
Lemma path_with_rev_marg :
  forall k marg c d,
  Path marg k c d <->
  Path (rev_marg marg) k d c.
Proof.  ... Qed.
\end{minted}
\footnote{DP: proofs omitted doesn't add information \textcolor{ blue}{MT: replaced by triple dots}}

\noindent
$\mathrm{Path}$ is an inductive datatype that exactly captures the notion of
sequence of nodes between two candidates (step 3). More elaborately,
$\mathrm{Path} \text{ }k \text{ }marg \text{ }c \text{ }d$ a path $p$, sequence of candidates
$p= (c,c_{1}, \dots ,c_{w},d)$, that joins $c$ and $d$ and the strength of
p, $\mathrm{st}(p) =  \min \lbrace \mathrm{marg} (c_i, c_{i+1}) \mid 0
\leq i \leq w \rbrace$, is greater than or equal to $k$.

\noindent

\bibliography{thesis}
\bibliographystyle{IEEEtran}

\end{document}


\subsection{2048}
\screenshot{plugins/images/ss-2048}{2048}{fig:2048}

2048 is a simple, addictive puzzle game played by moving tiles in around on a 4x4 grid. Tiles slide as far as possible in the direction chosen by the player each turn until they are stopped by either another tile or the edge of the grid. If two tiles of the same number collide while moving, they merge into a tile with the total value of the two tiles that collided. The resulting tile cannot merge with another the same move. After each move, a tile with the value of 2 or 4 is created in an empty spot on the grid.

The game is won when a tile with a value of 2048 is created, and the player loses when there are no more possible moves.

\note{On players with a small screen tiles with a value greater than 1000 are shortened
to ``1k'', ``2k'' and so forth (\emph{k} is the abbreviation of \emph{kilo},
which -- in computer talk -- means a multiple of 1024).}

\begin{btnmap}
  \PluginUp, \PluginDown, \PluginLeft, \PluginRight
  \opt{HAVEREMOTEKEYMAP}{& \PluginRCUp, \PluginRCDown, \PluginRCLeft, \PluginRCRight}
  & Slide tiles\\

  \PluginCancel
  \opt{HAVEREMOTEKEYMAP}{& \PluginRCCancel}
  & Go to menu\\
\end{btnmap}


\section{Nomenclature}

\begin{table}[htb!]
\centering
\begin{tabular}{|c|l|}
\hline
$x_i$ & Position of the center of mass of the differential element in the\\
& current configuration\\
\hline
$X_I$ & Position of the center of mass of the differential element in the\\
& reference configuration\\
\hline
$\xi_I$ & Position of the center of mass of the micro element in the\\
& current configuration w.r.t. the center of mass of the differential element\\
\hline
$\Xi_I$ & Position of the center of mass of the micro element in the\\
& reference configuration w.r.t. the center of mass of the differential element\\
\hline
$\sigma_{ij}$ & Unsymmetric Cauchy stress\\
\hline
$s_{ij}$ & Symmetric micro stress\\
\hline
$m_{ijk}$ & Higher order couple stress\\
\hline
$f_{i}$ & Body force density\\
\hline
$a_{i}$ & Acceleration\\
\hline
$\l_{ij}$ & Body force couple\\
\hline
$\omega_{ij}$ & Micro-spin inertia\\
\hline
\end{tabular}
\end{table}

\FloatBarrier


\newcommand{\Val}{\fun{Val}}
\newcommand{\POV}[1]{\ensuremath{\mathsf{PresOfVal}(\mathsf{#1})}}
\newcommand{\DBE}[2]{\ensuremath{\mathsf{DBE}({#1},~{#2})}}
\newcommand{\DGO}[2]{\ensuremath{\mathsf{DGO}({#1},~{#2})}}
\newcommand{\transtar}[2]{\xlongrightarrow[\textsc{#1}]{#2}\negthickspace^{*}}

\section{Properties}
\label{sec:properties}

This section describes the properties that the ledger should have. The goal is to
to include these properties in the executable specification to enable e.g.
property-based testing or formal verification.

\subsection{Preservation of Value}
\label{sec:preservation-of-value}

As visualized in Figure~\ref{fig:fund-preservation},
the total amount of lovelace in any given chain state
$\var{s}\in\ChainState$ is completely contained within the values of the six
variables:

\begin{tabular}{||l|l|l|l||}\hline\hline

  \textbf{Variable} & \textbf{Name in Figure~\ref{fig:fund-preservation}}
                    & \textbf{Nesting Inside Chain State} & \textbf{Kind} \\ \hline
  utxo & circulation & s.nes.es.ls.utxoSt & Map over Lovelace Values  \\ \hline
  deposits & deposits &  s.nes.es.ls.utxoSt & Lovelace Value ($\Coin$) \\ \hline
  fees & fees &  s.nes.es.ls.utxoSt & Lovelace Value ($\Coin$) \\ \hline
  rewards & reward accounts & s.nes.es.ls.dpstate.dstate  & Lovelace Value ($\Coin$)  \\ \hline
  treasury & treasury &  s.nes.es.acnt  & Lovelace Value ($\Coin$) \\ \hline
  reserves & reserves & s.nes.es.acnt & Map over Lovelace Values \\ \hline
  \hline
\end{tabular}

\noindent
Notice that $\var{deposits}$, $\var{fees}$, $\var{treasury}$, and $\var{reserves}$
are all single lovelace values, while $\var{utxo}$, and $\var{rewards}$ are
maps whose values are lovelace.

We define the \emph{Lovelace Value} of a given chain state as:
\begin{definition}[Lovelace Value]
  \label{def:val}
  \begin{equation*}
    \Val(s~\in~\var{State}) =
        \Val(\var{utxo}) +
            \Val(\var{deposits}) +
            \Val(\var{fees}) +
            \Val(\var{reserves}) +
            \Val(\var{treasury}) +
            \Val(\var{rewards})
  \end{equation*}
  where
  \begin{equation*}
      \Val(x \in \Coin) = x
  \end{equation*}
  \begin{equation*}
      \Val((\wcard\mapsto (y \in \Coin))^{*}) = \sum y
  \end{equation*}
\end{definition}

\noindent
For any state that is used in a given subtransition of $\mathsf{CHAIN}$,
we define $\Val{}$ in an analogous way, setting the value of any variable that is not explicitly
represented in the state to zero.
For example, given $\var{utxoSt}\in\UTxOState$,
\begin{equation*}
  \Val(\var{utxoSt}) =
  \left(\sum_{\wcard\mapsto(\wcard,~v)\in\var{utxo}}v\right) + \var{deposits} + \var{fees}
\end{equation*}

\noindent
The key property that we want to prove is that no semantic transition changes the value that
is captured in the state ($\Val{s}$).
This property is easy to state: intuitively,
the \emph{Lovelace Value}before the transition is the same as the
\emph{Lovelace Value} after that transition.

\begin{theorem}[Preservation of Value]
  \label{thm:chain-pres-of-value}
  For all environments $e$, blocks $b$, and states $s$, $s'$, if
  \begin{equation*}
    e\vdash s\trans{\hyperref[fig:rules:chain]{chain}}{b}s'
  \end{equation*}
  then
  \begin{equation*}
    \Val(s) = \Val(s')
  \end{equation*}
\end{theorem}

\noindent
We will prove the soundness of Theorem~\ref{thm:chain-pres-of-value} via a few lemmas.

\begin{lemma}
  \label{lemma:value-sum-pres-1}
  For any mapping $m:A\mapsto\Coin$ and set $s\in\powerset{A}$,
  \begin{equation*}
    \Val(\var{m}) = \Val(s\subtractdom m) + \Val(s\restrictdom m)
  \end{equation*}
\end{lemma}
\begin{proof}
  easy
\end{proof}

\begin{lemma}
  \label{lemma:value-sum-pres-2}
  For any mappings $m_1, m_2:A\mapsto\Coin$,
  if $\dom{m_1}\cap\dom{m_2}=\emptyset$,
  then
  \begin{equation*}
    \Val(m_1\cup m_2) = \Val(m_1) + \Val(m_2)
  \end{equation*}
\end{lemma}
\begin{proof}
  easy
\end{proof}

\begin{lemma}
  \label{lemma:utxo-pres-of-value}
  For all environments $e$, transactions $t$, and states $s$, $s'$, if
  \begin{equation*}
    e\vdash s\trans{\hyperref[fig:rules:utxo-shelley]{utxo}}{t}s'
  \end{equation*}
  then
  \begin{equation*}
    \Val(s) + w = \Val(s')
  \end{equation*}
  where $w = \fun{wbalance}~(\fun{txwdrls}~{t})$.
\end{lemma}

\begin{proof}
  The proof is essentially unfolding the definition of the predicate
  \begin{equation}
    \label{cons-is-prod}
    \consumed{pp}{utxo}{t} = \produced{pp}{stpools}{t}
  \end{equation}
  and applying a little algebra.
%
If we let:
  \begin{equation*}
    \begin{array}{r@{~=~}l}
      k & \keyRefunds{pp}{stkCreds}{t} \\
      f & \txfee{t} \\
      d & \totalDeposits{pp}{stpools}{(\txcerts{t})} \\
    \end{array}
  \end{equation*}
  then equation~\ref{cons-is-prod} can be rewritten as:
  \begin{equation*}
    \Val(\txins{t} \restrictdom{\var{utxo}}) + w + k = \Val(\outs{t}) + f + d
  \end{equation*}
  where $\outs{}$ is defined in Figure~\ref{fig:functions:utxo} and returns a value of type $\UTxO$.
  Therefore, moving $k$ to the right and adding $\txins{t} \subtractdom{\var{utxo}}$ to each side,
  \begin{equation*}
    \Val(\txins{t} \restrictdom{\var{utxo}}) + \Val(\txins{t} \subtractdom{\var{utxo}}) + w
    = \Val(\outs{t}) + f + d - k + \Val(\txins{t} \subtractdom{\var{utxo}})
  \end{equation*}
  (Though not needed for the proof at hand,
  note that $d-k$ is non-negative since the deposits will always be large enough to cover
  the current obligation. See Theorem~\ref{thm:non-neg-deposits}.)
%
  It then follows that:
  \begin{equation*}
    \begin{array}{r@{~=~}lr}
      \Val(\var{utxo}) + w
    & \Val(\outs{t}) + f + d - k + \Val(\txins{t} \subtractdom{\var{utxo}})
    & \text{(by Lemma~\ref{lemma:value-sum-pres-1})}
    \\
    & \Val((\txins{t} \subtractdom{\var{utxo}})\cup\outs{t}) + (d - k) + f
    & \text{(by Lemma~\ref{lemma:value-sum-pres-2})}
    \end{array}
  \end{equation*}
  Note that in order to apply Lemma~\ref{lemma:value-sum-pres-2} above,
  it must be true that $(\txins{t} \subtractdom{\var{utxo}})$ and $(\outs{t})$
  have disjoint domains, which follows from the uniqueness of the transaction IDs.

  Therefore, by adding the deposits and fees from $s$ to the equality above,
  it follows that $\Val(s) + w = \Val(s')$.
\end{proof}

\begin{lemma}
  \label{lemma:deleg-pres-of-value}
  For all environments $e$, transactions $c$, and states $s$, $s'$, if
  \begin{equation*}
    e\vdash s\trans{\hyperref[fig:delegation-rules]{deleg}}{c}s'
  \end{equation*}
  then
  \begin{equation*}
    \Val(s) = \Val(s')
  \end{equation*}
\end{lemma}

\begin{proof}
  The only variable with value in this transition is \var{rewards}.
  Only two of the rules in $\mathsf{DELEG}$ can change \var{rewards},
  namely $\mathsf{Deleg{-}Reg}$ and $\mathsf{Deleg{-}Dereg}$.
  However, $\mathsf{Deleg{-}Reg}$ only adds a zero value,
  and $\mathsf{Deleg{-}Dereg}$ only removes a zero value.
\end{proof}

\begin{lemma}
  \label{lemma:delegs-pres-of-value}
  For all environments $e$, certificates $\Gamma$, and states $s$, $s'$, if
  \begin{equation*}
    e\vdash s\trans{\hyperref[fig:rules:delegation-sequence]{delegs}}{\Gamma}s'
  \end{equation*}
  then
  \begin{equation*}
    \Val(s) = \Val(s') + w
  \end{equation*}
  where $w = \fun{wbalance}~(\fun{txwdrls}~{t})$,
  and $t$ is the transaction in the environment $e$.
\end{lemma}

\begin{proof}
  The proof is by induction on the length of $\Gamma$.
  Note that the only variable with value in this transition is \var{rewards}.

  \vspace{2ex}
  \noindent
  \emph{In the base case}, we look at the rule $\mathsf{Seq{-}delg{-}base}$.
  Since $\var{wdrls}\subseteq\var{rewards}$, then
  $\var{rewards} = \var{wdrls}\cup\var{(\var{rewards}\setminus\var{wdrls})}$.
%
  Therefore
  \begin{equation*}
    \begin{array}{r@{~=~}lr}
      \Val{(\var{rewards})}
      & \Val{(\var{rewards}\setminus\var{wdrls})} + \Val{(\var{wdrls})}
      & \text{by Lemma~\ref{lemma:value-sum-pres-2}}
      \\
      & \Val{(\var{rewards}\setminus\var{wdrls})} + w
      & \text{by definition}
      \\
      & \Val\left(\var{rewards}\unionoverrideRight\{(w, 0) \mid w \in \dom \var{wdrls}\}\right) + w
    \end{array}
  \end{equation*}
  Therefore $\Val(s) = \Val(s')$.

  \vspace{2ex}
  \noindent
  \emph{In the inductive case}, we look at the rule $\mathsf{Seq{-}delg{-}ind}$.
  In this case, the lemma then follows directly from Lemma~\ref{lemma:deleg-pres-of-value}.
\end{proof}

\begin{lemma}
  \label{lemma:poolreap-pres-of-value}
  For all environments $e$, epoch $\epsilon$, and states $s$, $s'$, if
  \begin{equation*}
    e\vdash s\trans{\hyperref[fig:rules:pool-reap]{poolreap}}{\epsilon}s'
  \end{equation*}
  then
  \begin{equation*}
    \Val(s) = \Val(s')
  \end{equation*}
\end{lemma}

\begin{proof}
  The $\mathsf{POOLREAP}$ value is contained in
  $\var{deposits}$, $\var{treasury}$, and $\var{rewards}$.
  Notice that $\var{unclaimed}$ is added to $\var{treasury}$
  and subtracted from the $\var{deposits}$.
  Moreover, $\var{refunded}$ is subtracted from $\var{deposits}$.
  (Note that $\var{deposits}-(\var{unclaimed}+\var{refunded})$
  is non-negative by Theorem~\ref{thm:non-neg-deposits}.)
  It therefore suffices to show that
  \begin{equation*}
    \begin{array}{r@{~=~}l}
    \Val(\var{rewards}\unionoverridePlus\var{refunds})
    & \Val(\var{rewards}) + \Val(\var{refunds})
    \\
    & \Val(\var{rewards}) + \var{refunded}
    \end{array}
  \end{equation*}
  But this is clear from the definition of $\unionoverridePlus$.
\end{proof}

\begin{lemma}
  \label{lemma:ru-pres-of-value}
  For every $(\Delta t,~\Delta r,~\var{rs},~\Delta f)$ in the range of $\fun{createRUpd}$,
  \begin{equation*}
    \Delta t + \Delta r + \Val(rs) + \Delta f = 0
  \end{equation*}
\end{lemma}

\begin{proof}
  In the definition of $\fun{createRUpd}$ in Figure~\ref{fig:functions:reward-update-creation},
  We see that:
  \begin{equation*}
    \begin{array}{r@{~=~}l}
      \var{rewardPot} & \var{feeSS} + \Delta r \\
      \var{R} & \var{rewardPot} - \Delta t_1 \\
      \Delta t_2 & R - \Val(\var{rs})\\
      \Delta t & \Delta t_1 + \Delta t_2 \\
    \end{array}
  \end{equation*}
  Therefore
  \begin{equation*}
    \begin{array}{r@{~=~}l}
      (\var{feeSS} + \Delta r) & \var{rewardPot} = R + \Delta t_1 = \Delta t_2 + \Val(rs) + \Delta t_1  \\
      0 & (\Delta t_1 + \Delta t_2 ) - \Delta r + \Val(rs)- \var{feeSS} \\
      0 & \Delta t - \Delta r + \Val(rs)- \var{feeSS} \\
    \end{array}
  \end{equation*}
  It then suffices to notice that $\fun{createRUpd}$ returns
  $(\Delta t,-~\Delta r,~\var{rs},~-\var{feeSS})$.
\end{proof}

\noindent

Note that Lemma~\ref{lemma:ru-pres-of-value} is not strictly need for the proof of
Theorem~\ref{thm:chain-pres-of-value}, since the $\mathsf{NEWEPOCH}$ transition
requires that $\Delta t + \Delta r + \Val(rs) + \Delta f = 0$ holds.
It does, however, give us confidence that the $\mathsf{CHAIN}$ transition can proceed.

We are now ready to prove Theorem~\ref{thm:chain-pres-of-value}.

\begin{proof}
  For a given transition $\mathsf{TR}$, let \POV{TR}
  be the statement:

  \begin{tabular}{l}
    for all environments $e$, signals $\sigma$, and states $s$, $s'$,
    $$
    $e\vdash s\trans{tr}{\sigma}s'~\implies~\Val(s) = \Val(s')$.
    $$
  \end{tabular}

  \noindent
  Our goal is to prove \POV{CHAIN}.
  Lemmas~\ref{lemma:utxo-pres-of-value} and \ref{lemma:delegs-pres-of-value} imply \POV{LEDGER},
  since $\mathsf{UTXOW}$ transforms state exactly as $\mathsf{UTXO}$ does.
  \POV{LEDGERS} then follows by straightforward induction on the length of $\Gamma$:
  the base case is trivial;
  and the inductive case follows directly from \POV{LEDGER}.
%
  \POV{SNAP} holds trivially, since it contains no value.
  Similarly, \POV{NEWPP} holds since $\var{diff}$ is added to $\var{reserves}$
  and subtracted from $\var{deposits}$.
  Therefore \POV{EPOCH} holds by Lemma~\ref{lemma:poolreap-pres-of-value}.
  \POV{MIR} holds since
  $\Val{i_{rwd}'}=\var{tot}$ in Figure~\ref{fig:rules:mir}.
  Morover, \POV{NEWEPOCH} holds in the presence of $\fun{applyRUpd}$
  since the transition requires $\Delta t + \Delta r + \Val(rs) + \Delta f = 0$.
  \POV{CHAIN} easily follows from this.
\end{proof}

\subsection{Non-negative Deposit Pot}  % TODO - this section is out of date due to no decaying deposits
\label{sec:non-negative-deposit-pot}

The \emph{deposit pot} (the variable $\var{deposits}$ in the UTxO State)
represents the amount of \emph{lovelace} that is set aside by the system as a whole for refunding deposits.
Deposits are added to this pot, which then decays exponentially over time,
and is also depleted by any refunded deposits.
At an epoch boundary, the decayed parts of any deposits (including, possibly, deposits for any transactions that will complete in future epochs)
will be distributed as additional \emph{rewards}, as described in~\cite{delegation_design}.
Since $\var{deposits}$ is only used to record the value of future refunds or rewards whose costs have
already been incurred, both it and any reward value will always be non-negative.
Note that there are two types of deposits which are recorded in the same pot: those for stake keys; and those for stake pools.
Stake keys are deregistered in the slot in which the deregistration certificates
is processed. Stake pools, however, are staged for retirement on epoch boundaries.
%
The following theorem ensures that the deposit pot is properly maintained
and will always be large enough to meet all of its obligations.

\begin{figure}[h!]
  \begin{tabular}{||l|l|l|l||}\hline\hline

    \textbf{Variable} & \textbf{Value}
                      & \textbf{Nesting Inside Chain State} & \textbf{Kind} \\ \hline
    deposits & 0 &  s.nes.es.ls.utxoSt & $\Coin$ \\ \hline
    stkCreds & $\emptyset$ & s.nes.es.ls.dpstate.dstate.stkCreds
             & $\StakeCreds$ ($\Credential\mapsto\Slot$)  \\ \hline
    stpools & $\emptyset$ & s.nes.es.ls.dpstate.pstate.stpools
            & $\StakePools$ ($\KeyHash\mapsto\Slot$)  \\ \hline
  \end{tabular}
  \caption{Initial Chain State}
  \end{figure}

\begin{theorem}[Non-negative Deposit Pot]
  \label{thm:non-neg-deposits}
  Let $n\in\N$ and $c_0\in\ChainState$ be a chain state in which $\var{deposits} ~=~0$, $\var{stkCreds}~=~\emptyset$ and $\var{stPools}~=~\emptyset$, as shown above:
%  \\~\\
  If
  \begin{equation*}
    s_0\vdash c_0\trans{\hyperref[fig:rules:chain]{chain}}{b_0}c_1,~~
    s_1\vdash c_1\trans{\hyperref[fig:rules:chain]{chain}}{b_1}c_2,~~
    \ldots,~~
    s_n\vdash c_n\trans{\hyperref[fig:rules:chain]{chain}}{b_n}c_{n+1},~~n \ge 0
  \end{equation*}
  is a sequence of valid $\mathsf{CHAIN}$ transitions,
  then $\forall i, 0 \le i \le n, \var{deposits} ~(c_{n+1}) \ge 0$.
\end{theorem}

\begin{proof}

  We will prove a slightly stronger condition, namely that some stronger invariants hold
  most of the time, and that when they do fail to hold, then $\var{deposits}$ is still non-negative.
  These stronger invariants will require a few additional definitions.
%
  Given a slot $s$, let $\ell(s)$ be the first slot of the epoch that $s$ occurs in,
  that is $\ell = \fun{firstSlot}\circ\fun{epoch}$.
  Given a mapping $m\in\mathsf{T}\to\Slot$ and a slot $s\in\Slot$,
  let $\fun{sep}$ be the function that separates $m$ into two maps,
  those whose value is strictly less than $s$ and those whose value is at least $s$.
  So,
  \begin{equation*}
    \fun{sep}~m~s = \forall x\mapsto t~\in~m,~~
    \left(\{x\mapsto t~\mid~t<s\},~\{x\mapsto t~\mid~t\geq s\}\right)
  \end{equation*}

  \noindent
  If we assume that the \emph{protocol parameters}, $pp$, are fixed\footnote{Note that the
    protocol parameters can only change in the $\mathsf{NEWPP}$ transition.}, then we can provide convenience functions
  $R_c$ and $R_p$ for the \emph{stake credential} and \emph{stake pool} refunds, respectively:
  \begin{equation*}
    \begin{array}{r@{~=~}l}
      R_c~s_0~s_1 & \refund{d_{val}}{d_{min}}{\lambda_d}{s_1-s_0} \\
      R_p~s_0~s_1 & \refund{p_{val}}{p_{min}}{\lambda_p}{s_1-s_0} \\
    \end{array}
  \end{equation*}
  where $d_{val}$, $d_{min}$, $\lambda_d$, $p_{val}$, $p_{min}$, $\lambda_p$
  are the protocol parameter values from $pp$, and $\fun{refund}$ is defined in
  Figure~\ref{fig:functions:deposits-refunds}.
  We let \DBE{c}{s} (``Deposits (precisely) Big Enough"), be the following property:
  \begin{equation}\tag{DBE}\label{DBE}
    \var{deposits}
    = \left(\sum_{\wcard\mapsto t\in C_{old}}R_c~t~\ell(s)\right)
    + |C_{new}|\cdot d_{val}
    + \left(\sum_{\wcard\mapsto t\in P_{old}}R_p~t~\ell(s)\right)
    + |P_{new}|\cdot p_{val}
  \end{equation}
  where
  \begin{equation*}
    \begin{array}{r@{~=~}l}
      C_{old},~C_{new} & \fun{sep}~\var{stkCreds}~{\ell(s)} \\
      P_{old},~P_{new} & \fun{sep}~\var{stpools}~{\ell(s)},
    \end{array}
  \end{equation*}
  for some slot, $s$, where $\var{pp}$, $\var{stkCreds}$, $\var{stpools}$ are in the corresponding chain state, $c$.
%
  In other words, \DBE{c}{s} asserts that the deposit pot is equal to the
  sum of the deposit refunds that were available at the previous epoch boundary,
  plus the sum of the initial deposit values for all the deposits from the current epoch.

  Notice that for a chain state $c$ and slot $s$, if the range of
  $\var{stkCreds}$ and $\var{stpools}$ contains only slots from the previous epoch,
  then \DBE{c}{s} is equivalent to
  \begin{equation}\tag{DEO}\label{DEO}
    \var{deposits} = \obligation{pp}{stkCreds}{stpools}{\ell(s)}
  \end{equation}
  where $\fun{obligation}$ is defined in Figure~\ref{fig:funcs:epoch-helper-rewards}.
%
  It is generally true that \DBE{c'}{s_i} holds after each subtransition of
  $s_i\vdash c_i\trans{\hyperref[fig:rules:chain]{chain}}{b_i}c_{i+1}$.
  However, this invariant can fail to hold after the
  $\hyperref[fig:delegation-transitions]{\mathsf{DELEG}}$ transition,
  since this transition can add and remove stake credentials, and can also add stake pools,
  but the deposit pot is not adjusted accordingly
  until the next subtransiton of $\hyperref[fig:rules:ledger]{\mathsf{LEDGER}}$,
  namely $\hyperref[fig:rules:utxo-shelley]{\mathsf{UTXO}}$.
%
  The invariant can also fail to hold if the slot increases while the chain state remains the same.
  That is, if \DBE{c_{i+1}}{s_i} holds, then \DBE{c_{i+1}}{s_{i+1}} can fail to hold if
  $\epoch{s_i} < \epoch{s_{i+1}}$, since the value of the deposit
  in the left hand side of equation~\ref{DBE} remains the same, but the
  refunded values become smaller\footnote{Note that if $\epoch{s_i} = \epoch{s_{i+1}}$, then \DBE{c_{i+1}}{s_{i+1}} is trivially true.}.
  Therefore, in this situation we can consider the slightly weaker constraint:
  \begin{equation}\tag{DGO}\label{DGTO}
    \var{deposits} \geq \obligation{pp}{stkCreds}{stpools}{\ell(s)}
  \end{equation}
  The difference between the left and right hand sides of the inequality
  corresponds to the lovelace value in $c_{i+1}$ that decays between $s_i$ and $s_{i+1}$.

  There are four sub-transitions where $\var{deposits}$ is changed:
  $\mathsf{SNAP}$ (Figure~\ref{fig:rules:snapshot}),
  $\mathsf{POOLREAP}$ (Figure~\ref{fig:rules:pool-reap}),
  $\mathsf{NEWPP}$ (Figure~\ref{fig:rules:new-proto-param}),
  $\mathsf{UTXO}$ (Figure~\ref{fig:rules:utxo-shelley}).
  This ordering is also the order in which $\var{deposits}$ is changed.
  Of these sub-transitions, only $\mathsf{UTXO}$ actually changes the value of $\var{deposits}$
  when $s_i$ is in the same epoch as $s_i$.
  (We say that $s_i$ \emph{crosses the epoch boundary} if the precondition of
  Rule~\ref{eq:new-epoch} in Figure~\ref{fig:rules:new-epoch} is met,
  namely if $\epoch{s_i} \ge e_\ell+1$.)
%
  The proof then proceeds by induction on $n$, showing the following:
  \begin{itemize}
    \item
      Let $c$ be the chain state after the $\mathsf{SNAP}$ transition
      in $s_i\vdash c_i\trans{\hyperref[fig:rules:chain]{chain}}{b_i}c_{i+1}$.
      If \DGO{c_i}{s_i}, then \DBE{c}{s_i} holds.
    \item $\mathsf{POOLREAP}$ preserves \ref{DBE}.
    \item $\mathsf{NEWPP}$ preserves \ref{DBE}.
    \item The property for $\mathsf{UTXO}$ requires a bit of explanation.
      Let $\var{nes}\in\NewEpochState$ be the new epoch state in $c_i$.
      Note that the property \ref{DBE} makes sense for values of $\NewEpochState$
      since it contains all the relevant variables.
      Similarly, \ref{DBE} also makes sense for values of $\UTxOState\times\PParams$.
      Let
      $$
        {\begin{array}{c}
           \var{gkeys} \\
         \end{array}}
        \vdash\var{nes}\trans{\hyperref[fig:rules:tick]{tick}}{\var{bh}}\var{nes'}
      $$
      be the first sub-transition of
      $s_i\vdash c_i\trans{\hyperref[fig:rules:chain]{chain}}{b_i}c_{i+1}$.
      If \DBE{\var{nes'}}{s_i} holds, then \DBE{(us', pp)}{s_i} holds for every transaction
      $tx$ in $b_i$, where:
      $$
      \var{env}\vdash \var{us} \trans{\hyperref[fig:rules:utxow-shelley]{utxo}}{tx} \var{us'},
      $$
      is a sub-transition of
      $s_i\vdash c_i\trans{\hyperref[fig:rules:chain]{chain}}{b_i}c_{i+1}$,
      and $\var{pp}$ is the protocol parameters in $\var{nes'}$.
  \end{itemize}

  \noindent
  Case $\hyperref[fig:rules:snapshot]{\mathsf{SNAP}}$.
  We must show that
  if $c$ is the chain state after the $\mathsf{SNAP}$ transition
  in $s_i\vdash c_i\trans{\hyperref[fig:rules:chain]{chain}}{b_i}c_{i+1}$,
  and \DGO{c_i}{s_i} holds, then so does \DBE{c}{s_i}.
%
  We can assume that $s_i$ crosses the epoch boundary,
  since otherwise the $\mathsf{SNAP}$ transition will not occur.
  Since the $\mathsf{SNAP}$ transition only happens within the $\mathsf{TICK}$ transition
  on the epoch boundary, it follows that
  $c_i$ does not contain any stake credentials or pools from the current epoch,
  and so \ref{DBE} will be equivalent to \ref{DEO} (the current epoch is $\epoch{s_i}$).
  However, \DBE{c}{s_i} holds trivially, since it is determined from the $\fun{obligation}$ value.
  \\~\\
  Case $\hyperref[fig:rules:pool-reap]{\mathsf{POOLREAP}}$.
  We must show that \ref{DBE} is preserved.
%
  We again assume that $s_i$ crosses the epoch boundary.
  The $\mathsf{POOLREAP}$ transition does the following:
  \begin{enumerate}
    \item leaves $\var{stkCreds}$ unchanged,
    \item removes $\var{retired}$ from $\var{stpools}$,
    \item subtracts $\var{unclaimed}+\var{refunded}$ from $\var{deposits}$.
  \end{enumerate}
%
  Notice that the domain of the $\var{pr}$ is $\var{retired}$,
  and similarly the domain of the $\var{rewardAcnts}$ is also $\var{retired}$
  since the domains of $\var{stpools}$ and $\var{poolParams}$ are the same.
  Therefore $\var{retired}$ is the disjoint union of
  $\dom({\var{refunds}})$ and $\dom({\var{mRefunds}})$, so that
  \begin{equation*}
    \begin{array}{r@{~=~}l}
      \var{unclaimed}+\var{refunded}
      &
      \left(
        \sum\limits_{\wcard\mapsto t\in\var{refunds}}R_p~t~\ell(s)
      \right)+
      \left(
        \sum\limits_{\wcard\mapsto t\in\var{mRefunds}}R_p~t~\ell(s)
      \right)
      \\
      &
      \sum\limits_{\wcard\mapsto t\in\var{rewardAcnts'}}R_p~t~\ell(s)
      \\
      &
      \left(
        \sum\limits_{\wcard\mapsto t\in\var{stpools}}R_p~t~\ell(s)
      \right)-
      \left(
        \sum\limits_{\wcard\mapsto t\in\var{retired}\subtractdom\var{stpools}}R_p~t~\ell(s)
      \right)
    \end{array}
  \end{equation*}
  Therefore, it follows that if \ref{DEO} holds before $\mathsf{POOLREAP}$, then it also holds afterwards.
  \\~\\
  Case $\hyperref[fig:rules:new-proto-param]{\mathsf{NEWPP}}$.
  We must show that \ref{DBE} is preserved.
%
  We again assume that $s_i$ crosses the epoch boundary.
  In this transition $\var{pp}$ can change, but $\var{stkCreds}$, $\var{stpools}$,
  and $\var{deposits}$ do not change.
  As in the $\mathsf{SNAP}$ case, \DBE{c}{s_i} holds trivially,
  since it is set to the value that is determined by $\fun{obligation}$.
  \\~\\
  Case $\hyperref[fig:rules:utxo-shelley]{\mathsf{UTXO}}$.
  We assume that \DBE{\var{nes'}}{s_i} holds, where $\var{nes'}$
  is the new epoch state after the $\mathsf{TICK}$ transition.
  We must show that \ref{DBE} is preserved after each $\mathsf{UTXO}$ transition.
%
  The $\mathsf{DELEGS}$ transition can result in values being
  added to or deleted from $\var{stkCreds}$, and added to $\var{stpools}$.
  Let $A_s$ be the added stake credentials, $D_s$ be the deleted credentials, and
  $A_p$ be the added stake pools, where $\var{stkCreds}'$ is the stake credential mapping
   $\var{stpools}'$ is the stake pools, and $\var{deposits}'$ is the deposit pot  after $\mathsf{DELEGS}$.
  We have that
  \begin{equation*}
    \begin{array}{rcl}
      \var{D_s} & \subseteq & \var{\var{stkCreds}\cup\var{A_s}} \\
      \var{stkCreds}' & = & (\var{stkCreds}\cup\var{A_s})\setminus\var{D_s} \\
      \var{stpools}' & = & \var{stpools}\cup\var{A_p} \\
    \end{array}
  \end{equation*}
  The slots in the range of $A_s$ will all be equal to $s_i$,
  but the slots in the range of $D_s$
may either be from the current epoch or an earlier one, so we split them using $\fun{sep}$:
  \begin{equation*}
    (\var{D_{s\_old}},~\var{D_{s\_new}}) = \fun{sep}~\var{D_s}~\ell(s_i)
  \end{equation*}
  We must then show that
  \begin{equation*}
    \var{deposits}' = \var{deposits}
    + |A_s|\cdot d_{val}
    + |P_c|\cdot p_{val}
    - |D_{s\_new}|\cdot d_{val}
    - \left(\sum_{\wcard\mapsto t\in D_{s\_old}}R_c~t~\ell(s_i)\right)
  \end{equation*}
  Looking at the $\mathsf{UTXO}$ transition in Figure~\ref{fig:rules:utxo-shelley},
  \begin{equation*}
    \var{deposits}' = \var{deposits} + \totalDeposits{pp}{stpools}{(\txcerts{tx})}
    - (\var{refunded} + \var{decayed})
  \end{equation*}
  The function $\fun{totalDeposits}$ is defined in Figure~\ref{fig:functions:deposits-refunds}
  and it is clear that here it is equal to
  $$|A_s|\cdot d_{val} + |P_c|\cdot p_{val.}$$
  Recall that
  \begin{equation*}
    \begin{array}{r@{~=~}l}
      \var{refunded} & \keyRefunds{pp}{stkCreds}~{tx} \\
      \var{decayed} & \decayedTx{pp}{stkCreds}~{tx}
    \end{array}
  \end{equation*}
  where $\fun{keyRefunds}$ is defined in Figure~\ref{fig:functions:deposits-refunds}.
  This iterates $\fun{keyRefund}$ from the same figure,
  which in turn just looks up the creation slot for a transaction and returns $R_c$.
  The function to calculate the value of decayed deposits, $\fun{decayedTx}$, is defined in Figure~\ref{fig:functions:deposits-decay}.
  This iterates $\fun{decayedKey}$ from the same figure.
  Therefore, to show that
  \begin{equation}\label{deleted-is-refunds-plus-decayed}
    |D_{s\_new}|\cdot d_{val} + \sum_{\wcard\mapsto t\in D_{s\_old}}R_c~t~\ell(s_i)
    = \var{refunded} + \var{decayed},
  \end{equation}
  and thus complete the proof for the $\mathsf{UTXO}$ case,
  it suffices to show that for a given $\var{c}\mapsto s\in D_s$,
  the $R_c$ value plus the $\fun{decayedKey}$ value that is associated with the stake
  credential $c$ is equal to $d_{val}$ if $\epoch(s)=\epoch(s_i)$, and is otherwise equal to $R_c~s~\ell(s_i)$.
  Looking at the definition of $\fun{decayedKey}$, observe that if $\epoch(s)=\epoch(s_i)$
  then $\var{start}=\var{created}$ and so the decayed value is $(R_c~s~s)-(R_c~s~s_i)$.
  However, $R_c~s~s = d_{val}$, so the refund plus the decayed value is
  $d_{val}-(R_c~s~s_i)+(R_c~s~s_i)=d_{val}$.
  Otherwise, if $s$ is from a previous epoch, then $\var{start}=\ell(s_i)$, and so
  the decayed value is $(R_c~s~\ell(s_i))-(R_c~s~s_i)$.
  The refund plus the decayed value is thus
  $(R_c~s~\ell(s_i))-(R_c~s~s_i)+(R_c~s~s_i)=(R_c~s~\ell(s_i))$.
  Therefore, equation~\ref{deleted-is-refunds-plus-decayed} holds, and
  consequently so also does \DBE{c'}{s_i}.

\end{proof}

\subsection{Header-Only Validation}
\label{sec:header-only-validation}
The header-only validation properties of the Shelley Ledger are the analogs
of those from Section 8.1 of \cite{byron_chain_spec}.

In any given chain state, the consensus layer needs to be able to validate the
block headers without having to download the block bodies.
Property~\ref{prop:header-only-validation} states that if an extension of a
chain that spans less than $\StabilityWindow$ slots is valid, then validating the
headers of that extension is also valid. This property is useful for its
converse: if the header validation check for a sequence of headers does not
pass, then we know that the block validation that corresponds to those headers
will not pass either.

First we define the header-only version of the $\mathsf{CHAIN}$ transition,
which we call $\mathsf{CHAINHEAD}$.
It is very similiar to $\mathsf{CHAIN}$, the only difference being that
it does not call $\mathsf{BBODY}$.

\begin{figure}[ht]
  \begin{equation}\label{eq:chain-head}
    \inference[ChainHead]
    {
      \var{bh} \leteq \bheader{block}
      &
      \var{gkeys} \leteq \fun{getGKeys}~\var{nes}
      &
      \var{s} \leteq \bslot{(\bhbody{bh})}
      \\
      (\wcard,~\wcard,~\wcard,~(\wcard,~\wcard,~\wcard,~\var{pp}),~\wcard,~\wcard,\wcard) \leteq \var{nes}
      \\~\\
      \fun{chainChecks}~\var{pp}~\var{bh}
      \\~\\
      {
        {\begin{array}{c}
           \var{gkeys} \\
         \end{array}}
        \vdash\var{nes}\trans{\hyperref[fig:rules:tick]{tick}}{\var{s}}\var{nes'}
      } \\~\\
      (\var{e_1},~\wcard,~\wcard,~\wcard,~\wcard,~\wcard,\wcard)
        \leteq\var{nes} \\
      (\var{e_2},~\wcard,~\wcard,~\var{es},~\wcard,~\var{pd},\var{osched})
        \leteq\var{nes'} \\
        (\wcard,~\wcard,\var{ls},~\wcard,~\var{pp'})\leteq\var{es}\\
        ( \wcard,
          ( (\wcard,~\wcard,~\wcard,~\wcard,~\wcard,~\var{genDelegs}),~
          (\wcard,~\wcard,~\wcard)))\leteq\var{ls}\\
          \var{ne} \leteq  \var{e_1} \neq \var{e_2}\\
      {
        {\begin{array}{c}
            \var{pp'} \\
            \var{osched} \\
            \var{pd} \\
            \var{genDelegs} \\
            \var{s_{now}} \\
            \var{ne}
         \end{array}}
        \vdash
        {\left(\begin{array}{c}
              \var{cs} \\
              \var{lab} \\
              \eta_0 \\
              \eta_v \\
              \eta_c \\
              \eta_h \\
        \end{array}\right)}
        \trans{\hyperref[fig:rules:prtcl]{prtcl}}{\var{bh}}
        {\left(\begin{array}{c}
              \var{cs'} \\
              \var{lab'} \\
              \eta_0' \\
              \eta_v' \\
              \eta_c' \\
              \eta_h' \\
        \end{array}\right)}
      } \\~\\~\\
    }
    {
      \var{s_{now}}
      \vdash
      {\left(\begin{array}{c}
            \var{nes} \\
            \var{cs} \\
            \eta_0 \\
            \eta_v \\
            \eta_c \\
            \eta_h \\
            \var{lab} \\
      \end{array}\right)}
      \trans{chainhead}{\var{bh}}
      {\left(\begin{array}{c}
            \varUpdate{\var{nes}'} \\
            \varUpdate{\var{cs}'} \\
            \varUpdate{\eta_0'} \\
            \varUpdate{\eta_v'} \\
            \varUpdate{\eta_c'} \\
            \varUpdate{\eta_h'} \\
            \varUpdate{\var{lab}'} \\
      \end{array}\right)}
    }
  \end{equation}
  \caption{Chain-Head rules}
  \label{fig:rules:chainhead}
\end{figure}

\begin{property}[Header only validation]\label{prop:header-only-validation}
  For all environments $e$, states $s$ with slot number $t$\footnote{i.e. the
    component $\var{s_\ell}$ of the last applied block of $s$ equals $t$},
    and chain extensions $E$ with corresponding headers $H$ such that:
  %
  $$
  0 \leq t_E - t  \leq \StabilityWindow
  $$
  %
  we have:
  %
  $$
  e \vdash s \transtar{\hyperref[fig:rules:chain]{chain}}{E} s'
  \implies
  e \vdash s \transtar{\hyperref[fig:rules:chainhead]{chainhead}}{H} s''
  $$
  where $t_E$ is the maximum slot number appearing in the blocks contained in
  $E$, and $H$ is obtained from $E$ by applying $\fun{bheader}$ to each block in $E$.
\end{property}

\begin{property}[Body only validation]\label{prop:body-only-validation}
  For all environments $e$, states $s$ with slot number $t$, and chain
  extensions $E = [b_0, \ldots, b_n]$ with corresponding headers $H$ such that:
  $$
  0 \leq t_E - t  \leq \StabilityWindow
  $$
  we have that for all $i \in [1, n]$:
  $$
  e \vdash s \transtar{\hyperref[fig:rules:chainhead]{chainhead}}{H} s_{h}
  \wedge
  e \vdash s \transtar{\hyperref[fig:rules:chain]{chain}}{[b_0 \ldots b_{i-1}]} s_{i-1}
  \implies
  e_{i-1} \vdash s_{i-1}\trans{\hyperref[fig:rules:chainhead]{chainhead}}{h_i} s'_{h}
  $$
  where $t_E$ is the maximum slot number appearing in the blocks contained in $E$.
\end{property}

Property~\ref{prop:body-only-validation} states that if we validate a sequence
of headers, we can validate their bodies independently and be sure that the
blocks will pass the chain validation rule. To see this, given an environment
$e$ and initial state $s$, assume that a sequence of headers
$H = [h_0, \ldots, h_n]$ corresponding to blocks in $E = [b_0, \ldots, b_n]$ is
valid according to the $\mathsf{chainhead}$ transition system:
%
$$
e \vdash s \transtar{\hyperref[fig:rules:chainhead]{chainhead}}{H} s'
$$
%
Assume the bodies of $E$ are valid
according to the $\mathsf{bbody}$ rules, but $E$ is not valid according to
the $\mathsf{chain}$ rule. Assume that there is a $b_j \in E$ such that it is
\textbf{the first block} such that does not pass the $\mathsf{chain}$
validation. Then:
%
$$
e \vdash s \transtar{\hyperref[fig:rules:chain]{chain}}{[b_0, \ldots b_{j-1}]} s_j
$$
But by Property~\ref{prop:body-only-validation} we know that
%
$$
e_j \vdash s_j \trans{\hyperref[fig:rules:chainhead]{chainhead}}{h_j} s_{j+1}
$$
which means that block $b_j$ has valid headers, and this in turn means that the
validation of $b_j$ according to the chain rules must have failed because it
contained an invalid block body. But this contradicts our assumption that the
block bodies were valid.

\begin{property}[Existence of roll back function]\label{prop:roll-back-funk}
  There exists a function $\fun{f}$ such that for all chains
  $$C = C_0 ; b; C_1$$
  we have that if for all alternative chains $C'_1$, $\size{C'_1} \leq \frac{\StabilityWindow}{2}$, with
  corresponding headers $H'_1$
  $$
  e \vdash s_0 \transtar{\hyperref[fig:rules:chain]{chain}}{C_0;b} s_1 \transtar{\hyperref[fig:rules:chain]{chain}}{C_1} s_2
  \wedge
  e \vdash s_1 \transtar{\hyperref[fig:rules:chain]{chain}}{C_1'} s'_1
  \implies
  (\fun{f}~(\bheader{b})~s_2) \transtar{\hyperref[fig:rules:chainhead]{chainhead}}{H'_1} s_h
  $$
\end{property}

Property~\ref{prop:roll-back-funk} expresses the fact the there is a function
that allow us to recover the header-only state by rolling back at most $k$
blocks, and use this state to validate the headers of an alternate chain. Note
that this property is not inherent to the $\mathsf{chain}$ rules and can be
trivially satisfied by any function that keeps track of the history of the
intermediate chain states up to $k$ blocks back. This property is stated here
so that it can be used as a reference for the tests in the consensus layer,
which uses the rules presented in this document.

\subsection{Validity of a Ledger State}
\label{sec:valid-ledg-state}

Many properties only make sense when applied to a valid ledger state. In
informal terms, a valid ledger state $l$ can only be reached when starting from
an initial state $l_{0}$ (ledger in the genesis state) and only executing LEDGER
state transition rules as specified in Section~\ref{sec:ledger-trans} which
changes wither the  UTxO or the delegation state.

\begin{figure}[ht]
  \centering
  \begin{align*}
    \genesisId & \in & \TxId \\
    \genesisTxOut & \in & \TxOut \\
    \genesisUTxO & \coloneqq & (\genesisId, 0) \mapsto \genesisTxOut
    \\
    \ledgerState & \in & \left(
                         \begin{array}{c}
                           \UTxOState \\
                           \DPState
                         \end{array}
    \right)\\
               && \\
    \fun{getUTxO} & \in & \UTxOState \to \UTxO \\
    \fun{getUTxO} & \coloneqq & (\var{utxo}, \wcard, \wcard, \wcard) \to \var{utxo}
  \end{align*}
  \caption{Definitions and Functions for Valid Ledger State}
  \label{fig:valid-ledger}
\end{figure}

In Figure~\ref{fig:valid-ledger} \genesisId{} marks the transaction identifier
of the initial coin distribution, where \genesisTxOut{} represents the initial
UTxO. It should be noted that no corresponding inputs exists, i.e., the
transaction inputs are the empty set for the initial transaction. The function
\fun{getUTxO} extracts the UTxO from a UTxO state.

\begin{definition}[\textbf{Valid Ledger State}]
  \begin{multline*}
    \forall l_{0},\ldots,l_{n} \in \LState, lenv_{0},\ldots,lenv_{n} \in \LEnv,
    l_{0} = \left(
      \begin{array}{c}
        \genesisUTxOState \\
        \left(
        \begin{array}{c}
          \emptyset\\
          \emptyset
        \end{array}
        \right)
      \end{array}
    \right)  \\
    \implies \forall 0 < i \leq n, (\exists tx_{i} \in \Tx,
    lenv_{i-1}\vdash l_{i-1} \trans{ledger}{tx_{i}} l_{i}) \implies
    \applyFun{validLedgerState} l_{n}
  \end{multline*}
  \label{def:valid-ledger-state}
\end{definition}

Definition~\ref{def:valid-ledger-state} defines a valid ledger state reachable
from the genesis state via valid LEDGER STS transitions. This gives a
constructive rule how to reach a valid ledger state.

\subsection{Ledger Properties}
\label{sec:ledger-properties}

The following properties state the desired features of updating a valid ledger
state.

\begin{property}[\textbf{Preserve Balance}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \LState: \applyFun{validLedgerstate}{l},
    l=(u,\wcard,\wcard,\wcard), l' = (u',\wcard,\wcard,\wcard)\\
    \implies \forall \var{tx} \in \Tx, lenv \in\LEnv, lenv \vdash\var{u} \trans{utxow}{tx} \var{u'} \\
    \implies \applyFun{destroyed}{pc~utxo~stkCreds~rewards~tx} =
    \applyFun{created}{pc~stPools~tx}
  \end{multline*}
  \label{prop:ledger-properties-1}
\end{property}

Property~\ref{prop:ledger-properties-1} states that for each valid ledger $l$,
if a transaction $tx$ is added to the ledger via the state transition rule UTXOW
to the new ledger state $l'$, the balance of the UTxOs in $l$ equals the balance
of the UTxOs in $l'$ in the sense that the amount of created value in $l'$
equals the amount of destroyed value in $l$. This means that the total amount of
value is left unchanged by a transaction.

\begin{property}[\textbf{Preserve Balance Restricted to TxIns in Balance of
    TxOuts}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState: \applyFun{validLedgerstate}{l},
    l=(u,\wcard,\wcard,\wcard), l' = (u',\wcard,\wcard,\wcard)\\
    \implies \forall \var{tx} \in \Tx, lenv \in\LEnv, lenv \vdash \var{u}
    \trans{utxow}{tx} \var{u'} \\
    \implies \fun{ubalance}(\applyFun{txins}{tx} \restrictdom
    \applyFun{getUTxO}{u}) = \fun{ubalance}(\applyFun{outs}{tx}) +
    \applyFun{txfee}{tx} + depositChange
  \end{multline*}
  \label{prop:ledger-properties-2}
\end{property}

Property~\ref{prop:ledger-properties-2} states a slightly more detailed relation
of the balances change. For ledgers $l, l'$ and a transaction $tx$ as above, the
balance of the UTxOs of $l$ restricted to those whose domain is in the set of
transaction inputs of $tx$ equals the balance of the transaction outputs of $tx$
minus the transaction fees and the change in the deposit
$depositChange$~(cf.~Fig.~\ref{fig:rules:utxo-shelley}).

\begin{property}[\textbf{Preserve Outputs of Transaction}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState: \applyFun{validLedgerstate}{l},
    l=(u,\wcard,\wcard,\wcard), l' = (u',\wcard,\wcard,\wcard)\\
    \implies \forall \var{tx} \in \Tx, lenv \in\LEnv, lenv \vdash \var{u}
    \trans{utxow}{tx} \var{u'} \implies \forall \var{out} \in
    \applyFun{outs}{tx}, out \in \applyFun{getUTxO}{u'}
  \end{multline*}
  \label{prop:ledger-properties-3}
\end{property}

Property~\ref{prop:ledger-properties-3} states that for all ledger states
$l, l'$ and transaction $tx$ as above, all output UTxOs of $tx$ are in the UTxO
set of $l'$, i.e., they are now available as unspent transaction output.

\begin{property}[\textbf{Eliminate Inputs of Transaction}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState: \applyFun{validLedgerstate}{l},
    l=(u,\wcard,\wcard,\wcard), l' = (u',\wcard,\wcard,\wcard)\\
    \implies \forall \var{tx} \in \Tx, lenv \in\LEnv, lenv \vdash \var{u}
    \trans{utxow}{tx} \var{u'} \implies \forall \var{in} \in
    \applyFun{txins}{tx}, in \not\in \fun{dom}(\applyFun{getUTxO}{u'})
  \end{multline*}
  \label{prop:ledger-properties-4}
\end{property}

Property~\ref{prop:ledger-properties-4} states that for all ledger states
$l, l'$ and transaction $tx$ as above, all transaction inputs $in$ of $tx$ are
not in the domain of the UTxO of $l'$, i.e., these are no longer available to
spend.

\begin{property}[\textbf{Completeness and Collision-Freeness of new Transaction
    Ids}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState: \applyFun{validLedgerstate}{l},
    l=(u,\wcard,\wcard,\wcard), l' = (u',\wcard,\wcard,\wcard)\\
    \implies \forall \var{tx} \in \Tx, lenv \in\LEnv, lenv \vdash \var{u}
    \trans{utxow}{tx} \var{u'} \\ \implies \forall ((txId', \wcard) \mapsto
    \wcard) \in \applyFun{outs}{tx}, ((txId, \wcard) \mapsto \wcard)
    \in\applyFun{getUTxO}{u} \implies \var{txId'} \neq \var{txId}
  \end{multline*}
  \label{prop:ledger-properties-5}
\end{property}

Property~\ref{prop:ledger-properties-5} states that for ledger states $l, l'$
and a transaction $tx$ as above, the UTxOs of $l'$ contain all newly created
UTxOs and the referred transaction id of each new UTxO is not used in the UTxO
set of $l$.

\begin{property}[\textbf{Absence of Double-Spend}]
  \begin{multline*}
    \forall l_{0},\ldots,l_{n} \in \ledgerState, l_{0} =
    \left(
      \begin{array}{c}
        \left\{
        \genesisUTxO
        \right\} \\
        \left(
        \begin{array}{c}
          \emptyset\\
          \emptyset
        \end{array}
        \right)
      \end{array}
    \right) \wedge \applyFun{validLedgerState} l_{n}, l_{i}=(u_{i},\wcard,\wcard,\wcard)\\
    \implies \forall 0 < i \leq n, tx_{i} \in \Tx, lenv_{i}\in\LEnv,
    lenv_{i} \vdash u_{i-1}
    \trans{ledger}{tx_{i}} u_{i} \wedge \applyFun{validLedgerState} l_{i} \\
    \implies \forall j < i, \applyFun{txins}{tx_{j}} \cap
    \applyFun{txins}{tx_{i}} = \emptyset
  \end{multline*}
  \label{prop:ledger-properties-no-double-spend}
\end{property}

Property~\ref{prop:ledger-properties-no-double-spend} states that for each valid
ledger state $l_{n}$ reachable from the genesis state, each transaction $t_{i}$
does not share any input with any previous transaction $t_{j}$. This means that
each output of a transition is spent at most once.

\subsection{Ledger State Properties for Delegation Transitions}
\label{sec:ledg-prop-deleg}

\begin{figure}[ht]
  \centering
  \begin{align*}
    \fun{getStDelegs} & \in & \DState \to \powerset \Credential \\
    \fun{getStDelegs} & \coloneqq &
                                    ((\var{stkCreds}, \wcard,
                                    \wcard,\wcard,\wcard,\wcard) \to \var{stkCreds} \\
                      &&\\
    \fun{getRewards} & \in & \DState \to (\AddrRWD \mapsto \Coin) \\
    \fun{getRewards} & \coloneqq & (\wcard, \var{rewards},
                                   \wcard,\wcard,\wcard,\wcard)
                                   \to \var{rewards} \\
                      &&\\
    \fun{getDelegations} & \in & \DState \to (\Credential \mapsto \KeyHash) \\
    \fun{getDelegations} & \coloneqq & (\wcard, \wcard,
                                       \var{delegations},\wcard,\wcard,\wcard) \to
                                       \var{delegations} \\
                      &&\\
    \fun{getStPools} & \in & \LState \to (\KeyHash \mapsto \DCertRegPool) \\
    \fun{getStPools} & \coloneqq & (\wcard, (\wcard,
                                   (\var{stpools},\wcard,\wcard,\wcard))) \to \var{stpools} \\
                      &&\\
    \fun{getRetiring} & \in & \LState \to (\KeyHash \mapsto \Epoch) \\
    \fun{getRetiring} & \coloneqq & (\wcard, (\wcard,
                                    (\wcard, \wcard, \var{retiring},\wcard))) \to \var{retiring} \\
  \end{align*}
  \caption{Definitions and Functions for Stake Delegation in Ledger States}
  \label{fig:stake-delegation-functions}
\end{figure}

\begin{property}[\textbf{Registered Staking Credential with Zero Rewards}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState: \applyFun{validLedgerstate}{l},
    l = (\wcard, ((d, \wcard), \wcard)), l' = (\wcard, ((d',\wcard), \wcard)), dEnv\in\DEnv \\
    \implies \forall \var{c} \in \DCertRegKey, dEnv\vdash \var{d}
    \trans{deleg}{c} \var{d'} \implies \applyFun{cwitness}{c} = \var{hk}\\
    \implies hk\not\in \fun{getStDelegs}~\var{d} \implies \var{hk} \in
    \applyFun{getStDelegs}{d'} \wedge
    (\applyFun{getRewards}\var{d'})[\fun{addr_{rwd}}{hk}] = 0
  \end{multline*}
  \label{prop:ledger-properties-6}
\end{property}

Property~\ref{prop:ledger-properties-6} states that for each valid ledger state
$l$, if a delegation transaction of type $\DCertRegKey$ is executed, then in the
resulting ledger state $l'$, the set of staking credential of $l'$ includes the
credential $hk$ associated with the key registration certificate and the
associated reward is set to 0 in $l'$.

\begin{property}[\textbf{Deregistered Staking Credential}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState: \applyFun{validLedgerstate}{l},
    l = (\wcard, (d, \wcard)), l' = (\wcard, (d', \wcard)), dEnv\in\DEnv \\
    \implies \forall \var{c} \in \DCertDeRegKey, dEnv\vdash\var{d}
    \trans{deleg}{c} \var{d'} \implies \applyFun{cwitness}{c} = \var{hk}\\
    \implies \var{hk} \not\in \applyFun{getStDelegs}{d'} \wedge hk\not\in
    \left\{ \fun{stakeCred_{r}}~sc\vert
      sc\in\fun{dom}(\applyFun{getRewards}{d'})
    \right\}\\
    \wedge hk \not\in \fun{dom}(\applyFun{getDelegations}{d'}))
  \end{multline*}
  \label{prop:ledger-properties-7}
\end{property}

Property~\ref{prop:ledger-properties-7} states that for $l, l'$ as above but
with a delegation transition of type $\DCertDeRegKey$, the staking credential
$hk$ associated with the deregistration certificate is not in the set of staking
credentials of $l'$ and is not in the domain of either the rewards or the
delegation map of $l'$.

\begin{property}[\textbf{Delegated Stake}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState: \applyFun{validLedgerstate}{l},
    l = (\wcard, (d,\wcard)), l' = (\wcard, (d',\wcard)), dEnv\in\DEnv \\
    \implies \forall \var{c} \in \DCertDeleg, dEnv \vdash\var{d}
    \trans{deleg}{c} \var{d'} \implies \applyFun{cwitness}{c} = \var{hk}\\
    \implies \var{hk} \in \applyFun{getStDelegs}{d'} \wedge
    (\applyFun{getDelegations}{d'})[hk] = \applyFun{dpool}{c}
  \end{multline*}
  \label{prop:ledger-properties-8}
\end{property}

Property~\ref{prop:ledger-properties-8} states that for $l, l'$ as above but
with a delegation transition of type $\DCertDeleg$, the staking credential $hk$
associated with the deregistration certificate is in the set of staking
credentials of $l$ and delegates to the staking pool associated with the
delegation certificate in $l'$.

\begin{property}[\textbf{Genesis Keys are Always All Delegated}]
  \label{prop:genkeys-delegated}
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \LState: \applyFun{validLedgerstate}{l},\\
    \implies \forall \Gamma \in \seqof{\Tx}, env \in (\Slot \times \PParams), \\
    env \vdash\var{l} \trans{ledgers}{\Gamma} \var{l'} \implies |genDelegs| = 7
  \end{multline*}
\end{property}

Property \ref{prop:genkeys-delegated} states that all seven of the genesis keys
are constantly all delegated after applying a list of transactions to a valid ledger
state.

\subsection{Ledger State Properties for Staking Pool Transitions}
\label{sec:ledg-state-prop}

\begin{property}[\textbf{Registered Staking Pool}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState: \applyFun{validLedgerstate}{l},
    l = (\wcard, (\wcard, p)), l' = (\wcard, (\wcard, p')), pEnv\in\PEnv \\
    \implies \forall \var{c} \in \DCertRegPool, \var{p} \trans{pool}{c} \var{p'}
    \implies \applyFun{cwitness}{c} = \var{hk}\\ \implies
    \var{hk}\in\applyFun{getStPools}{p'} \wedge \var{hk} \not\in
    \applyFun{getRetiring}{p'}
  \end{multline*}
  \label{prop:ledger-properties-9}
\end{property}

Property~\ref{prop:ledger-properties-9} states that for $l, l'$ as above but
with a delegation transition of type $\DCertRegPool$, the key $hk$ is associated
with the author of the pool registration certificate in $\var{stpools}$ of $l'$
and that $hk$ is not in the set of retiring stake pools in $l'$.

\begin{property}[\textbf{Start Staking Pool Retirement}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState, \var{cepoch} \in \Epoch:
    \applyFun{validLedgerstate}{l},
    l = (\wcard, (\wcard,p)), l' = (\wcard, (\wcard,p')), pEnv\in\PEnv \\
    \implies \forall \var{c} \in \DCertRetirePool, pEnv\vdash\var{p}
    \trans{POOL}{c} \var{p'} \\ \implies e = \applyFun{retire}{c} \wedge
    \var{cepoch} < e < \var{cepoch} + \emax \wedge \applyFun{cwitness}{c} =
    \var{hk}\\ \implies (\applyFun{getRetiring}{p'})[\var{hk}] = e \wedge
    \var{hk} \in
    \fun{dom}(\applyFun{getStPools}{p})\wedge\fun{dom}(\applyFun{getStPools}{p'}
    )
  \end{multline*}
  \label{prop:ledger-properties-10}
\end{property}

Property~\ref{prop:ledger-properties-10} states that for $l, l'$ as above but
with a delegation transition of type $\DCertRetirePool$, the key $hk$ is
associated with the author of the pool registration certificate in
$\var{stpools}$ of $l'$ and that $hk$ is in the map of retiring staking pools of
$l'$ with retirement epoch $e$, as well as that $hk$ is in the map of stake
pools in $l$ and $l'$.

\begin{property}[\textbf{Stake Pool Reaping}]
  \begin{multline*}
    \forall \var{l}, \var{l'} \in \ledgerState, \var{e} \in \Epoch:
    \applyFun{validLedgerstate}{l},\\
    l = (\wcard, (d, p)), l' = (\wcard, (d', p')), pp\in\PParams, acnt, acnt'\in\Acnt \\
    \implies pp\vdash\var{(acnt, d, p} \trans{poolreap}{e} \var{(acnt, d', p')}
    \implies \forall \var{retire}\in{(\fun{getRetiring}~p)}^{-1}[e], retire \neq
    \emptyset \\ \wedge \var{retire} \subseteq
    \fun{dom}(\applyFun{getStPool}{p}) \wedge
    \var{retire} \cap\fun{dom}(\applyFun{getStPool}{p'})=\emptyset \\
    \wedge\var{retire} \cap \fun{dom}(\applyFun{getRetiring}{p'}) = \emptyset
  \end{multline*}
  \label{prop:ledger-properties-11}
\end{property}

Property~\ref{prop:ledger-properties-11} states that for $l, l'$ as above but
with a delegation transition of type POOLREAP, there exist registered stake
pools in $l$ which are associated to stake pool registration certificates and
which are to be retired at the current epoch $\var{e}$. In $l'$ all those stake
pools are removed from the maps $stpools$ and $retiring$.

\subsection{Properties of Numerical Calculations}
\label{sec:prop-numer-calc}

The numerical calculations for refunds and rewards in
(see Section~\ref{sec:epoch}) are also required to have certain properties. In
particular we need to make sure that the functions that use non-integral
arithmetic have properties which guarantee consistency of the system. Here, we
state those properties and formulate them in a way that makes them usable in
properties-based testing for validation in the executable spec.

\begin{property}[\textbf{Minimal Refund}]
  \label{prop:minimal-refund}

  The function $\fun{refund}$ takes a value, a minimal percentage, a decay
  parameter and a duration. It must guarantee that the refunded amount is within
  the minimal refund (off-by-one for rounding / floor) and the original value.

  \begin{multline*}
    \forall d_{val} \in \mathbb{N}, d_{min} \in [0,1], \lambda \in (0, \infty),
    \delta \in \mathbb{N} \\
    \implies \max(0,d_{val}\cdot d_{min} - 1) \leq \floor*{d_{val}\cdot(d_{min} +
      (1-d_{min})\cdot e^{-\lambda\cdot\delta})} \leq d_{val}
  \end{multline*}
\end{property}

\begin{property}[\textbf{Maximal Pool Reward}]
  \label{prop:maximal-pool-reward}

  The maximal pool reward is the expected maximal reward paid to a stake
  pool. The sum of all these rewards cannot exceed the total available reward,
  let $Pool$ be the set of active stake pools:

  \begin{equation*}
    \forall R \in Coin:\sum_{p \in Pools} \floor*{\frac{R}{1+p_{a_{0}}}\cdot
      \left(
        p_{\sigma'}+p_{p'}\cdotp_{a_{0}}\cdot\frac{p_{\sigma'}-p_{p'}\cdot\frac{p_{z_{0}}-p_{\sigma'}}{p_{z_{0}}}}{p_{z_{0}}}
      \right)}\leq R
  \end{equation*}
\end{property}

\begin{property}[\textbf{Actual Reward}]
  \label{prop:actual-reward}

  The actual reward for a stake pool in an epoch is calculated by the function
  $\fun{poolReward}$. The actual reward per stake pool is non-negative and
  bounded by the maximal reward for the stake pool, with $\overline{p}$ being
  the relation $\frac{n}{\max(1, \overline{N})}$ of the number of produced
  blocks $n$ of one pool to the total number $\overline{N}$ of produced blocks
  in an epoch and $maxP$ being the maximal reward for the stake pool. This gives
  us:

  \begin{equation*}
    \forall \gamma \in [0,1] \implies 0\leq \floor*{\overline{p}\cdot maxP} \leq maxP
  \end{equation*}
\end{property}

The two functions $\fun{r_{operator}}$ and $\fun{r_{member}}$ are closely related as
they both split the reward between the pool leader and the members.

\begin{property}[\textbf{Reward Splitting}]
  \label{prop:reward-splitting}

  The reward splitting is done via $\fun{r_{operator}}$ and $\fun{r_{member}}$, i.e.,
  a split between the pool leader and the pool members using the pool cost $c$
  and the pool margin $m$. Therefore the property relates the total reward
  $\hat{f}$ to the split rewards in the following way:

  \begin{multline*}
    \forall m\in [0,1], c\in Coin \implies c + \floor*{(\hat{f} - c)\cdot (m +
      (1 - m)) \cdot \frac{s}{\sigma}} + \sum_{j}\floor*{(\hat{f} -
      c)\cdot(1-m)\cdot\frac{t_{j}}{\sigma}} \leq \hat{f}
  \end{multline*}

\end{property}

\clearpage

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "ledger-spec"
%%% End: