\section{Operational Semantics}

\subsection{Notation}

The state of the evaluator, $\sigma$, is the tuple consisting of \\
packet, $\pi$\\
action\_list, $\alpha$ \\
stored\_action\_list, $\Lambda$ \\
context, $\Gamma$, which is the tuple: \\
$\langle ingress\_port, \ egress\_port, \ physical\_port, \ key, \ meta, \ header\_offset, \ table \rangle$ \\ \\
Compactly, $\sigma = \langle \pi, \alpha, \Lambda, \Gamma \rangle$
\\ \\
We can examine the status of $\pi$ or $\Gamma$ by using the index operator, []. The index itself is context-sensitive: $\pi$ is indexed by some \textit{field}, $\Gamma$ is indexed by one of its substructures. We will use the assignment operator, $\leftarrow$, within the index operator to assign a bitfield to a value or the value of another bitfield.
A field in $\pi$ can be set to a literal value or copied from a bitfield or register. For example:
\begin{equation}
  \pi[\textit{field} \leftarrow \textit{value}]
\end{equation}
\begin{equation}
  \pi[\textit{field} \leftarrow \mathct{r}]
\end{equation}
\begin{equation}
  \pi[\textit{field} \leftarrow \textit{bitfield}]
\end{equation}
A variable in $\Gamma$ is accessed similarly, but uses the dot operator, ., to access its substructures within the index operator. Example:
\begin{equation}
  \Gamma[\Gamma.\mathct{key} \leftarrow \textit{bitfield}]
\end{equation}
One should not confuse the range operator, [), with the index operator. To avoid ambiguity, the range operator \textit{always} appears inside
of the index operator, []. Example:
\begin{equation}
  \pi[field_1 \leftarrow field_2[0, 10)]
\end{equation}

Comments:
\begin{enumerate}
\item Field \textit{field} with a packet, $\pi$, is set to some literal value, \textit{value}.
\item The value of register $\mathct{r}$ is copied into \textit{field}.
\item The value of some bitfield, \textit{bitfield} is copied into \textit{field}.
\item The value of the $\mathct{key}$ register in $\Gamma$ is set to the value of \textit{bitfield}
\item The bits of $field_1$ in $\pi$ are set to the bits 0, up to but not including 10, in $field_2$.
\end{enumerate}

\subsection{Operational Semantics 5-Tuple}
Turbak and Gifford define operational semantics for a language as the 5-Tuple, $\langle CF, \Rightarrow, FC, IF, OF \rangle$. CF is the set of all possible configurations that an abstract machine may be in. $\Rightarrow$ is the transition relation, a function that transitions from one configuration to another. FC is the set of all final configurations, the possible ending configurations of the machine. IF is the input function, a function that translates an input into the beginning state of the machine. Finally, OF is the output function, or the transition of the final state into some useful value or domain \cite{Turbak2008}. In Pip, we define the 5-tuple as follows:\\
pip = $\langle IF, \ CF, \ \Rightarrow, \ FC, \ OF \rangle$\\
IF = $\textrm{program} \times \pi \rightarrow CF$ \\
CF = $\alpha \times \Gamma \times \pi \times Lambda$ \\
$\Rightarrow$ = Defined in section ``Transition Relation''. \\
FC = $(\Lambda = \varnothing) \times (\alpha = \varnothing) \times \pi \times \Gamma[egress\_port \neq 0]$ \\
OF = $FC \rightarrow$ \texttt{serialization}

\texttt{serialization} is the output state of Pip: a textual logging of all states that the machine entered.
\subsection{Transition Relation}
\setlength{\mathindent}{0pt}

\begin{mdframed}
\begin{gather*}
  (\mathct{advance}~n \cdot \bar\alpha), \langle \pi, \Lambda, \Gamma \rangle
  \Rightarrow
  (\bar\alpha), \langle \pi, \Lambda, \Gamma[\mathct{header}
  \leftarrow \mathct{header} + n] \rangle
\\
  (\mathct{clear} \cdot \bar\alpha), \langle \pi, \Lambda, \Gamma \rangle
  \Rightarrow
  (\bar\alpha), \langle \pi, \varnothing, \Gamma \rangle
\\
  (\mathct{drop} \cdot \bar\alpha), \langle \pi, \Lambda, \Gamma \rangle
  \Rightarrow
  \varnothing, \langle \pi, \varnothing, \Gamma [\mathct{out} \leftarrow 0] \rangle
\\
  (\mathct{write} \ \textit{action} \cdot \bar\alpha), \langle \pi, \Lambda,
  \Gamma \rangle
  \Rightarrow
  (\bar\alpha), \langle \pi, \Lambda \cdot \textit{action}, \Gamma \rangle
\\
  (\mathct{goto} \ T \cdot \bar\alpha),
  \langle \pi, \Lambda, \Gamma \rangle
  \Rightarrow
  (\bar\alpha), \langle \pi, \Lambda,
  \Gamma[\mathct{current\_table} \leftarrow T] \rangle
\\
  (\mathct{set} \ \textit{field} \ \textit{value} \cdot \bar\alpha), \langle \pi,
  \Lambda, \Gamma \rangle
  \Rightarrow
  (\bar\alpha), \langle \pi', \Lambda, \Gamma' \rangle
\\
  (\mathct{output} \ \mathct{port} \ n \cdot \bar \alpha), \langle \pi, \Lambda,
  \Gamma \rangle
  \Rightarrow
  (\bar\alpha), \langle \pi, \Lambda, \Gamma[\mathct{egress\_port}
  \leftarrow \mathct{port} \ n] \rangle
\\
  (\mathct{copy} \ as_1 \ src \ as_2 \ dst \cdot \bar\alpha), \langle \pi,
  \Lambda, \Gamma \rangle
  \Rightarrow
  (\bar\alpha), \langle \pi', \Lambda, \Gamma' \rangle
\end{gather*}
\end{mdframed}

The $\mathct{advance}$ command advances the header offset by \textit{n} bits.
This can be used by a programmer to adjust the decoding offset relative to a
packet header.
The $\mathct{clear}$ command clears the stored action list. This can be used
by a program reset any accumulated actions if certain conditions are detected
during packet analysis (e.g., filtering flows based on UDP packet content).
The $\mathct{drop}$ command truncates both the action list and stored action list,
and sets the output port to 0 (the null port).
The effect of this to cause the program to terminate such that the execution
environment will not forward the packet.
The \mathct{write} command appends an action to the stored action list. This is
the only way to write to the stored action list, allowing for some action to be
taken upon egress, providing the packet is not dropped.
The \mathct{goto} command jumps from the current match table to a new table. The
key register is cleared and rewritten based on the new table's rules. This can
be used as a rudimentary control structure.
The \mathct{set} command sets a bitfield, \textit{field} to some value \textit{value}.
This is used to set fields to a literal value.
The \mathct{output} action outputs to the specified \mathct{port}, \textit{n}, beginning
egress processing.
The \mathct{copy} action copies from one bitfield, \textit{src} to another bitfield, \textit{dst}.
A bitfield can be copied from any address space to any other address space, except for key registers,
which cannot be used as a source.

Definition of copy function:
\begin{mdframed}
\begin{gather*}
  (\mathct{copy}  \ meta \ src \ packet \ dst \ n)
  \rightarrow
  \langle \pi[dst \leftarrow \Gamma.\mathct{meta}[dst, dst + n)],
  \Lambda, \Gamma \rangle
\\
  (\mathct{copy} \ meta \ src \ header \ dst \ n)
  \rightarrow
  \langle \pi[dst + \mathct{hoff} \leftarrow \Gamma.meta[dst, dst + n)],
  \Lambda, \Gamma \rangle
\\
  (\mathct{copy} \ meta \ src \ key \ dst \ n)
  \rightarrow
  \langle \pi, \Lambda, \Gamma[\Gamma.\mathct{key} \leftarrow
  \Gamma.\mathct{meta}[meta, meta + n)] \rangle
\\
  (\mathct{copy} \ packet \ src \ packet \ dst \ n)
  \rightarrow
  \langle \pi[dst \leftarrow \pi[src, src + n)], \Lambda, \Gamma \rangle
\\
  (\mathct{copy} \ packet \ src \ header \ dst \ n)
  \rightarrow
  \langle \pi[dst + \mathct{hoff} \leftarrow
  \pi[src, src + n)],
  \Lambda, \Gamma \rangle
\\
  (\mathct{copy} \ packet \ src \ key \ dst \ n)
  \rightarrow
  \langle \pi, \Lambda, \Gamma[\Gamma.\mathct{key} \leftarrow \pi[src, src + n)]
  \rangle
\\
  (\mathct{copy} \ header \ src \ header \ dst \ n)
  \rightarrow
  \langle \pi[dst + \mathct{hoff} \leftarrow
  \pi[src + \mathct{hoff}, src + \mathct{hoff} + n)],
  \Lambda, \Gamma \rangle
\\
  (\mathct{copy} \ header \ src \ packet \ dst \ n)
  \rightarrow
  \langle \pi[dst \leftarrow
  \pi[src + \mathct{hoff}, src +
  \mathct{hoff} + n)], \Lambda, \Gamma \rangle
\\
  (\mathct{copy} \ header \ src \ key \ dst \ n)
  \rightarrow
  \langle \pi, \Lambda, \Gamma[\Gamma.\mathct{key}[dst] \leftarrow
  \pi[src +
  \mathct{hoff}, src + \mathct{hoff} + n)] \rangle
\\
  (\mathct{copy} \ header \ src \ meta \ dst \ n)
  \rightarrow
  \langle \pi, \Lambda, \Gamma[\Gamma.\mathct{meta}[dst] \leftarrow
  \pi[src +
  \mathct{hoff}, src + \mathct{hoff} + n)] \rangle
\end{gather*}
\end{mdframed}

Defintion of set function:
\begin{mdframed}
\begin{gather*}
  (\mathct{set} \ (meta \ field \ n) \ value)
  \rightarrow
  \langle \pi, \Lambda, \Gamma[\Gamma.\mathct{meta}[field, field + n) \leftarrow value] \rangle
  \\
  (\mathct{set} \ (key \ field \ n) \ value)
  \rightarrow
  \langle \pi, \Lambda, \Gamma[\Gamma.\mathct{key}[field, field + n) \leftarrow value] \rangle
  \\
  (\mathct{set} \ (packet \ field \ n) \ value)
  \rightarrow
  \langle \pi, \Lambda, \Gamma[\Gamma.\mathct{packet}[field, field + n) \leftarrow value] \rangle
  \\
  (\mathct{set} \ (header \ field \ n) \ value)
  \rightarrow
  \langle \pi, \Lambda, \Gamma[\Gamma.\mathct{packet}[field + \mathct{hoff},
      field + \mathct{hoff} + n) \leftarrow value] \rangle
  \\
\end{gather*}
\end{mdframed}
\textit{Note:} the context variable $\mathct{header\_offset}$ is abbreviated to $\mathct{hoff}$ for brevity.


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{tikz}
\usepackage{tkz-graph}
\usepackage{float}
\usepackage{amsmath}
\GraphInit[vstyle = Shade]

\title{Assignment 2}
\author{Jason Fantl, Jacob Tuttle}
\date{November 2019}

\begin{document}

\maketitle

\section{Theory vs. Practice}

3 reasons why asymptotic analysis may be misleading with respect to actual performance in practice:
\begin{itemize}
  \item Because asymptotic analysis ignores constants, it can lead to misrepresenting which algorithm is more efficient for specific situations. For example, if one algorithm runs in O(n) time and another runs in O($n^2$) time, you would assume the O(n) algorithm is more efficient. But if you also know that constants are included, and that the linear time algorithm would run in $10000n$ time, and the other in $n^2$ time, the more efficient algorithm depends on your input size, not just asymptotic time complexity.
  \item In practice there are always restrictions on both memory and time, and asymptotic analysis only considers how well an algorithm scales, not how well it will fit within the given conditions. This could lead to using an algorithm that scales very well but fails to complete the task at all within the available constraints. For example, if an algorithm were to rely on a large volume of memory access, when run on a computer with very efficient memory access techniques, these actions would have little effect on the runtime; however, if it were run on a device with much less efficient memory access, the execution time would balloon as a result that has nothing to do with the $O$ complexity.
  \item While asymptotic analysis will provide information about how the algorithm will behave in the abstract sense, it says nothing about how the code will run on a specific machine. Even if one were to run the algorithm on one machine, and use this data to extrapolate the runtimes for various input sizes, that information would mean nothing if the algorithm were run on another machine. The asymptotic runtime of an algorithm says very little about the true execution time for an algorithm, and it provides even less information when considering the differences of running on different machines.
\end{itemize}

Given a binary search tree with $1,000$ elements and a measured time of $5$ seconds to access one of those elements, we could use asymptotic analysis to predict how long it would take to find in element in a binary search tree with $10,000$ elements.
We know the time complexity of a searching in a binary search tree is $O(log(n))$. We can find the ratio of time it should take between different trees using this fact. The ratio of time between a tree with $1,000$ elements and a tree with $10,000$ should be $log_2(1,000)/log_2(10,000) = 0.75$. Using this calculation and the fact that the $1,000$ element tree took $5$ seconds, we predict it should take $\frac{5}{0.75} = 6.67$ seconds to find an element.

If the measured time of the two binary search trees doesn't match our prediction, here are three reasons why that might have happened:
\begin{itemize}
  \item Since $O$ only describes the highest order term, disregarding constants and lower order terms, one of these discarded terms may have been much larger than was initially considered. If one of these constants or lower order terms were to be quite large, increasing the input size could change the run time more significantly than calculations indicate.
  \item Depending on what form the input binary tree takes, the worst case time complexity of searching can be $O(n)$. It's possible the first execution, the $5$ second one, ran on an average or best case tree and the second execution ran on a worst case input. This would result in a much larger execution time since the worst case takes asymptotically more time than the average case.
  \item If the algorithm were run on different computers, then even if one were to run the same algorithm on the same tree, different run times could be produced. When run on a slower computer, this difference would be even more pronounced and could result in the difference between calculated and observed run times discussed in this problem.
\end{itemize}

\section{Graph Properties}

Definitions:
\begin{itemize}
\item Isomorphic: G1 = (V1, E1) is isomorphic to G2 = (V2, E2) if there is a
one-to-one and onto function $f : V1 \rightarrow V2$ such that
$(u, v) \in E1 \iff (f(u), f(v)) \in E2$
\item Completely connected: A graph is completely connected if there exists an edge between every pair of vertices.
\item One-to-One function: A function f is one-to-one if for all x and y f(x) = f(y) then x = y.
\item Onto function: A function f is onto if for all y in the range of f there exists an x such that f(x) = y
\end{itemize}

%Theorem: If two graphs A and B have the same number of nodes and are completely connected, they are isomorphic.

%Proof:
%We have a completely connected graph G1 = (V1, E1), and a completely connected graph G2 = (V2, E2) both with x vertices. We will label each vertex of graph G1 from V1 to Vx since it has x vertices. Then for each vertex, it has x edges since a completely connected graph connects every pair of vertices, and there are x vertices. For each edge edge coming out of vertex Vn, connecting to Vm, we will label that edge as En,m. Since G2 has the same number of vertices and is also completely connected, we will label all of its vertices and edges in the same exact way. Now there exists a simple function f which takes an edge or vertex and returns the same vertex or edge, that is f(u) = u and f(v) = v. This function is one-to-one since for all Pn and Qm where Pn and Qm are arbitrary vertices or edges, if f(Pn) = f(Qm) then Pn = Qm by the definition of f. f is also onto since for any value I in the range of f we pick a new value J = I, then f(J) = I by the definition of f.

%To be continued \\

Theorem: If two graphs A and B have the same number of nodes and are completely connected, they are isomorphic. \\

Proof: Let $A$ and $B$ be two graphs that are completely connected and have the same number of nodes. By the definition of two completely connected graphs, we can define $A$ as a set of vertices $V_A$ labeled $a_1, a_2, \hdots a_n$ and a set of edges $E_A : (a_1, a_2), (a_1, a_3), \hdots (a_1, a_n), (a_2, a_3), (a_2, a_4), \hdots (a_2, a_n), \hdots (a_{n-1}, a_n)$. Likewise, $B$ is defined in a similar fashion with vertices $V_B : b_1, b_2, \hdots b_n$ and edges $E_B : (b_1, b_2), (b_1, b_3), \hdots (b_1, b_n), (b_2, b_3), (b_2, b_4), \hdots (b_2, b_n), \hdots (b_{n-1}, b_n)$. For these two graphs to be isomorphic, there must be a one-to-one and onto function $f: V1 \rightarrow V2$ such that $(u, v) \in E_A \iff (f(u), f(v)) \in E_B$ \\

If we can find this bijection, $f$, such that $(u, v) \in E_A \iff (f(u), f(v)) \in E_B$ then it will be shown that $A$ and $B$ are isomorphic. Let $f$ be defined as the function such that:
\begin{align*}
    f(a_1) &= b_1 \\
    f(a_2) &= b_2 \\
    &\vdots \\
    f(a_n) &= b_n
\end{align*}

$f$ is onto and one-to-one as we have defined it because every node in $V_A$ can be mapped by $f$ to a single corresponding node in $V_B$.

Using this function, it can be shown that every edge in $A$ corresponds to the same edge $(f(a_i), f(a_j)) = (b_i, b_j)$ for all $i, j \leq n$. Therefore, $A$ and $B$ are isomorphic. \\

% Old proof that is added
%Theorem: If two graphs A and B are isomorphic they do not need to be completely connected.

%Proof: Let there be graphs G1 and G2 such that both have 3 vertices, called A1, B1, and C1 for G1, and A2, B2, and C2 for G2. Let G1 only have edges from A1 to B1 called AB1 and B1 to C1 called BC1, and let G2 only have edges from A2 to B2 called AB2 and B2 to C2 called BC2. Neither of these graphs are fully connected since there isn't an edge from A1 to C1 and there isn't an edge from A2 to C2. These graphs are isomorphic since the edge AB1 can be mapped to AB2 and BC1 mapped to BC2, and the edge and AB2 can be mapped to AB1 and BC2 mapped to BC1. This exhaustively finds a mapping between the sets of edges. By this example, we have found two graphs which are isomorphic and not fully connected, proving the theorem.*/

Theorem: If two graphs $A$ and $B$ are isomorphic, they do not need to be completely connected. \\

Proof: Let $A$ and $B$ be the graphs by Figure 1 and Figure 2 respectively and be defined as:

\begin{align*}
    A &= (V_A, E_A) \\
    V_A &= \{a, b, c\} \\
    E_A &= \{(a, c), (c, b)\} \\
    B &= (V_B, E_B) \\
    V_B &= \{x, y, z\} \\
    E_B &= \{(x, y), (y, z)\}
\end{align*}

\begin{figure}[H]
    \centering
    \begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

    % draw nodes
    \foreach [count=\i] \x/\y/\t in {0/0/c, 0/3/a, 2/2/b}
        \node [circle, draw]
            (v\t) at (\x, \y) {\t};

    % draw edges
    \foreach \i/\j in {a/c, c/b}
        \draw (v\i) edge[post] (v\j);

    \end{tikzpicture}
    \caption{Graph $A$}
    \label{fig:graph_a}
\end{figure}
\begin{figure}[H]
    \centering
    \begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

    % draw nodes
    \foreach [count=\i] \x/\y/\t in {0/0/x, 3/0/y, 6/0/z}
        \node [circle, draw]
            (v\t) at (\x, \y) {\t};

    % draw edges
    \foreach \i/\j in {x/y, y/z}
        \draw (v\i) edge[post] (v\j);

    \end{tikzpicture}
    \caption{Graph $B$}
    \label{fig:graph_b}
\end{figure}
Let $f$ be a one-to-one and onto bijection from $A \rightarrow B$ such that:
\begin{align*}
    f(a) &= x \\
    f(b) &= z \\
    f(c) &= y
\end{align*}
Using the definitions above, it can be seen that all edges are mapped from $E_A$ to $E_B$ by $f$ and $f$ is one-to-one and onto from $A \rightarrow B$. Furthermore, in graph $A$ nodes $a$ and $b$ are not connected and in graph $B$ nodes $x$ and $z$ are not connected; therefore, the graphs are not completely connected. These graphs satisfy the theorem as two graphs that are isomorphic and not completely connected; therefore two graphs do not need to be completely connected to be isomorphic.

\section{Ford-Fulkerson --- Augmenting Paths}
Code solutions to this problem are provided in: \\ \texttt{Ford-Fulkerson\_Augmenting\_Paths.js}

\section{Ford-Fulkerson Algorithm }

Residual graph, iteration 1:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

   \foreach \i/\j/\t in {S/B/8, S/D/2, S/E/3, B/C/1, D/C/3, D/F/9, D/E/4, E/F/2, E/T/1, C/F/5, F/T/7}
    \draw (v\i) edge[post] node{\t} (v\j);
\end{tikzpicture}

Residual graph, iteration 2:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {S/B/8, S/D/2, B/C/1, D/C/3, D/F/9, D/E/4, E/F/2, T/E/1, C/F/5, F/T/7}
        \draw (v\i) edge[post] node{\t} (v\j);
    \foreach \i/\j/\t in {S/E/2, E/S/1}
        \draw (v\i) edge[post, bend right=10] node{\t} (v\j);

\end{tikzpicture}

Residual graph, iteration 3:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {S/B/8, S/D/2, B/C/1, D/C/3, D/F/9, D/E/4, F/E/2, T/E/1, C/F/5, E/S/3}
        \draw (v\i) edge[post] node{\t} (v\j);
    \foreach \i/\j/\t in {F/T/5, T/F/2}
        \draw (v\i) edge[post, bend left=10] node{\t} (v\j);

\end{tikzpicture}

Residual graph, iteration 4:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {S/B/8, D/S/2, B/C/1, D/C/3, D/E/4, F/E/2, T/E/1, C/F/5, E/S/3}
        \draw (v\i) edge[post] node{\t} (v\j);
    \foreach \i/\j/\t in {F/T/3, T/F/4, D/F/7, F/D/2}
        \draw (v\i) edge[post, bend left=10] node{\t} (v\j);

\end{tikzpicture}

Residual graph, iteration 5:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {D/S/2, C/B/1, D/C/3, D/E/4, F/E/2, T/E/1, E/S/3}
        \draw (v\i) edge[post] node{\t} (v\j);
    \foreach \i/\j/\t in {S/B/7, B/S/1, C/F/4, F/C/1, F/T/2, T/F/5, D/F/7, F/D/2}
        \draw (v\i) edge[post, bend left=10] node{\t} (v\j);

\end{tikzpicture}

Original graph: Max flow of 6

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/S, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/T}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\f/\t in {S/B/1/8, S/D/2/2, S/E/3/3, B/C/1/1, D/C/0/3, D/F/2/9, D/E/0/4, E/F/2/2, E/T/1/1, C/F/1/5, F/T/5/7}
        \draw (v\i) edge[post] node{\f/\t} (v\j);

\end{tikzpicture}

\section{Kruskal’s Algorithm }
Minimum spanning tree, iteration 1:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/A, 0/4/B}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {A/B/1}
        \draw (v\i) edge node{\t} (v\j);

\end{tikzpicture}

Minimum spanning tree, iteration 2:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/A, 0/4/B, 10/0/E, 7/4/F}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {A/B/1, E/F/2}
        \draw (v\i) edge node{\t} (v\j);

\end{tikzpicture}

Minimum spanning tree, iteration 3:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/A, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {A/B/1, E/F/2, A/E/3, D/C/3}
        \draw (v\i) edge node{\t} (v\j);

\end{tikzpicture}

Minimum spanning tree, iteration 4:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/A, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/G}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {A/B/1, E/F/2, A/E/3, D/C/3, E/G/4, D/E/4}
        \draw (v\i) edge node{\t} (v\j);

\end{tikzpicture}

Minimum spanning tree, iteration 5:

\begin{tikzpicture}[shorten >=1pt, auto, node distance=3cm]

   \foreach [count=\i] \x/\y/\t in {0/0/A, 0/4/B, 3/4/C, 3/2/D, 10/0/E, 7/4/F, 10/4/G, 7/2/H}
     \node [circle,draw]
        (v\t) at (\x,\y) {\t};

    \foreach \i/\j/\t in {A/B/1, E/F/2, A/E/3, D/C/3, E/G/4, D/E/4, D/H/9}
        \draw (v\i) edge node{\t} (v\j);

\end{tikzpicture}
\end{document}


\section{UTxO}
\label{sec:utxo}

\begin{figure*}[htb]
  \emph{Derived types}
  %
  \begin{equation*}
    \begin{array}{r@{~\in~}l@{\qquad=\qquad}lr}
      \var{uin}
      & \UTxOIn
      & \TxId \times \Ix
%      & \text{transaction output preference}
      \\
      \var{uout}
      & \UTxOOut
      & (\TxOutND \uniondistinct \TxOutP) \times \Slot
%      & \text{transaction outputs}
      \\
      \var{utxo}
      & \UTxO
      & \UTxOIn \mapsto \UTxOOut
%      & \text{unspent tx outputs}
      \\
      \var{cur}
      & \ScriptPurpose
      & \PolicyID \uniondistinct \UTxOIn \uniondistinct \AddrRWD \uniondistinct \DCert
%      & \text{item the script is validated for}
    \end{array}
  \end{equation*}
  \caption{Definitions used in the UTxO transition system}
  \label{fig:defs:utxo-shelley-1}
\end{figure*}

We make a number of changes to the Shelley UTxO model~\ref{XX} to support the Goguen Extended UTxO model
(see Figure~\ref{fig:defs:utxo-shelley-1}).

\begin{itemize}
\item
  $\UTxO$ entries are stored in the finite map $\UTxOIn\mapsto \UTxOOut$.

\item
  $\UTxOIn$ is the same type as $\TxIn$ in Shelley, but we have changed
  the name because the types of transaction inputs and UTxO keys
  differ in Goguen.

\item
  $\UTxOOut$ is the type of UTxO entries.
  Note that, like in the case of the type of transaction inputs,
  this type differs from the type of the output of a transaction.
  Goguen UTxO entries include a slot number for each output
  that indicates when the output was created.
  This will be used for future functionality.

\item
  $\ScriptPurpose$ is the type of the items that scripts can validate.

\end{itemize}

\subsection{UTxO Transitions}
\label{sec:utxo-trans}

We have added several functions that deal with transaction and UTxO inputs and
outputs as shown in Figure \ref{fig:functions:insouts}. These are used in the definition of the UTxO transition system.

\begin{itemize}
  \item The function $\fun{txinputs_{vf}}$ returns only those transaction inputs
    that were selected to pay transaction fees (we call these ``fee-marked'' inputs).
    These inputs may only contain Ada.
    \begin{note}
      Make it more obvious that we check that the fee inputs only contain Ada, maybe mention it elsewhere. Also, what does vf stand for?
    \end{note}
  \item The predicate $\fun{feesOK}$ checks whether the transaction is
  paying the necessary fees, and that it does it correctly. That is, it checks that:
  \begin{enumerate}[label=({\roman*})]
    \item the fee-marked inputs are not locked by non-native scripts;
    \item all the fee-marked inputs contain strictly Ada and no other kinds of token;
    \item the fee-marked inputs are sufficient to cover the fee amount that is stated
    in the transaction; and
    \item the fee amount that the transaction states it is paying suffices to cover
    the minimum fee that the transaction is obligated to pay.
  \end{enumerate}
  \item The function $\fun{getOut}$ selects the data from a transaction output that
  will be stored in the UTxO, i.e. a $\UTxOOut$ without the slot number.
  \item The function $\fun{txins}$ returns the UTxO keys of transaction inputs.
\end{itemize}

Note that when creating a transaction, the wallet is responsible for
determining the fees. Thus, it also has to execute the non-native scripts
and include the fees for their execution.
\begin{figure}[htb]
  \begin{align*}
    & \fun{txinputs_{vf}} \in \TxBody \to \powerset{\TxId \times \Ix} \\
    & \fun{txinputs_{vf}} ~txb~= \\
    &~~\{ (txid,ix)~\vert~(txid,ix,\var{isfee}) \in
    \fun{txinputs} ~txb,~
     \var{isfee} = \True\}
    \nextdef
    & \fun{feesOK} \in \N \to \PParams \to \GoguenTx \to \UTxO \to \Bool  \\
    & \fun{feesOK} ~n~\var{pp}~tx~utxo~= \\
    &~~\fun{range}~(\fun{txinputs_{vf}}~{txb} \restrictdom \var{utxo}) \subseteq \TxOutND ~ \\
    &~~\wedge~ \var{balance} \in \Coin \\
    &~~      \wedge~ \var{balance} \geq \txfee{txb} ~ \\
    &~~      \wedge~ \minfee~n~{pp}~{tx} \leq \txfee{txb} \\
    &~~      \where \\
    & ~~~~~~~ \var{txb}~=~\txbody{tx} \\
    & ~~~~~~~ \var{balance}~=~\fun{ubalance}~(\fun{txinputs_{vf}}~{txb} \restrictdom \var{utxo})
    \nextdef
    & \fun{getOut} \in \TxOut \to \TxOutND \uniondistinct \TxOutP \\
    & \fun{getOut} ~{txout}~= \begin{cases}
         \var{txout}  & \text{if~} \var{txout} \in \TxOutND \\
              (\fun{getAddr}~\var{txout}, \fun{getValue}~\var{txout},
              \fun{getDataHash}~\var{txout}) & \text{otherwise}
            \end{cases}
    \nextdef
    & \fun{txins} \in \TxBody \to \powerset{\TxId \times \Ix} \\
    & \fun{txins} ~\var{txb} = \{(txid,ix) \mid ((txid,ix),\wcard)\in\fun{txinputs} ~txb\}
  \end{align*}
  \caption{Functions on Tx Inputs and Outputs.}
  \label{fig:functions:insouts}
\end{figure}
%
Figure~\ref{fig:functions:utxo} defines the functions that are needed for the UTxO transition system.
The changes that are needed for Plutus integration are:

\begin{itemize}

  \item The $\fun{getCoin}$ function sums all the Ada in a given output and returns it as a
  $\Coin$ value.

  \item The function $\fun{outs}$ discards the $\HasDV$ tag from a
  transaction output and adds the slot number of the block in which the transaction is
  included.

  \item $\fun{txscriptfee}$ calculates the fee that a transaction must pay for script
  execution based on the amount of $\ExUnits$ it has budgeted, and the prices in the current protocol parameters
  for each component of $\ExUnits$.

  \item The minimum fee calculation, $\fun{minfee}$, includes the script
  fees that the transaction is obligated to pay in order to run its scripts.

  \item The $\fun{produced}$ calculation requires the current slot number as an argument -- this is
  needed to construct the correct UTxO outputs.
\end{itemize}

Since the $\Tx$ type combines both $\ShelleyTx$ and $\GoguenTx$, and
there was already a way of computing an ID from a Shelley transaction, there
is potential for confusion how the ID of a transaction is
computed. Here, $\TxId$ is always computed from values of type $\Tx$,
\emph{and never from the underlying $\ShelleyTx$ or $\GoguenTx$}.  That is, there is a \emph{canonical} ID for each Goguen transaction,
and this is not necessarily the same as the corresponding ID in the underlying Shelley or Goguen transaction type.

\begin{figure}[htb]
  \emph{Helper Functions}
  \begin{align*}
    & \fun{getCoin} \in \UTxOOut \to \Coin \\
    & \fun{getCoin}~{\var{out}} ~=~\sum_{\mathsf{adaID} \mapsto tkns \in \fun{getValue}~out}
       (\sum_{q \in \range~{tkns}} \fun{co}~q)
  \end{align*}
  %
  \emph{Main Calculations}
  \begin{align*}
    & \fun{outs} \in \Slot \to \TxBody \to \UTxO \\
    & \fun{outs} ~ \var{slot}~\var{txb} =
        \left\{
          (\fun{txid} ~ \var{txb}, \var{ix}) \mapsto (\fun{getOut}~\var{txout},\var{slot}) ~
          \middle|~
          \var{ix} \mapsto \var{txout} \in \txouts{txb}
        \right\}
    \nextdef
    & \fun{txscriptfee} \in \N \to \Prices \to \ExUnits \to \Coin \\
    & \fun{txscriptfee}~n~ (\var{pr_{init}, pr_{mem}, pr_{steps}})~ (\var{mem, steps})
    = \var{pr_{init}}*n + \var{pr_{mem}}*\var{mem} + \var{pr_{steps}}*\var{steps}
    \nextdef
    &\fun{minfee} \in \N \to \PParams \to \GoguenTx \to \Coin \\
    &\fun{minfee}  ~n~\var{pp}~\var{tx} = \\
    &~~(\fun{a}~\var{pp}) \cdot \fun{txSize}~\var{tx} + (\fun{b}~\var{pp}) +
    \fun{txscriptfee}~n~(\fun{prices}~{pp})~(\fun{txexunits}~(\fun{txbody}~{tx}))
    \nextdef
    & \fun{produced} \in \Slot \to \PParams \to \StakePools \to \TxBody \to \Value \\
    & \fun{produced}~\var{slot}~\var{pp}~\var{stpools}~\var{txb} = \\
    &~~\ubalance{(\outs{slot}~{txb})} + \fun{coinToValue}(\txfee{txb} + \deposits{pp}{stpools}~{(\txcerts{txb})})
  \end{align*}
  \caption{Functions used in UTxO rules}
  \label{fig:functions:utxo}
\end{figure}

\subsection{Combining Scripts with Their Inputs}
\label{sec:scripts-inputs}

Figure~\ref{fig:functions:script1} shows the helper functions that are needed to
retrieve all the data that is relevant to Plutus script validation.
These include:

\begin{itemize}
\item
  $\fun{indexof}$ finds the index of a given certificate, value, input, or
  withdrawal in a list, finite map, or set of such objects.
  This function assumes there is some ordering on each of these structures.
%  This function is abstract because it assumes there is some ordering rather
%  than giving it explicitly.
  \begin{note}
    $\fun{indexof}$ might need an actual implementation. Also, some
    restructuring in related functions might make it easier.
    Sets and maps don't really have indexes, of course.
  \end{note}
\item
  $\fun{indexedScripts}$ and $\fun{indexedDats}$ create finite maps from sets of the corresponding object.
  The finite maps are indexed by the hashes of the objects that they contain.
%
%  wherein, respectively, all the scripts
%  and datums that a transaction carries as sets, are indexed by their hashes.
\item
  $\fun{findRdmr}$ finds the redeemer in a Goguen transaction
   that corresponds to a given item in the indexed redeemer structure, if it exists.
\end{itemize}

\begin{figure}[htb]
  %
  \emph{Abstract functions}
  \begin{align*}
    &\fun{indexof} \in \DCert \to \seqof{\DCert} \to \Ix\\
    &\fun{indexof} \in \AddrRWD \to \Wdrl \to \Ix\\
    &\fun{indexof} \in \UTxOIn \to \powerset{\TxIn} \to \Ix\\
    &\fun{indexof} \in \PolicyID \to \Value \to \Ix\\
    & \text{get the index of an item in an ordered representation}
  \end{align*}
  %
  \emph{Helper functions}
  \begin{align*}
    &\fun{indexedScripts} \in \GoguenTx \to (\ScriptHash \mapsto \Script) \\
    &\fun{indexedScripts}~{tx} ~=~ \{ h \mapsto s ~\vert~ \fun{hashScript}~{s}~=~h,
     s\in~\fun{txscripts}~(\fun{txwits}~{tx})\}
    \nextdef
    &\fun{indexedDats} \in \GoguenTx \to (\DataHash \mapsto \Data)\\
    &\fun{indexedDats}~{tx} ~=~ \{ h \mapsto d ~\vert~ \fun{hashData}~{d}~=~h,
     d\in~\fun{txdats}~(\fun{txwits}~{tx})\}
    \nextdef
    &\fun{toRdmrPtr} \in \GoguenTx \to \ScriptPurpose \to \RdmrPtr \\
    &\fun{toRdmrPtr}~{tx}~{it} ~=~
      \begin{cases}
        (\mathsf{certTag},\fun{indexof}~\var{it}~(\fun{txcerts}~{txb}))   & \var{it}~\in~\DCert \\
        (\mathsf{wdrlTag},\fun{indexof}~\var{it}~(\fun{txwdrls}~{txb}))   & \var{it}~\in~\AddrRWD \\
        (\mathsf{forgeTag},\fun{indexof}~\var{it}~(\fun{forge}~{txb}))    & \var{it}~\in~\PolicyID \\
        (\mathsf{inputTag},\fun{indexof}~\var{it}~(\fun{txinputs}~{txb})) & \var{it}~\in~\UTxOIn
      \end{cases} \\
    & ~~\where \\
    & ~~~~~~~ \var{txb}~=~\txbody{tx}
    \nextdef
    &\fun{findRdmr} \in \GoguenTx \to (\ScriptPurpose \mapsto \Data)\\
    & \fun{findRdmr}~{tx} ~=~ \{ \var{it} \mapsto \var{d} ~|~
      \var{it} \in \ScriptPurpose,~ \fun{toRdmrPtr}~{tx}~{it} \mapsto \var{d} \in \fun{txrdmrs}~(\fun{txwits}~{tx}) \}
  \end{align*}
  \caption{Combining Script Validators and their Inputs}
  \label{fig:functions:script1}
\end{figure}

\textbf{Plutus Script Validation}
Figure~\ref{fig:defs:functions-valid} shows the abstract functions that are used for script validation.

\begin{itemize}
\item
  $\fun{valContext}$ constructs the validation context.
  This includes all the necessary transaction and chain state data that needs to be passed to the script interpreter.
    It has a $\UTxO$ as its argument to recover the full information of the inputs of the transaction,
    but only the inputs of the transaction are provided to scripts.
\item
    $\fun{hashScript},~ \fun{hashData}$ are abstract hashing functions.
\item
  $\fun{runMSigScript}$ validates multi-signature scripts, exactly as in the Shelley ledger specification (where it is called $\fun{evaluateScript}$).
\item
  $\fun{runPLCScript}$ validates Plutus scripts. It takes the following
  arguments:
  \begin{itemize}
  \item A cost model, that is used to calculate the $\ExUnits$ that are needed for script execution;
  \item A list of terms of type $\Data$ that will be passed to the script; %is given access to.
  \item The execution unit budget.
  \end{itemize}
  It outputs a pair of the validation result (as a Boolean)
  and the remaining execution units (subtracting those that are used for script execution).
  Note that script execution stops if the full budget has been spent before validation is complete.
\end{itemize}
\begin{note}
  Maybe rename runPLCScript.
\end{note}

\begin{note}
  \textbf{Know your contract arguments}
  A Plutus validator script may receive either a list of three terms of type $\Data$, in case it validates the spending of script outputs
  or two terms (redeemer and context, with no datum), for all other uses.
  Script authors must keep this in mind when writing scripts, since the ledger call to the interpreter is oblivious to what
  arguments are required.
\end{note}

\begin{figure*}[htb]
  \emph{Abstract Script Validation Functions}
  %
  \begin{align*}
     &\fun{hashScript} \in  ~\Script\to \ScriptHash \\
     &\text{Compute script hash} \\~\\
     &\fun{hashData} \in  ~\Data \to \DataHash \\
     &\text{Compute hash of data} \\~\\
     &\fun{valContext} \in  \UTxO \to \GoguenTx \to \ScriptPurpose \to \Data \\
     &\text{Build Validation Data} \\~\\
     &\fun{runMSigScript} \in\ScriptMSig\to \GoguenTx \to \IsValidating  \\
     &\text{Validate a multi-signature script} \\~\\
     &\fun{runPLCScript} \in \CostMod \to\ScriptPlutus \to
    \seqof{\Data} \to \ExUnits \to (\IsValidating \times \ExUnits) \\
     &\text{Validate a Plutus script, taking resource limits into account}
  \end{align*}
  %
  \emph{Notation}
  %
  \begin{align*}
    \llbracket \var{script_v} \rrbracket_{\var{cm},\var{exunits}}~\var{d}
    &=& \fun{runPLCScript} ~{cm}~\var{script_v}~\var{d}~\var{exunits}
  \end{align*}
  \caption{Script Validation, cont.}
  \label{fig:defs:functions-valid}
\end{figure*}

Note that no ``checks'' are performed within the functions that match the
scripts with their inputs. Missing validators, missing inputs, incorrect hashes, the wrong type of script etc,
are caught during the application of the UTXOW rule (before these functions are ever applied).
%
Various items of data are involved in building the inputs for script validation:

\begin{itemize}
\item The hash of the validator script;

\item The hash of the required datum, if any;

\item The corresponding full validator and datum object, which are looked up in the finite map
constructed by $\fun{indexedScripts}$ and $\fun{indexedDats}$, respectively;

\item The redeemer, which is contained in the transaction's indexed redeemer structure
and which is located using the $\fun{findRdmr}$ function; and

\item the validation data, built using the UTxO, the transaction itself,
and the current item being validated.
\end{itemize}

\begin{figure}[htb]
  \begin{align*}
    & \fun{getData} \in \GoguenTx \to \UTxO \to \ScriptPurpose \to \seqof{\Data} \\
    & \fun{getData}~{tx}~{utxo}~{it}~=~
      \begin{cases}
        [\var{d}] & \var{it} \mapsto ((a,\_),h_d, \_) \in \var{utxo}, \var{h_d}\mapsto \var{d} \in \fun{indexedDats}~{tx} \\
        \epsilon  & \text{otherwise}
      \end{cases}
    \nextdef
    & \fun{mkPLCLst} \in \PParams \to \GoguenTx \to \UTxO \to \seqof{(\ScriptPlutus \times \seqof{\Data} \times \CostMod)} \\
    & \fun{mkPLCLst} ~\var{pp}~\var{tx}~ \var{utxo} ~=~ \\
    & ~~\fun{toList} \{ (\var{script}, (r; \fun{valContext}~\var{utxo}~\var{tx}~\var{cur}; \fun{getData}~{tx}~{utxo}~{cur}), \var{cm}) \mid \\
    & ~~~~(\var{cur}, \var{scriptHash}) \in \fun{scriptsNeeded}~{tx}~{utxo}, \\
    & ~~~~\var{cur} \mapsto \var{r} \in \fun{findRdmr}~{tx}, \\
    & ~~~~\var{scriptHash}\mapsto \var{script}\in \fun{indexedScripts}~{tx}, \\
    & ~~~~\fun{language}~{script} \mapsto \var{cm} \in \fun{costmdls}~{pp} \}
  \end{align*}
  \caption{Scripts and their Arguments}
  \label{fig:functions:script2}
\end{figure}

\subsection{Two-Phase Transaction Validation for Non-Native Scripts}
\label{sec:two-phase}

\begin{note}
  Make it more obvious somewhere where native vs non-native scripts are processed.
\end{note}

The costs of processing native scripts (those that involve only executing standard ledger rules) are included in the standard transaction fees.
In order to ensure that users pay for the computational resources that are needed to validate non-native scripts, even
if transactions are invalid, transactions are validated in two phases:
the first phase consists of every aspect of transaction validation apart from executing the non-native scripts; and
the second phase involves actually executing those scripts.
%
Our validation approach  uses four transition systems, each with different responsibilities. We
give the details of each below, but to summarize, when a transction is processed,
the processing is done
in the following order:

\begin{tabular}{lp{12cm}}
  \textbf{(UTXOW):} & Verifies that all the necessary witnessing information is present, including
  VKey witnesses, scripts, and all the script input data. It also performs
  key witness checks and runs multisig scripts. It then applies the state changes that are
  computed by the UTXO transition.
  \\
  \textbf{(UTXO):} & Verifies that a transaction satisfies all the accounting requirements
  (including the general accounting property, correct fee payment, etc.),
  and applies the state changes that are computed by the UTXOS transition.
  \\
  \textbf{(UTXOS):} & Performs the appropriate UTxO state changes, based on the
  value of the $\IsValidating$ tag, which it checks using the SVAL transition.
  \\
  \textbf{(SVAL):} & Runs the scripts, verifying that the $\IsValidating$ tag
  is applied correctly.
\end{tabular}

In general, there is no way to check that the budget that has been supplied is sufficient for the transaction,
except by running the scripts. To avoid over-spending the budget, we run them sequentially,
stopping whenever one does not validate, and charging the transaction the corresponding
fees. From the point of view of the ledger, there is no difference
between a script running out of $\ExUnits$ during validation, or not validating.
If a transaction contains an invalid script, the only change to the ledger
as a result of applying this transaction is the fees.

Two-phase validation requires a new transition system
(see Figure \ref{fig:ts-types:utxos}) to sequentially run
scripts and to track spent execution units as part of its state
($\var{remExU}$). The signal here is a sequence of pairs of a validator
script and the corresponding input data.

Note that there is one state variable in the SVAL transition system. The reason
for this is that in the second, script-running validation phase, we separate
the UTxO state update from sequentially running scripts. This transition
system is strictly for running the scripts, and a transition of this type
will be used by another rule to perform the correct UTxO update.

Running scripts sequentially
to verify that they all validate in the allotted $\ExUnits$ budget only requires
the amount of remaining $\ExUnits$ to be included in the state, and nothing else.
In the environment, we need the protocol parameters and the
transaction being validated. All other data needed
to run the scripts comes from the signal.

\begin{figure}[htb]
  \emph{Validation environment}
  \begin{equation*}
    \ValEnv =
    \left(
      \begin{array}{r@{~\in~}lr}
        \var{pp} & \PParams & \text{protocol parameters}\\
        \var{tx} & \GoguenTx & \text{transaction being processed} \\
      \end{array}
    \right)
  \end{equation*}
  %
  \emph{Validation state}
  \begin{equation*}
    \ValState =
    \left(
      \begin{array}{r@{~\in~}lr}
        \var{remExU} & \ExUnits & \text{exunits remaining to spend on validation} \\
      \end{array}
    \right)
  \end{equation*}
  %
  \emph{Script transitions}
  \begin{equation*}
    \_ \vdash
    \var{\_} \trans{sval}{\_} \var{\_}
    \subseteq \powerset (\ValEnv \times \ValState \times \seqof{(\ScriptPlutus\times\seqof{\Data}\times\CostMod)} \times \ValState)
  \end{equation*}
  %
  \caption{UTxO script validation types}
  \label{fig:ts-types:utxos}
\end{figure}

The rules for the second-phase script validation SVAL are given in
Figure~\ref{fig:rules:utxo-scrval}. Again, no UTxO state update
is done in this rule. Its purpose is to verify that the
validation tag ($\fun{txvaltag}$) is applied correctly by the creater of
the block. It does this by running all the scripts.

Note that following the Shelley ledger specification approach, every function
that we define and use in the preconditions or calculations that are used in the ledger rules is
necessarily total.
In this way, all the errors (validation failures) that we encounter always come from
rule applications, i.e. a precondition of a rule is not met.
We mention this here because the SVAL rule looks as if it could be
simply a function. However, we want the incorrect application of the
validation tag to be an error, so this must be an error that comes form
an unmet precondition of a rule.

There are three transition rules.
The first rule, $\mathsf{Scripts\mbox{-}Val}$, applies when:

\begin{enumerate}
\item There
are no scripts left to validate in the signal list (i.e. this is the base case of
induction when all the scripts have validated) -- note that there could be $\ExUnits$ left over; and
\item The validation tag is applied correctly (it is $\True$).
\end{enumerate}

The $\mathsf{Scripts\mbox{-}Stop}$ rule applies when:

\begin{enumerate}
  \item The current script-input pair  does not validate;
  (either because the transaction ran out of $\ExUnits$ or for any other reason); and
  \item The validation tag is correct ($\False$ in this case).
\end{enumerate}

These first two rules require no state change.
The $\mathsf{Scripts\mbox{-}Ind}$ rule applies when:

\begin{enumerate}
  \item The current script being validated has been validated;
  \item There is a non-negative fee which remains to pay for validating
  the rest of the scripts in the list; and
  \item Transition rules apply for the rest of the list (without the current script).
\end{enumerate}

The only state change in this rule is of the variable $\var{remExU}$.
It is decreased by subtracting the cost of the execution of the
current script from its current value.
We use this variable to keep track of the remaining funds for
script execution. If the transaction is overpaying ($\fun{txscriptfee}~{tx}$
is too big), then the whole fee is still taken.

It is always in the interest of the slot leader to have the new block validate,
and for it to contain only valid transactions. This motivates the
slot leader to:

\begin{enumerate}
  \item Correctly apply the $\IsValidating$ tag;
  \item Include all transactions that validate,
  \textit{even in case of a 2nd step script validation failure};
  \item Exclude any transactions that are invalid in some way \textit{other than 2nd step script validation failure}.
\end{enumerate}

We want to
discard the blocks which have transactions with these tags
applied incorrectly.
One of the reasons for having the correct validation tag added by the slot leader
to a transaction is that re-applying blocks would not require repeat
execution of scripts in the transactions inside a block. In fact, when replaying
blocks, all the witnessing information can be thrown away.
We also rely on the correct use of tags in other rules (at this time, only in
the rules that are shown in Figure \ref{fig:rules:ledger}).

\textbf{Non-integral calculations within the Plutus interpreter.} At present, all Plutus calculations use integral types. If there
will be any future non-integral calculations (e.g. from the Actus contracts that are implemented using
the Marlowe interpreter), these should
be performed exactly as in the Shelley ledger (as described in~\cite{non_int}). This is a matter of
ensuring deterministic script validation outcomes: inconsistent rounding, for example, could
result in different validation outcomes running the same script on the same
arguments.

\begin{figure}[htb]
  \begin{equation}
    \inference[Scripts-Val]
    {
    \fun{txvaltag}~\var{tx} = \True  &
    \var{remExU}~\geq~0
    }
    {
    \begin{array}{l}
      \var{pp}\\
      \var{tx}\\
    \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{remExU}\\
      \end{array}
      \right)
      \trans{sval}{\epsilon}
      \left(
      \begin{array}{r}
        \var{remExU}\\
      \end{array}
      \right) \\
    }
  \end{equation}
  \begin{equation}
    \inference[Scripts-Stop]
    { \\~\\
    (\var{isVal},\var{remExU'})~:=~ \llbracket sc \rrbracket_
    {cm,\var{remExU}} dt \\
    (sc, dt, cm) := s
    \\
    ~
    \\
    \fun{txvaltag}~\var{tx} = \False &
    (\var{remExU'}~<~0 ~ \lor ~ \var{isVal} = \False)
    }
    {
    \begin{array}{l}
      \var{pp}\\
      \var{tx}\\
    \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{remExU}\\
      \end{array}
      \right)
      \trans{sval}{\Gamma;s}
      \left(
      \begin{array}{r}
        \var{remExU}\\
      \end{array}
      \right)
    }
  \end{equation}
  \begin{equation}
    \inference[Scripts-Ind]
    {
    {
    \begin{array}{l}
      \var{pp}\\
      \var{tx}\\
    \end{array}
    }
      \vdash
      \left(
      {
      \begin{array}{r}
        \var{remExU}\\
      \end{array}
      }
      \right)
      \trans{sval}{\Gamma}
      \left(
      {
      \begin{array}{r}
        \var{remExU'}\\
      \end{array}
      }
      \right) \\
    (\var{isVal},\var{remExU''})~:=~ \llbracket sc \rrbracket
    _{cm,\var{remExU'}} dt \\
    (sc, dt, cm) := s & \var{remExU''}~\geq~0
    }
    {
    \begin{array}{l}
      \var{pp}\\
      \var{tx}\\
    \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{remExU}\\
      \end{array}
      \right)
      \trans{sval}{\Gamma;s}
      \left(
      \begin{array}{r}
        \varUpdate{remExU''}\\
      \end{array}
      \right)
    }
  \end{equation}
  \caption{Script validation rules}
  \label{fig:rules:utxo-scrval}
\end{figure}

\subsection{Updating the UTxO State}
\label{sec:utxo-state-trans}

We have defined a separate transition system, UTXOS, to represent the two distinct
UTxO state changes, one resulting from all scripts in a transaction validating,
the other - from at least one failing to validate. Its transition types
are all the same as for the for the UTXO transition, see Figure
\ref{fig:ts-types:utxo-scripts}.

\begin{figure}[htb]
  \emph{State transitions}
  \begin{equation*}
    \_ \vdash
    \var{\_} \trans{utxo, utxos}{\_} \var{\_}
    \subseteq \powerset (\UTxOEnv \times \UTxOState \times \GoguenTx \times \UTxOState)
  \end{equation*}
  %
  \caption{UTxO and UTxO script state update types}
  \label{fig:ts-types:utxo-scripts}
\end{figure}

There are two rules, corresponding to the two possible state changes of the
UTxO state in the UTXOS transition system (Figure~\ref{fig:rules:utxo-state-upd}).
%
In both cases, the SVAL transition is called upon to verify that the $\IsValidating$
tag has been applied correctly. The function $\fun{mkPLCLst}$ is used to build
the signal list $\var{sLst}$ for the SVAL transition.
%
The first rule
applies when the validation tag is $\True$.
In this case, the states of the UTxO, fee
  and deposit pots, and updates are updated exactly as in the current Shelley
  ledger spec.
%
  The second rule
  applies when the validation tag is $\False$.
  In this case, the UTxO state changes as follows:

  \begin{enumerate}
    \item All the
    UTxO entries corresponding to the transaction inputs selected for covering
    script fees are removed;

    \item The sum total of the value of the marked UTxO entries
    is added to the fee pot.
  \end{enumerate}

\begin{figure}[htb]
  \begin{equation}
    \inference[Scripts-Yes]
    {
    \var{txb}\leteq\txbody{tx} &
    \fun{txvaltag}~\var{tx} = \True
    \\
    ~
    \\
    \var{sLst} := \fun{mkPLCLst}~\var{pp}~\var{tx}~\var{utxo}
    \\~\\
    {
      \left(
        \begin{array}{r}
          \var{pp} \\
          \var{tx} \\
        \end{array}
      \right)
    }
      \vdash
        \var{\fun{txexunits}~{tx}}
      \trans{sval}{sLst}\var{remExU}
      \\~\\
    {
      \left(
        \begin{array}{r}
          \var{slot} \\
          \var{pp} \\
          \var{genDelegs} \\
        \end{array}
      \right)
    }
    \vdash \var{ups} \trans{\hyperref[fig:rules:update]{up}}{\fun{txup}~\var{tx}} \var{ups'}
    \\~\\
    \var{refunded} \leteq \keyRefunds{pp}{stkCreds}~{txb}
    \\
    \var{depositChange} \leteq
      (\deposits{pp}~{stpools}~{(\txcerts{txb})}) - \var{refunded}
    }
    {
    \begin{array}{l}
      \var{slot}\\
      \var{pp}\\
      \var{stkCreds}\\
      \var{stpools}\\
      \var{genDelegs}\\
    \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{utxo} \\
        \var{deposits} \\
        \var{fees} \\
        \var{ups} \\
      \end{array}
      \right)
      \trans{utxos}{tx}
      \left(
      \begin{array}{r}
        \varUpdate{\var{(\txins{txb} \subtractdom \var{utxo}) \cup \outs{slot}~{txb}}}  \\
        \varUpdate{\var{deposits} + \var{depositChange}} \\
        \varUpdate{\var{fees} + \txfee{txb}} \\
        \varUpdate{\var{ups'}} \\
      \end{array}
      \right) \\
    }
  \end{equation}
  \begin{equation}
    \inference[Scripts-No]
    {
    \var{txb}\leteq\txbody{tx} &
    \fun{txvaltag}~\var{tx} = \False
    \\
    ~
    \\
    \var{sLst} := \fun{mkPLCLst}~\var{pp}~\var{tx}~\var{utxo}
    \\~\\
    {
      \left(
        \begin{array}{r}
          \var{pp} \\
          \var{tx} \\
        \end{array}
      \right)
    }
      \vdash
        \var{\fun{txexunits}~{tx}}
      \trans{sval}{sLst}\var{remExU}
    }
    {
    \begin{array}{l}
      \var{slot}\\
      \var{pp}\\
      \var{stkCreds}\\
      \var{stpools}\\
      \var{genDelegs}\\
    \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{utxo} \\
        \var{deposits} \\
        \var{fees} \\
        \var{ups} \\
      \end{array}
      \right)
      \trans{utxos}{tx}
      \left(
      \begin{array}{r}
        \varUpdate{\var{\fun{txinputs_{vf}}~{txb} \subtractdom \var{utxo}}}  \\
        \var{deposits} \\
        \varUpdate{\var{fees} + \fun{ubalance}~(\fun{txinputs_{vf}}~{txb}\restrictdom \var{utxo})} \\
        \var{ups} \\
      \end{array}
      \right)
    }
  \end{equation}
  \caption{State update rules}
  \label{fig:rules:utxo-state-upd}
\end{figure}

Figure \ref{fig:rules:utxo-shelley} shows the $\type{UTxO-inductive}$
transition rule for the UTXO transition type. Note that the
signal for this transition is specifically of type $\GoguenTx$, so it does not
work with Shelley transactions. Thus, the UTXOW rule needs to convert a $\Tx$ into
a $\GoguenTx$ to invoke the UTXO rule.
This rule has the following preconditions (plus the relevant ones
from the original Shelley specification):

\begin{enumerate}
  \item The transaction is being processed within its validity interval;

  \item The transaction has at least one input;

  \item All inputs in a transaction correspond to UTxO entries;

  \item The general accounting property holds;

  \item The transaction pays fees correctly;

  \item The transaction is not forging any Ada;

  \item All outputs of the transaction contain only non-negative quantities;

  \item The transaction size does not exceed the maximum limit;

 \item The execution units budget that a transaction gives does not exceed the maximum
  permitted number of units;

  \item The UTXOS state transition is valid.
\end{enumerate}

The resulting state transition is defined entirely by the application of the
UTXOS rule.

\begin{figure}[htb]
  \begin{equation}\label{eq:utxo-inductive-shelley}
    \inference[UTxO-inductive]
    {
      \var{txb}\leteq\txbody{tx} &
      \var{txw}\leteq\fun{txwits}~{tx} \\
      \fun{txfst}~txb \leq \var{slot}
      & \fun{txttl}~txb \geq \var{slot}
      \\
      \txins{txb} \neq \emptyset
      & \txins{txb} \subseteq \dom \var{utxo}
      \\
      \consumed{pp}{utxo}{stkCreds}{rewards}~{txb} = \produced{slot}~{pp}~{stpools}~{txb}
      \\~\\
      \fun{feesOK}~(\vert~ \fun{txscripts}~{tx} \cap \ScriptPlutus ~\vert) ~pp~tx~utxo \\
      \\
      ~
      \\
      \mathsf{adaID}~\notin \dom~{\fun{forge}~tx} \\
      \forall txout \in \txouts{txb}, ~ \fun{getValue}~txout  ~\geq ~ 0 \\~
      \forall txout \in \txouts{txb}, ~ \fun{getCoin}~txout ~\geq \\
      \fun{valueSize}~(\fun{getValue}~txout) * \fun{minUTxOValue}~pp \\~
      \\
      \fun{txsize}~{tx}\leq\fun{maxTxSize}~\var{pp} \\
      \fun{txexunits}~{txb} \leq \fun{maxTxExUnits}~{pp}
      \\
      ~
      \\
      {
        \begin{array}{c}
          \var{slot}\\
          \var{pp}\\
          \var{stkCreds}\\
          \var{stpools}\\
          \var{genDelegs}\\
        \end{array}
      }
      \vdash
      {
        \left(
          \begin{array}{r}
            \var{utxo} \\
            \var{deposits} \\
            \var{fees} \\
            \var{ups}\\
          \end{array}
        \right)
      }
      \trans{utxos}{\var{tx}}
      {
        \left(
          \begin{array}{r}
            \var{utxo'} \\
            \var{deposits'} \\
            \var{fees'} \\
            \var{ups'}\\
          \end{array}
        \right)
      }
    }
    {
      \begin{array}{l}
        \var{slot}\\
        \var{pp}\\
        \var{stkCreds}\\
        \var{stpools}\\
        \var{genDelegs}\\
      \end{array}
      \vdash
      \left(
      \begin{array}{r}
        \var{utxo} \\
        \var{deposits} \\
        \var{fees} \\
        \var{ups}\\
      \end{array}
      \right)
      \trans{utxo}{tx}
      \left(
      \begin{array}{r}
        \varUpdate{\var{utxo'}}  \\
        \varUpdate{\var{deposits'}} \\
        \varUpdate{\var{fees'}} \\
        \varUpdate{\var{ups'}}\\
      \end{array}
      \right)
    }
  \end{equation}
  \caption{UTxO inference rules}
  \label{fig:rules:utxo-shelley}
\end{figure}

\subsection{Witnessing}
\label{sec:wits}

Because of two-phase transaction validation, Plutus script validation is not part of transaction witnessing.
However, native script validation does remain part of transaction witnessing.
When witnessing a transaction, we therefore need to validate only the native scripts.
We have consequently changed the definition of the function
$\fun{scriptsNeeded}$, see Figure~\ref{fig:functions-witnesses} to include both multi-signature and Plutus scripts, plus the scripts that are used for any
validation purpose (forging, outputs, certificates, withdrawals).

\begin{figure}[htb]
  \begin{align*}
    & \hspace{-1cm}\fun{scriptsNeeded} \in \UTxO \to \GoguenTx \to \powerset (\ScriptPurpose \times \ScriptHash) \\
    & \hspace{-1cm}\fun{scriptsNeeded}~\var{utxo}~\var{tx} = \\
    & ~~\{ (\var{i}, \fun{validatorHash}~a) \mid i \mapsto (a, \wcard) \in \var{utxo},\\
    & ~~~~~i\in\fun{txinsScript}~{(\fun{txins~\var{txb}})}~{utxo}\} \\
    \cup & ~~\{ (\var{a}, \fun{stakeCred_{r}}~\var{a}) \mid a \in \dom (\AddrRWDScr
           \restrictdom \fun{txwdrls}~\var{txb}) \} \\
    \cup & ~~\{ (\var{cert}, \var{c}) \mid \var{cert} \in (\DCertDeleg \cup \DCertDeRegKey)\cap\fun{txcerts}~(\txbody{tx}), \\
    & ~~~~~~\var{c} \in \cwitness{cert} \cap \AddrScr\} \\
      \cup & ~~\{ (\var{pid}, \var{pid}) \mid \var{pid} \in \supp~(\fun{forge}~\var{txb}) \} \\
    & \where \\
    & ~~~~~~~ \var{txb}~=~\txbody{tx}
  \end{align*}
  \caption{Scripts Needed}
  \label{fig:functions-witnesses}
\end{figure}

In the Goguen era, we must be able to validate both Shelley transactions
and Goguen transactions. To do this, we transform any Shelley transactions
into Goguen ones, filling any missing data fields with default values.
The only time that we need the original Shelley transaction is to check the signatures
in the hash of the original transaction body, as shown in
Figure~\ref{fig:rules:utxow-goguen}. In addition to the Shelley UTXOW preconditions
that still apply, we have made the following changes and additions:

\begin{itemize}

    \item All the multi-signature scripts in the transaction validate;

    \item The transaction contains exactly those scripts that are required for witnessing and no
    additional ones (this includes all languages of scripts, for all purposes);

    \item The transaction contains a redeemer for every item that needs to be  validated
      by a Plutus script;

    \item The only certificates that are allowed to have scripts as witnesses
    are delegation de-registration certificates;

    \item The transaction has a datum for every Plutus script output that it spends;

    \item The transaction has a datum for every Plutus script output that is
    marked with the $\True$ tag for $\HasDV$;

    \item
    The hash of the subset of protocol parameters in the transaction body is equal to
    the hash of the same subset of protocol parameters that are currently on the ledger;

    \item The hash of the indexed redeemer structure that is attached to the transaction is
    the same as $\fun{rdmrsHash}~{tx}$ (the hash value that is contained in the signed body of
    the transaction).

\end{itemize}

If these conditions are all satisfied, then the resulting UTxO state change is fully determined
by the UTXO transition (the application of which is also part of the conditions).

\begin{figure}[htb]
  \emph{State transitions}
  \begin{equation*}
    \_ \vdash
    \var{\_} \trans{utxow}{\_} \var{\_}
    \subseteq \powerset (\UTxOEnv \times \UTxOState \times \Tx \times \UTxOState)
  \end{equation*}
  %
  \caption{UTxO with witnesses state update types}
  \label{fig:ts-types:utxo-witness}
\end{figure}

\begin{figure}
  \begin{equation}
    \label{eq:utxo-witness-inductive-goguen}
    \inference[UTxO-witG]
    {
      \var{tx}~\leteq~\fun{toGoguenTx}~{tx}_o \\~\\
      \var{txb}\leteq\txbody{tx} &
      \var{txw}\leteq\fun{txwits}~{tx} &
      \var{tx}~\in~\GoguenTx \\
      (utxo, \wcard, \wcard, \wcard) \leteq \var{utxoSt} \\
      \var{witsKeyHashes} \leteq \{\fun{hashKey}~\var{vk} \vert \var{vk} \in
      \dom (\txwitsVKey{txw}) \}\\~\\
      \forall \var{validator} \in \fun{txscripts}~{txw} \cap \ScriptMSig,\\
      \fun{runMSigScript}~\var{validator}~\var{tx}\\~\\
      \{ h \mid (\wcard, h) \in \fun{scriptsNeeded}~\var{utxo}~\var{tx}\} ~=~ \dom (\fun{indexedScripts}~{tx}) \\
      \forall (\var{purp}, h) \in ~\fun{scriptsNeeded}~\var{utxo}~\var{tx}, ~h\mapsto s~\in~\fun{indexedScripts}~{tx},\\
       s \in \ScriptPlutus~\Leftrightarrow \exists r, \var{purp} \mapsto r \in \fun{findRdmr}~{tx}
      \\~\\
      \forall \var{cert}~\in~\fun{txcerts}~{txb}, \fun{regCred}~{cert}\in \PolicyID \Leftrightarrow
      \var{cert} \in~ \DCertDeRegKey \\~\\
      \forall~\var{txin}\in\fun{txinputs}~{txb},
      \var{txin} \mapsto \var{(\wcard,\wcard,h_d)} \in \var{utxo},
      \var{h_d} ~\in \fun{dom}(\fun{indexedDats}~{tx})
      \\
      ~
      \\
      \forall~ix \mapsto (a,v,d_h,\True) ~\in~\fun{txouts}~{txb}, \\
       \var{d_h}\in \fun{dom}~ (\fun{indexedDats}~{tx})
      \\
      ~
      \\
      \fun{ppHash}~{txb}~=~\fun{hashLanguagePP}~\var{pp}~(\fun{cmlangs}~(\fun{txscripts}~\var{txw})) \\~\\
      \fun{txrdmrs}~\var{txw} ~=~ \emptyset \Leftrightarrow \fun{rdmrsHash}~{txb}~=~\Nothing \\
      \fun{txrdmrs}~\var{txw} ~\neq~ \emptyset \Leftrightarrow
      \fun{hash}~(\fun{txrdmrs}~\var{txw})~ =~  \fun{rdmrsHash}~{txb} \\
      \\~\\
      \forall \var{vk} \mapsto \sigma \in \txwitsVKey{txw},
      \mathcal{V}_{\var{vk}}{\serialised{tx_{o}}}_{\sigma} \\
      \fun{witsVKeyNeeded}~{utxo}~{tx}~{genDelegs} \subseteq \var{witsKeyHashes}
      \\~\\
      genSig \leteq
      \left\{
        \fun{hashKey}~gkey \vert gkey \in\dom{genDelegs}
      \right\}
      \cap
      \var{witsKeyHashes}
      \\
      \left\{
        c\in\txcerts{txb}~\cap\DCertMir
      \right\} \neq\emptyset \implies \vert genSig\vert \geq \Quorum \wedge
      \fun{d}~\var{pp} > 0
      \\~\\
      \var{mdh}\leteq\fun{txMDhash}~\var{txb}
      &
      \var{md}\leteq\fun{txMD}~\var{tx}
      \\
      (\var{mdh}=\Nothing \land \var{md}=\Nothing)
      \lor
      (\var{mdh}=\fun{hashMD}~\var{md})
      \\~\\
      {
        \begin{array}{r}
          \var{slot}\\
          \var{pp}\\
          \var{stkCreds}\\
          \var{stpools}\\
          \var{genDelegs}\\
        \end{array}
      }
      \vdash \var{utxoSt} \trans{\hyperref[fig:rules:utxo-shelley]{utxo}}{tx}
      \var{utxoSt'}\\
    }
    {
      \begin{array}{r}
        \var{slot}\\
        \var{pp}\\
        \var{stkCreds}\\
        \var{stpools}\\
        \var{genDelegs}\\
      \end{array}
      \vdash \var{utxoSt} \trans{utxow}{{tx}_o} \varUpdate{\var{utxoSt'}}
    }
  \end{equation}
  \caption{UTxO with witnesses inference rules for GoguenTx}
  \label{fig:rules:utxow-goguen}
\end{figure}