\subsection{Classical Field Theory}
To begin to understand the Standard Model, a quantum field theory, it is helpful to first understand the classical notion of a field.
A field is a physical quantity defined as a function of space and time.
The physical quantity may be as simple as a scalar (e.g. the temperature at each point in space and time) or may be a vector (e.g. the electric field).
More generally, the physical quantity is a tensor of arbitrary rank.

With the notion of a field defined, we may next ask how to use these fields to describe the behavior of the universe.
In classical mechanics, this is achieved through constructing a Lagrangian density, $\mathcal L$ (referred to simply as the ``Lagrangian''), as a function of one or more fields, $\phi(x)$, and their derivatives:
\begin{equation} \label{eqn:lagrangian}
    \mathcal L = \mathcal L(\phi, \partial_\mu \phi).
\end{equation}
One of the fundamental concepts of classical mechanics is the principle of least action, which states that the action, $S$, defined as the time integral of the Lagrangian,
\begin{equation} \label{eqn:action}
    S = \int L~dt = \int \mathcal L(\phi, \partial_\mu \phi)~d^4x
\end{equation}
for a given system will be minimized as the system evolves between two points in time~\cite{Peskin:1995ev}:
\begin{equation} \label{eqn:least_action}
    \delta S = 0.
\end{equation}
Through inserting Eqn.~\ref{eqn:action} into Eqn.~\ref{eqn:least_action} and integrating by parts, one obtains the Euler-Lagrange equations of motion:
\begin{equation}
    \partial_\mu \bigg( \frac{\partial \mathcal L}{\partial (\partial_\mu \phi)} \bigg) - \frac{\partial \mathcal L}{\partial \phi} = 0.
\end{equation}
Though the SM Lagrangian is vastly more complex than the toy Lagrangian of Eqn.~\ref{eqn:lagrangian}, and is composed of quantum rather than classical fields, the same principle of least action allows us to describe the dynamics and interactions of the fundamental particles of the universe.

\subsection{Quantum Mechanics}
While classical mechanics provides a good description of our universe in some regimes, namely when we are dealing with large objects which move much more slowly than the speed of light, it cannot explain many of the observed phenomena in nature.
A standard motivation for the need of quantum theory, is the so-called ``ultraviolet catastrophe''~\cite{Schwartz:2013pla}, in which the classical prediction for the energy radiated by a blackbody, an object of some fixed temperature, diverges: the intensity of light radiated increases without bound as a function of frequency.
The ultraviolet catastrophe led Planck to propose a solution whose core principle was the idea that light may be radiated only at specific energies -- in other words, that the energy was \emph{quantized}.
This paved the way for the development of quantum mechanics, which proved very successful for describing blackbody radiation, developing models of the hydrogen atom, and many other applications.

However, one of the major shortcomings of quantum mechanics is the fact that it cannot describe the production or annihilation of particles~\cite{Zee:2003mt}.
More generally, quantum mechanics is incompatible with the theory of special relativity.
This fundamental limitation of quantum mechanics motivated the development of theories which could explain the universe at both very small scales (i.e. ``quantum'') and at very high (relativistic) energies.
Quantum field theory has emerged as the most successful theoretical framework for doing so.

\subsection{The Klein-Gordon Field}
To describe the universe in terms of quantum fields, it is helpful to examine a toy example: start with a classical field and make the necessary modifications to reinterpret the dynamical variables as quantum mechanical operators which obey the canonical commutation relations of quantum mechanics\footnote{A full description of quantum mechanics is beyond the scope of this thesis. A description of quantum mechanical operators and the derivation of their canonical commutation relations can be found in many textbooks on quantum mechanics, e.g.~\cite{Griffiths:qm}.} (following the treatment in ~\cite{Peskin:1995ev}).
We then see that the allowed states of the resulting quantum field have a natural physical interpretation as particles.

In choosing a toy example for a quantum field theory, it is helpful to begin with a ``derivation''~\cite{Griffiths:2008zz} of the Schr{\"o}dinger equation, which forms the basis of quantum mechanics.
Beginning with the classical energy-momentum relation
\begin{equation}
    \frac{\bf{p}^2}{2m} + V = E,
\end{equation}
one can promote the momentum and energy variables to quantum mechanical operators which act on the wave function $\Psi$, making the substitutions $\bf{p} \to -i\hbar\nabla$ and $E \to i\hbar \partial/\partial t$, and obtain the Schr{\"o}dinger equation
\begin{equation}
    - \frac{\hbar^2}{2m} \nabla^2 \Psi + V \Psi = i\hbar \frac{\partial \Psi}{\partial t}.
\end{equation}
As one of the primary aims of quantum field theory is to provide a description of particles which is consistent with special relativity, it is natural to start with the relativistic energy-momentum relation
\begin{equation}
    E^2 - \bf{p}^2 = m^2,
\end{equation}
and again promote the momentum and energy variables to quantum mechanical operators.
Doing so leads one to the \emph{Klein-Gordon equation}, originally proposed to describe the behavior of relativistic electrons\footnote{In fact, the Klein-Gordon equation does not provide a satisfactory description of relativistic electrons. It applies only to scalar (spin 0) particles, of which the Higgs boson is the only known example in nature.}~\cite{Klein:kge,Gordon:kge}:
\begin{equation}
    -\frac{\partial^2 \Psi}{\partial t^2} + \nabla^2 \Psi = m^2 \Psi.
\end{equation}
However, we are still working in the context of the wave function for the dynamics of a single particle -- in this paradigm we are still unable to describe the annihilation and pair production of particles.
We will see that this is possible working in the field theory framework, so it is natural to next ask: what Lagrangian density will give rise to the Klein-Gordon equation?
The Lagrangian for the classical Klein-Gordon field is given by
\begin{equation} \label{eqn:classical_kg}
    \mathcal L = \frac{1}{2} (\partial_\mu \phi)^2 - \frac{1}{2} m^2 \phi^2.
\end{equation}
%The reason for starting with this specific Lagrangian is the fact that its resulting equation of motion is the Klein-Gordon equation, originally proposed to describe the behavior of relativistic electrons~\cite{Klein:kge,Gordon:kge}.
Rather than the Lagrangian formalism, it is often more convenient to work with the Hamiltonian formalism, in which a conjugate momentum density $\pi \equiv \partial L/\partial \dot{\phi}$ is used instead of the time-derivative of the field variable, $\dot{\phi}$.
The Hamiltonian density is then defined as
\begin{equation}
    \mathcal H \equiv \sum \pi \dot{\phi} - \mathcal L.
\end{equation}
See~\cite{Fetter:cm} for a description of the Hamiltonian formalism.

Returning to the classical Klein-Gordon field, the Hamiltonian density is given by:
\begin{equation} \label{eqn:classical_kg_ham}
    \mathcal H = \frac{1}{2} \pi^2 + \frac{1}{2} (\nabla \phi)^2 + \frac{1}{2} m^2 \phi^2.
\end{equation}
The variables $\pi$ and $\phi$ can then be promoted to quantum mechanical operators which obey the canonical commutation relations
\begin{align}
    [\phi(\bf{x}), \pi(\bf{y})] &= i \delta^{(3)}(\bf{x} - \bf{y}) \\
    [\phi(\bf{x}), \phi(\bf{y})] &= [\pi(\bf{x}), \pi(\bf{y})] = 0.
\end{align}
Next, it is convenient to rewrite $\phi$ and $\pi$ in terms of so-called ladder operators\footnote{The motivation for the use of the ladder operators can be found in any standard quantum mechnics textbook, e.g.~\cite{Griffiths:qm}},  $a_{\bf{p}}$ and $a^{\dagger}_{\bf{p}}$, defined implicitly as
\begin{align}
    \phi(x) &= \int \frac{d^3p}{(2\pi)^3} \frac{1}{\sqrt{2\omega_{\bf{p}}}} (a_{\bf{p}} + a^{\dagger}_{-\bf{p}}) e^{i \bf{p}\cdot\bf{x}}, \\
    \pi(x) &= \int \frac{d^3p}{(2\pi)^3} (-i) \sqrt{\frac{\omega_{\bf{p}}}{2}} (a_{\bf{p}} - a^{\dagger}_{-\bf{p}}) e^{i \bf{p}\cdot\bf{x}},
\end{align}
and with $\omega_{\bf{p}} \equiv \sqrt{|\bf{p}|^2 + m^2}$.
Combining the commutation relations with the definitions of the ladder operators, the Hamiltonian may be written~\cite{Peskin:1995ev} as
\begin{equation}
    H = \int \frac{d^3p}{(2\pi)^3} \omega_{\bf{p}} \bigg( a^{\dagger}_{\bf{p}} a_{\bf{p}} + \frac{1}{2} \Big[a_{\bf{p}}, a^{\dagger}_{\bf{p}} \Big] \bigg).
\end{equation}
Calculating the commutators of the Hamiltonian and the ladder operators, $[H, a^{\dagger}_{\bf{p}}] = \omega_{\bf{p}} a^{\dagger}_{\bf{p}}$ and $[H, a_{\bf{p}}] = -\omega_{\bf{p}} a_{\bf{p}}$, we obtain a natural physical interpretation.
The operator $a^{\dagger}_{\bf{p}}$ acting on the ground state creates a state with momentum and energy given by $\bf{p}$ and $\omega_{\bf{p}}$, respectively -- in other words, it creates a particle with momentum $\bf{p}$ and energy $\omega_{\bf{p}}$.
Similarly, acting on this excited state with the operator $a_{\bf{p}}$ returns the system to the ground state -- it annihilates a particle with momentum $\bf{p}$ and energy $\omega_{\bf{p}}$.

Although the fields describing the various particles in the SM are considerably more complex than the the scalar field in this example, the Klein-Gordon field still serves to illustrate a valuable point: the quantum field theory framework allows us to describe the creation and annihilation of particles with an energy-momentum relation that is consistent with special relativity.
In particular, the Klein-Gordon Lagrangian (Eqn.~\ref{eqn:classical_kg}) describes a field whose excitations are particles of spin-zero and mass $m$.
More generally, the vast majority of fundamental particles are not spin-zero and we will need more complicated Lagrangians to describe their dynamics.

\subsection{Spinor \& Vector Fields} \label{sec:theory_sv_fields}
Other than the Higgs boson, all of the currently known fundamental particles are either spin-$\frac{1}{2}$ (fermions) or spin-1 (bosons).
How can we move beyond the Klein-Gordon Lagrangian and construct Lagrangians for spin-$\frac{1}{2}$ and spin-1 particles?
In general, the business of constructing Lagrangians in quantum field theory is not as rigorously motivated as in classical field theory, where Lagrangians are derived by the relation $L = T - U$ for a given physical system.
Lagrangians in quantum field theory are usually motivated by writing down the most general Lagrangian which respects all of the symmetries of the physical system.
Alternatively, we might choose a Lagrangian which yields the desired equations of motion.

The Lagrangian for spin-$\frac{1}{2}$ particles can be motivated by picking one whose resulting equations of motion are the Dirac equation, which Dirac showed describes the dynamics of spin-$\frac{1}{2}$ particles~\cite{Dirac:1928hu}.
One such choice is the following, called the Dirac Lagrangian~\cite{Peskin:1995ev}:
\begin{equation} \label{eqn:dirac_lagrangian}
    \mathcal L_{\text{Dirac}} = \bar{\psi}(i \gamma_\mu \partial_\mu - m) \psi,
\end{equation}
whose resulting equation of motion is the Dirac equation
\begin{equation}
    (i \gamma_\mu \partial_\mu - m) \psi(x) = 0.
\end{equation}
In the preceding equations, $\psi$ represents a two-component spinor with its adjoint $\bar{\psi} \equiv \psi^\dagger\gamma^0$ and the $\gamma^\mu$ a set of matrices which satisfy the anticommutation relation
\begin{equation}
    \{\gamma_\mu, \gamma_\nu\} = 2 g^{\mu\nu},
\end{equation}
with $g^{\mu\nu}$ the Minkowski metric.

The Lagrangian for spin-1 particles can be motivated by selecting a Lagrangian whose equations of motion are consistent with the dynamics with those of the photon, a familiar spin-1 particle.
Such a Lagrangian is the Proca Lagrangian~\cite{Griffiths:2008zz}, which describes a four-component vector field $A^\mu$
\begin{equation} \label{eqn:proca_lagrangian}
    \mathcal L_{\text{Proca}} = -\frac{1}{4} F_{\mu \nu}F^{\mu \nu} + \frac{1}{2} m^2 A_\mu A^\mu.
\end{equation}
The resulting field equation is then~\cite{Griffiths:2008zz}
\begin{equation}
    \partial_\mu F^{\mu\nu} + m^2A^\nu = 0,
\end{equation}
which for the case of the photon (which is massless, $m=0$) restores Maxwell's equations in empty space: $\partial_\mu F^{\mu\nu} = 0$.
The Klein-Gordon, Dirac, and Proca Lagrangians form the basis from which the SM Lagrangian is constructed.

%\subsection{Perturbative Expansions via Feynman Diagrams}
%Having now written down Lagrangians which are representative of the dynamics of particles in the SM, we next wish to calculate physically observable quantities, namely cross sections and decay rates.
%The resulting Euler-Lagrange equations of motion for Lagrangians like those considered in Sec.~\ref{sec:theory_sv_fields} are, in general, nonlinear differential equations with no known exact solutions.
%Rather than exact solutions, we must settle for perturbative solutions.

%In practice, this is done through an expansion in orders of the coupling constant, a parameter in a Lagrangian which represents the strength of an interaction.

%\subsection{Renormalization}

%In attempting to construct Lagrangians to describe the dynamics of spin-$\frac{1}{2}$ and spin-1 particles, there are several considerations


\documentclass{article}
\usepackage{amsmath}
\title{Cardano's Formula for Cubic equations}
\date{2021 - 11 - 18}
\author{Nnadiukwu Miracle}
\begin{document}
	\maketitle
\centering
	\section*{Abstract}
	Gerolamo Cardano was born in Pavia in 1501 as the illegitimate child of a jurist. He attended the University of Padua and became a physician in the town of Sacco, after being rejected in his home town in Milan. He became one of the most famous doctors in Europe,  having treated the pope. He was also an astrologer and an avid gambler, to which he wrote the book on Games of chance, which was the first treatise on the Mathematics of probability.\cite{elsevier}
	\centering
	\section*{Introduction to Cardano's formula}
	Cardano's formula for solution of cubic equations for an equation like:
		\begin{equation*}
		x^3 + ax^2 + a_2x + a_3 = 0
	\end{equation*}
	The parameters Q, R, S and T can be computed thus:
		\begin{align*}
			Q &=\dfrac{3a_2 - a^2_1}{a}  	&R &= \frac{9a_1a_2 - 27a_3 - 2a^3_1}{54}\\
			\linebreak
			S &=3\sqrt{R + \sqrt{-Q^3 + R^2}}  &T &= 3\sqrt{R - \sqrt{Q^3 + R^2}}	\\
		\end{align*}
to give the roots:
\begin{align*}
	x_1 &=	S + T - \frac{1}{3}a_1\\
	x_2 &=	\frac{-(S + T)}{2} - \frac{a_1}{3} + i\frac{\sqrt{3}(s - T)}{2}\\
	x_3 &=	\frac{-(S + T)}{2} - \frac{a_1}{3} - i\frac{\sqrt{3}(s - T)}{2}
\end{align*}
Note: $x^3$ must not have a co-efficient
\subsection*{Some examples}
\begin{itemize}
	\item $x^3 - 3x^2 + 4 = 0$
	\item $x^3 - 3x^2 + 4 = 0$
\end{itemize}

	\bibliographystyle{ieeetr}
	\bibliography{cardano}
\end{document}

CSC 101 - miracle - LaTEX/class project 3.tex


\documentclass[letterpaper]{article}

\usepackage{fullpage}
\usepackage{nopageno}
\usepackage{amsmath}
\usepackage{amssymb}
\allowdisplaybreaks

\newcommand{\abs}[1]{\left\lvert #1 \right\rvert}

\begin{document}
\title{Notes}
\date{November 26, 2014}
\maketitle
\section*{fundamental theorem of ring homomorphism}

\subsection*{observation}
let $\varphi:R\to S$ be a given ring homomorphism (R,S are commutative rings)

we want to define $\varepsilon:R[x]\to S$ ring homomorphism such that $\begin{cases}\varphi(r)=\varepsilon(r)&\forall r\in R\\\varepsilon(x)=s&s\text{ fixed }\in S\end{cases}$

then $\varepsilon(a_0+a_1x+\dots+a_nx^n)=\varphi(a_0)+\phi(a_1)s+\dots+\varphi(a_n)s^n$

\subsection*{construction}
we define $R_1+R_2+\dots+R_n=\{(a_1,a_2,\dots,a_n):a_i\in R_i\}$ with component wise operations. this is a ring.

\subsection*{definition}
given $R$ a commutative ring, we define the characteristic of$R$ to be $\text{char } R$ to be the smallest $n$ such that $1_1+1_2+...+1_n=0$. If it doesn't exists we say $\text{char } R$ is zero.

\subsection*{prop}
the characteristic of an integral domain is either $0$ or prime.

\subsubsection*{proof}
if 0 then done, lets, assume that it's not prime.

then $\text{char } R=n=\alpha\beta$ and $0=1_1+1_2+\dots+1_n=1_1+1_2+\dots+1_\alpha+1_1+\dots+1_\beta=\alpha\beta$. Because we are in an integral domain then $\alpha=0$ or $\beta=0$ and so we have a contradiction because $\alpha<n$ and the same for $\beta$ and so we have a contradiction because $n$ is the smallest to be 0 and so $n$ is prime.

\subsection*{corollary}
if $K$ is a field then characteristic is 0 or prime
\end{document}


\documentclass{article}
\usepackage{amsmath}
\usepackage{hyperref}

\begin{document}

%taken from https://en.wikipedia.org/wiki/Lagrangian_mechanics

\section{Lagrangian Mechanics}
\subsection{Lagrangian and action}
% this is a comment that is ignored
The core element of \href{https://en.wikipedia.org/wiki/Lagrangian_mechanics}{Lagrangian mechanics} is the Lagrangian function, which summarizes the dynamics of the entire system in a very simple expression. The physics of analyzing a system is reduced to choosing the most convenient set of generalized coordinates, determining the kinetic and potential energies of the constituents of the system, then writing down the equation for the Lagrangian to use in Lagrange's equations. It is defined by
$$ L = T -V $$
where $T$ is the total kinetic energy and $V$ is the total potential energy of the system.

The next fundamental element is the action $\mathcal{S}$, defined as the time integral of the Lagrangian:
$$\mathcal{S} = \int_{t_1}^{t_2} L\,\mathrm{d}t.$$
This also contains the dynamics of the system, and has deep theoretical implications (discussed below). Technically action is a functional, rather than a function: its value depends on the full Lagrangian function for all times between $t_1$ and $\bigl. t_2\bigr.$. Its dimensions are the same as angular momentum.

In classical field theory, the physical system is not a set of discrete particles, but rather a continuous field defined over a region of 3d space. Associated with the field is a Lagrangian density $\mathcal{L}(\mathbf{r},t)$ defined in terms of the field and its derivatives at a location $\bigl.\mathbf{r}\bigr.$. The total Lagrangian is then the integral of the Lagrangian density over 3d space (see volume integral):
 $$L(t) = \int  \mathcal{L}(\mathbf{r},t) \mathrm{d}^3 \mathbf{r}$$
 where $\bigl.\mathrm{d}^3\mathbf{r}\bigr.$ is a 3d differential volume element, must be used instead. The action becomes an integral over space and time:
 $$\mathcal{S} = \int_{t_1}^{t_2}\int \mathcal{L}(\mathbf{r},t) \mathrm{d}^3\mathbf{r} \mathrm{d}t.$$

 \subsection{Hamilton's principle of stationary action}
 Let $q_0$ and $q_1$ be the coordinates at respective initial and final times $t_0$ and $t_1$. Using the calculus of variations, it can be shown that Lagrange's equations are equivalent to Hamilton's principle: The trajectory of the system between $t_0$ and $t_1$ has a stationary action $\mathcal{S}$.

 By stationary, we mean that the action does not vary to first-order from infinitesimal deformations of the trajectory, with the end-points $(q_0, t_0)$ and $(q_1,t_1)$ fixed. Hamilton's principle can be written as: %this is another comment that is ignored
 $$\delta \mathcal{S} = 0. $$
 Thus, instead of thinking about particles accelerating in response to applied forces, one might think of them picking out the path with a stationary action.

 Hamilton's principle is sometimes referred to as the principle of least action, however the action functional need only be stationary, not necessarily a maximum or a minimum value. Any variation of the functional gives an increase in the functional integral of the action.

 We can use this principle instead of Newton's Laws as the fundamental principle of mechanics, this allows us to use an integral principle (Newton's Laws are based on differential equations so they are a differential principle) as the basis for mechanics. However it is not widely stated that Hamilton's principle is a variational principle only with holonomic constraints, if we are dealing with nonholonomic systems then the variational principle should be replaced with one involving d'Alembert principle of virtual work. Working only with holonomic constraints is the price we have to pay for using an elegant variational formulation of mechanics.

\end{document}


\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath,amssymb}
\usepackage{hyperref}
\usepackage[symbol]{footmisc}

\newcommand{\F}{\mathbb{F}}
\newcommand{\G}{\mathbb{G}}
\newcommand{\hs}{\mathcal{H}}
\newcommand{\enc}{\operatorname{Enc}}
\newcommand{\dec}{\operatorname{Dec}}

\title{Triptych multisignature analysis}
\author{Cypher Stack}
\date{\today}

\begin{document}

\maketitle

This document describes research and analysis into multisignature support for the Triptych zero-knowledge proving system and its associated transaction model.

\textbf{All material in this document should be considered experimental and unsuitable for production without thorough independent review.}

\section{Introduction}

Triptych \cite{triptych} is a zero-knowledge proving system that can be used in a multidimensional linkable ring signature construction to build a confidential transaction protocol.
Proofs constructed using Triptych scale in size logarithmically with the size of the input anonymity set, and can take advantage of efficient verification using batching and multiscalar multiplication.

A currently open question is the extent to which the protocol can support multisignature operations, where a group of players each holding a portion of a private signing key can jointly produce a valid transaction without mutual trust in each other or another third party.
It is a requirement that the resulting proof be indistinguishable from one produced by a single player holding a private key; that is, the resulting proof must be verifiable using a standard public key.

A confidential protocol based on Triptych requires the use of a private key in two places: during generation of a one-of-many authorizing proof, and when constructing a linking tag used to prevent double-spend attempts.
The one-of-many proof uses the private key in a linear fashion, which allows for straightforward approaches to multiparty computation.
However, the linking tag is constructed using the inverse of the private key, posing a challenge to such operations.
Fortunately, this inversion operation is similar to that used in other protocols, so we can apply earlier work toward a solution.

Let $\G$ be the prime-order subgroup of the \texttt{ed25519} elliptic curve group, and let $\F$ be its scalar field.
Let $G$, $H$, and $U$ be independent fixed generators of $\G$ known to all players.
Let $\hs: \{0,1\}^* \to \F$ be a cryptographic hash function.
We often prefix input to $\hs$ with an integer value, to act as an arbitrary domain separator; note that any equivalent domain separation method may be substituted, and that our notation is used for convenience.
When referring to sets of keys generated by players, we assume a fixed and publicly-known ordering, such as lexicographic ordering, is used.

\section{Key generation}

Keys are generated in a manner similar to that of MuSig \cite{musig}.
We assume a set of $\nu$ players who wish to generate linear shares of a private and public key constructed in the following way.
Throughout this section, we assume actions taken by a player $\alpha \in [0,\nu)$ are separately taken by all $\nu$ players in parallel.
\begin{enumerate}
    \item Each player $\alpha$ chooses random $(a_\alpha, b_\alpha) \in \F^2$ and computes $B_\alpha \equiv b_\alpha G$.
    It generates a private key $\gamma_\alpha$ and corresponding public key $\Gamma_\alpha$ for the Paillier cryptosystem compatible with encryption of \texttt{ed25519} prime-order subgroup scalar elements.
    It sends the tuple $(a_\alpha, B_\alpha, \Gamma_\alpha)$ to all players.
    \item Each player $\alpha$ computes the aggregate private view key $$a \equiv \sum_{\alpha=0}^{\nu-1} \hs(0, \{a_\beta G\}_{\beta=0}^{\nu-1}, \alpha) a_\alpha$$ and corresponding aggregate public view key $$A \equiv aG = \sum_{\alpha=0}^{\nu-1} \hs(0, \{a_\beta G\}_{\beta=0}^{\nu-1}, \alpha) a_\alpha G.$$
    \item Each player $\alpha$ computes the aggregate public spend key $$B \equiv \sum_{\alpha=0}^{\nu-1} \hs(1, \{B_\beta\}_{\beta=0}^{\nu-1}, \alpha) B_\alpha.$$
\end{enumerate}

The aggregate public key pair $(A,B)$ is used to receive transactions.

\section{Transaction generation and scanning}

A sender produces a transaction for the address $(A,B)$ as usual; we describe the process here for the sake of notation clarity.
\begin{enumerate}
    \item The sender chooses random $r \in \F$ and sets $R \equiv rG$.
    \item The sender computes the output public key $P \equiv \hs(2,rA)G + B$.
    \item The sender chooses random $s_1 \in \F$ and, using a valid value $v \in \F$, computes a commitment $C_{\operatorname{val}} \equiv s_1 G + vH$.
    \item The sender computes other auxiliary transaction information as needed.
\end{enumerate}

The sender includes $R, P, C_{\operatorname{val}}$ among other public transaction information, and submits the transaction to the network.

Any of the $\nu$ players holding shares of the address $(A,B)$ scan transactions for outputs destined for the address as usual, using the known aggregate private view key $a$ and aggregate public spend key $B$.
Specifically, for a given output public key $P$ with associated $R$, they test if $\hs(2,aR)G + B = P$, and ignore if the equality does not hold.
If it does, we note the associated private key:
\begin{align*}
p &\equiv \hs(2,aR) + b \\
&= \hs(2,aR) + \sum_{\alpha=0}^{\nu-1} \hs(1, \{B_\beta\}_{\beta=0}^{\nu-1}, \alpha) b_\alpha
\end{align*}
Of course, each player $\alpha$ holds only its own share $b_\alpha$ of the aggregate private spend key.

\section{Linking tag computation}

To spend the output represented by the public output key $P$, the players must cooperatively compute the associated linking tag $J$.
In the Triptych protocol, this tag is defined (continuing our rather bespoke notation from this documentation, rather than directly using the notation from \cite{triptych}) as follows:
\begin{align*}
J &\equiv p^{-1}U \\
&= \left( \hs(2,aR) + \sum_{\alpha=0}^{\nu-1} \hs(1, \{B_\beta\}_{\beta=0}^{\nu-1}, \alpha) b_\alpha \right)^{-1}U
\end{align*}

The non-linearity of the linking tag with respect to the associated output private key makes such a cooperative computation more complex.
However, we can apply a method of Gennaro and Goldfeder \cite{gennaro}, which was originally devised for use in multiparty threshold ECDSA signature computation.
The result will be that all players obtain $J$ without revealing their private spend key shares to each other.

Because $p$ consists of an additive prefix $\hs(2,aR)$ that is not distributed between players, we define players' secret shares $\{p_\alpha\}_{\alpha=0}^{\nu-1}$ of $p$ according to their index:
\begin{itemize}
    \item $p_0 := \hs(2,aR) + \hs(1, \{B_\beta\}_{\beta=0}^{\nu-1}, 0) b_0$
    \item $p_{\alpha > 0} := \hs(1, \{B_\beta\}_{\beta=0}^{\nu-1}, \alpha) b_\alpha$
\end{itemize}
The result is that $\sum_{\alpha=0}^{\nu-1} p_\alpha = p$.
The designation of indices does not affect protocol security.

A more comprehensive version of this method assumes the use of range proofs coupled with Paillier ciphertext; however, the authors hypothesize (but do not prove) that no significant information leakage occurs if these proofs are omitted.

We specifically require the use of Paillier public-key encryption, the keys for which have been introduced previously.
Let $\enc_\alpha$ represent Paillier encryption using the public key $\Gamma_\alpha$ for player $\alpha$, and $\dec_\alpha$ represent Paillier decryption using the private key $\gamma_\alpha$ for this player.

The process proceeds as follows.
\begin{enumerate}
    \item Each player $\alpha$ chooses random $g_\alpha \in \F$ and sets $G_\alpha \equiv g_\alpha U$.
    It generates a commitment $C_{\operatorname{tag},\alpha}$ to $G_\alpha$ and sends the commitment to all players.
    \item Each player $\alpha$ sets $c_\alpha \equiv \enc_\alpha(p_\alpha)$. It sends $c_\alpha$ to all players.
    \item For each other player $\beta$, player $\alpha$ chooses random $b_{\alpha\beta} \in \F$.
    It sends the value $\gamma_\alpha c_\beta + \enc_\beta(-b_{\alpha\beta})$ to player $\beta$, who decrypts using $\gamma_\beta$ and defines $a_{\beta\alpha}$ to be the resulting plaintext.
    \item Each player $\alpha$ computes $\delta_\alpha := p_\alpha \gamma_\alpha + \sum_{\beta \neq \alpha}(a_{\alpha\beta} + b_{\alpha\beta})$.
    It computes a Schnorr proof of representation $\Pi_\alpha$ of $G_\alpha$ with respect to the generator $U$.
    It sends $G_\alpha$, $\Pi_\alpha$, and $\delta_\alpha$ to all players.
    \item Each player computes $\delta := \sum_{\beta=0}^{\nu-1} \delta_\beta$.
    It ensures that the commitment $C_{\operatorname{tag},\beta}$ and Schnorr proof $\Pi_\beta$ are valid for each $\beta$, and aborts otherwise.
    It then computes the aggregate linking tag $J := \delta^{-1} \sum_{\beta=0}^{\nu-1} G_\beta$.
\end{enumerate}

Note that in this protocol, we use additive notation on Paillier ciphertexts, and multiplicative notation between field elements in $\F$ and Paillier ciphertexts.
Because of Paillier encryption homomorphism, these operations are well defined.

\section{Authorizing proof}

Triptych requires the use of a one-of-many authorizing proof.
When embedded with a linking tag and message using the non-interactive Fiat-Shamir heuristic, this proof serves as a digital signature that the signer knows the private key corresponding to an input key and corresponding to the linking tag.
The proof effectively proceeds in two stages.
In the first stage, the signer hides the index corresponding to the known public key in the input set.
In the second stage, the signer demonstrates knowledge of the private key corresponding to the public key at the hidden index, and further shows that the linking tag is constructed correctly.
Throughout this section, we assume the input set contains $N$ key tuples, where $N = n^m$ for some $n,m \in \mathbb{N}$.

The proof proceeds as follows.
\begin{enumerate}
    \item Any designated player assembles an input set $\{(M_{i,0}, M_{i,1})\}_{i=0}^{N-1}$.
    A secret index $0 \leq \ell < N$ is chosen. Each $M_{i,0} \in \G$ is an existing output public key, and the designated output public key is set such that $M_{\ell,0} = P$.
    \item Any designated player computes a commitment offset $C_{\operatorname{off}} \equiv s_2 G + vH$, where $s_2 \in \F$ is chosen according to the transaction protocol as usual.
    Each $M_{i,1}$ is the amount commitment corresponding to $M_{i,0}$, offset by $C_{\operatorname{off}}$.
    Let $s \equiv s_1 - s_2$, such that $M_{\ell,1} = sG$.
    \item Each player $\alpha$ selects random $$r_A^{(\alpha)}, r_B^{(\alpha)}, r_C^{(\alpha)}, r_D^{(\alpha)}, \left\{a_{j,i}^{(\alpha)}\right\}_{i=1,j=0}^{n-1,m-1}, \left\{\rho_j^{(\alpha)}\right\}_{j=0}^{m-1} \in \F$$ according to the proof protocol.
    It sends the values $$r_A^{(\alpha)}, r_B^{(\alpha)}, r_C^{(\alpha)}, r_D^{(\alpha)}, \left\{a_{j,i}^{(\alpha)}\right\}_{i=1,j=0}^{n-1,m-1}, \left\{\rho_j^{(\alpha)}G\right\}_{j=0}^{m-1}, \left\{\rho_j^{(\alpha)}J\right\}_{j=0}^{m-1}$$ to all players.
    \item Each player computes the following values:
        \begin{align*}
            r_A &\equiv \sum_{\alpha=0}^{\nu-1} \hs(3, \{r_A^{(\beta)}\}_{\beta=0}^{\nu-1}, \alpha) r_A^{(\alpha)} \\
            r_B &\equiv \sum_{\alpha=0}^{\nu-1} \hs(4, \{r_B^{(\beta)}\}_{\beta=0}^{\nu-1}, \alpha) r_B^{(\alpha)} \\
            r_C &\equiv \sum_{\alpha=0}^{\nu-1} \hs(5, \{r_C^{(\beta)}\}_{\beta=0}^{\nu-1}, \alpha) r_C^{(\alpha)} \\
            r_D &\equiv \sum_{\alpha=0}^{\nu-1} \hs(6, \{r_D^{(\beta)}\}_{\beta=0}^{\nu-1}, \alpha) r_D^{(\alpha)} \\
            \left\{a_{j,i}\right\}_{i=1,j=0}^{n-1,m-1} &\equiv \left\{\sum_{\alpha=0}^{\nu-1} \hs(7, \{a_{j,i}^{(\beta)}\}_{\beta=0}^{\nu-1}, \alpha) a_{j,i}^{(\alpha)}\right\}_{i=1,j=0}^{n-1,m-1} \\
            \{\rho_j G\}_{j=0}^{m-1} &\equiv \left\{\sum_{\alpha=0}^{\nu-1} \hs(8, \{\rho_j^{(\beta)}G, \rho_j^{(\beta)}J\}_{\beta=0}^{\nu-1}, \alpha) \rho_j^{(\alpha)}G\right\}_{j=0}^{m-1} \\
            \{\rho_j J\}_{j=0}^{m-1} &\equiv \left\{\sum_{\alpha=0}^{\nu-1} \hs(8, \{\rho_j^{(\beta)}G, \rho_j^{(\beta)}J\}_{\beta=0}^{\nu-1}, \alpha) \rho_j^{(\alpha)}J\right\}_{j=0}^{m-1}
        \end{align*}
        It uses the index $\ell$ to compute the set $\{\sigma_{j,i}\}_{i,j=0}^{n-1,m-1}$ according to the proof protocol, and further uses this collection of values to compute $A, B, C, D$ as well.
    \item Each player computes the hash value $\mu$, the values $\{X_j,Y_j\}_{j=0}^{m-1}$, and the challenge $\xi$ according to the proof protocol.
    It computes the set $\{f_{j,i}\}_{i=1,j=0}^{n-1,m-1}$ and the values $z_A, z_C, K$.
    \item Each player $\alpha$ computes $$z^{(\alpha)} \equiv \hs(1, \{B_\beta\}_{\beta=0}^{\nu-1},\alpha) b_\alpha \xi^m - \sum_{j=0}^{m-1} \hs(8, \{\rho_j^{(\beta)}G, \rho_j^{(\beta)}J\}_{\beta=0}^{\nu-1}, \alpha) \rho_j^{(\alpha)}\xi^j$$ and sends this value to all players.
    \item Each player computes $$z \equiv (\hs(2, aR) + \mu s)\xi^m + \sum_{\alpha=0}^{\nu-1} z^{(\alpha)}$$ and assembles the complete proof.
\end{enumerate}

\section{Observations}

A possible modification is to replace the Schnorr proof of representation of the value $G_\alpha$ in the Paillier inversion protocol with a proof that the associated commitment $C_{\operatorname{tag},\alpha}$ has a known discrete logarithm.

It may be necessary to require a specific commitment round for the authorizing proof pre-challenge values.
Currently, these values are computed using MuSig-type hash aggregation in order to assert that the resulting aggregated values are uniformly distributed and cannot be controlled by malicious players.
However, the aggregation uses a common coefficient set to compute values of the form $\{\rho_j G\}$ and $\{\rho_j J\}$.

It may be secure in practice to compress the Paillier inversion protocol, sending the initial commitment and encrypted key shares simultaneously.

\section{Conclusions}

The use of cooperative signing in the Triptych transaction protocol imposes significant communication complexity.
Notably, the inversion construction of linking tags requires an expensive many-to-many share conversion that itself requires multiple communication rounds between all signers, and a Paillier-based approach to this inversion itself requires support for arbitrary RSA groups.

Because security of the authorizing proof relies in part on Fiat-Shamir transcripts, signers cannot complete this proof (namely, the challenge values) without first computing the corresponding linking tag, as the tag must be embedded in the transcript.
Further, it is not possible to complete the entire pre-challenge portion of the authorizing proof prior to the linking tag computation, as this also requires knowledge of the complete tag.

If efficient multisignature operations are a priority for which this level of communication complexity is infeasible, it may be beneficial to investigate alternate transaction protocols that use linear linking tag constructions and/or simpler cooperative authorization proofs.
The author is aware of (and collaborating on the development of) at least two newer trustless protocols that take this approach: Seraphis\footnote{\url{https://gist.github.com/UkoeHB/24f6be6125684046c5c4d9f49351bccf}} and Lelantus 3\footnote{Disclaimer: The Firo project funds Cypher Stack research that includes development of this protocol.}.

It remains for stakeholders and interested parties to assess the feasibility of this construction as it applies to protocols of interest, and determine if Cypher Stack or other researchers and developers should continue to formalize, optimize, implement, or deploy it in software.

\bibliographystyle{plain}
\bibliography{main}

\end{document}


\subsection{Eplett's identity}

\citeauthor{riordan:intro:combinatorial:analysis},
in his book \cite{riordan:intro:combinatorial:analysis},
asks for a solution of the following exercise:

\begin{quote}
    let $\lbrace a_{n} \rbrace_{n\in\mathbb{N}}$ be a sequence, with $a_{0}\neq0$,
    and $\lbrace a_{n}^{\prime} \rbrace_{n\in\mathbb{N}}$ be its \emph{inverse}:
    if $A(t)$ and $A^{\prime}(t)$ are two \ac{fps} over them, respectively,
    then $A(t)A^{\prime}(t)=1$. Show that:
    \begin{displaymath}
        a_{n}^{\prime} = \frac{(-1)^{n}}{a_{0}^{n+1}}
            \left|
            \begin{array}{ccccc}
                a_1 & a_2 & \ldots & a_{n-1} & a_{n}\\
                a_0 & a_1 & \ldots & a_{n-2} & a_{n-1}\\
                0   & a_0 & \ldots & a_{n-3} & a_{n-2}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & a_{0} & a_{1}\\
            \end{array}
            \right|
    \end{displaymath}
    for $n \geq 2$.
    \marginpar{another way to find the inverse of a given sequence}
\end{quote}

\begin{proof}
Although not explicitly requested, %to show for $n\geq2$,
it's useful to recall formula about $a_{0}^{\prime}$ and $a_{1}^{\prime}$,
since they'll occur in the following.

First of all we interpret the product
$A(t)A^{\prime}(t)=1$ as the Cauchy product over the ring of \ac{fps},
namely as a convolution, therefore:
\begin{displaymath}
    \left[t^{0}\right]A(t)A^{\prime}(t)=a_{0}a_{0}^{\prime}=1
\end{displaymath}
is the relation which defines $a_{0}^{\prime}=\frac{1}{a_0}$.  On the other hand:
\begin{displaymath}
    \left[t^{1}\right]A(t)A^{\prime}(t)=a_{0}a_{1}^{\prime}+a_{1}a_{0}^{\prime}=0
\end{displaymath}
is the relation which defines $a_{1}^{\prime}=-\frac{a_1}{a_{0}^{2}}$.

The proof proceeds by induction on $n$:
\begin{itemize}
    \item base $n=2$:
        \begin{displaymath}
            a_{2}^{\prime} = \frac{1}{a_{0}^{3}}
                \left|
                \begin{array}{cc}
                    a_1 & a_2 \\
                    a_0 & a_1 \\
                \end{array}
                \right|
                = \frac{a_{1}^{2}-a_{0}a_{2}}{a_{0}^{3}}
        \end{displaymath}
        since $\big[t^{2}\big]A(t)A^{\prime}(t)=a_{0}a_{2}^{\prime}
            +a_{1}a_{1}^{\prime}+a_{2}a_{0}^{\prime}=0$, we have:
            \begin{displaymath}
                \begin{split}
                    a_{0}a_{2}^{\prime} &= -\left(a_{1}a_{1}^{\prime}+a_{2}a_{0}^{\prime}\right)
                        = -\left(-\left(\frac{a_{1}}{a_{0}}\right)^{2}+\frac{a_{2}}{a_{0}}\right)\\
                    a_{2}^{\prime} &= \frac{a_{1}^{2}}{a_{0}^{3}}-\frac{a_{2}}{a_{0}^{2}}
                \end{split}
            \end{displaymath}
        which proves the base case;

    \item assume the statement holds for $n$ and show it still holds for $n+1$, therefore
        we're left to prove the following:
    \begin{displaymath}
        a_{n+1}^{\prime} =
            -\frac{1}{a_{0}}\frac{(-1)^{n}}{a_{0}^{n+1}}
            \left|
            \begin{array}{ccccc}
                a_1 & a_2 & \ldots & a_{n} & a_{n+1}\\
                a_0 & a_1 & \ldots & a_{n-1} & a_{n}\\
                0   & a_0 & \ldots & a_{n-2} & a_{n-1}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & a_{0} & a_{1}\\
            \end{array}
            \right|
    \end{displaymath}
    expanding the determinant:
    \begin{displaymath}
        a_{1}
            \left|
            \begin{array}{ccccc}
                a_1 & a_2 & \ldots & a_{n-1} & a_{n}\\
                a_0 & a_1 & \ldots & a_{n-2} & a_{n-1}\\
                0   & a_0 & \ldots & a_{n-3} & a_{n-2}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & a_{0} & a_{1}\\
            \end{array}
            \right|
        - a_{0}
            \left|
            \begin{array}{ccccc}
                a_2 & a_3 & \ldots & a_{n} & a_{n+1}\\
                a_0 & a_1 & \ldots & a_{n-2} & a_{n-1}\\
                0   & a_0 & \ldots & a_{n-3} & a_{n-2}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & a_{0} & a_{1}\\
            \end{array}
            \right|
    \end{displaymath}
    therefore:
    \begin{displaymath}
        a_{n+1}^{\prime} =
            -\frac{a_{1}}{a_{0}}a_{n}^{\prime}
        -
            \frac{1}{a_{0}}\frac{(-1)^{n-1}}{a_{0}^{n}}
            \left|
            \begin{array}{ccccc}
                a_2 & a_3 & \ldots & a_{n} & a_{n+1}\\
                a_0 & a_1 & \ldots & a_{n-2} & a_{n-1}\\
                0   & a_0 & \ldots & a_{n-3} & a_{n-2}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & a_{0} & a_{1}\\
            \end{array}
            \right|
    \end{displaymath}
    expanding the determinant a second time:
    \marginpar{tedious manipulations, skip them at a first reading}
    \begin{displaymath}
        a_{2}
            \left|
            \begin{array}{ccccc}
                a_1 & a_2 & \ldots & a_{n-2} & a_{n-1}\\
                a_0 & a_1 & \ldots & a_{n-3} & a_{n-2}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & a_{0} & a_{1}\\
            \end{array}
            \right|
        - a_{0}
            \left|
            \begin{array}{ccccc}
                a_3 & a_4 & \ldots & a_{n} & a_{n+1}\\
                a_0 & a_1 & \ldots & a_{n-3} & a_{n-2}\\
                0   & a_0 & \ldots & a_{n-4} & a_{n-3}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & a_{0} & a_{1}\\
            \end{array}
            \right|
    \end{displaymath}
    therefore:
    \begin{displaymath}
        a_{n+1}^{\prime} =
            -\frac{a_{1}}{a_{0}}a_{n}^{\prime}
            -\frac{a_{2}}{a_{0}}a_{n-1}^{\prime}
            -\frac{1}{a_{0}}\frac{(-1)^{n-2}}{a_{0}^{n-1}}
            \left|
            \begin{array}{ccccc}
                a_3 & a_4 & \ldots & a_{n} & a_{n+1}\\
                a_0 & a_1 & \ldots & a_{n-3} & a_{n-2}\\
                0   & a_0 & \ldots & a_{n-4} & a_{n-3}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & a_{0} & a_{1}\\
            \end{array}
            \right|
    \end{displaymath}
    keep expanding determinants $n$ times yield:
    \begin{displaymath}
        a_{n+1}^{\prime} =
            -\frac{a_{1}}{a_{0}}a_{n}^{\prime}
            -\frac{a_{2}}{a_{0}}a_{n-1}^{\prime}
            \ldots
            -\frac{a_{n}}{a_{0}}a_{1}^{\prime}
            -\frac{a_{n+1}}{a_{0}}a_{0}^{\prime}
    \end{displaymath}
    which is the same to say:
    \begin{displaymath}
        a_{0}a_{n+1}^{\prime}
            +a_{1}a_{n}^{\prime}
            +a_{2}a_{n-1}^{\prime}
            \ldots
            +a_{n}a_{1}^{\prime}
            +a_{n+1}a_{0}^{\prime}
            = 0
    \end{displaymath}
    which is the relation we get from $\big[t^{n+1}\big]A(t)A^{\prime}(t)=0$
    so the induction step holds and the argument is proved as required.

\end{itemize}

\end{proof}

Previous exercise is actually a lemma for an identity which
\citeauthor{eplett:1979} finds and discusses in \cite{eplett:1979}.  Let
$\lbrace d_{nk}\rbrace_{n,k\in\mathbb{N}}$ be the Catalan triangle as defined
in \autoref{eq:shapiro:catalan:triangle:expanded}, so \citeauthor{eplett:1979}'s
result reads as follow.

\begin{theorem}
    \marginpar{\ldots this combination can be also expressed using a $A$-matrix, as
        we will see later}
    \begin{displaymath}
        c_{j-1}=\sum_{k=1}^{j}{(-1)^{k-1}d_{jk}}
    \end{displaymath}
    In other words, coefficient $c_{j-1}$, the first one lying on row $j-1$,
    combines coefficients lying on row $j$, summing with alternating signs.
    \label{thm:eplett:identity}
\end{theorem}
\begin{proof}
    Let $\vect{a}=\lbrace a_{n}\rbrace_{n\in\mathbb{N}}$ be a sequence such
    that $a_{0}=1$ and consider its \emph{inverse} sequence, call it $\vect{b}$,
    where $b_{0}=1$ by inverse relation on the very first coefficient.
    By previous exercise observe that:
    \begin{displaymath}
        a_{n} = b_{n}+a_{1}b_{n-1}+a_{2}b_{n-2}+\ldots+a_{n-1}b_{1}
    \end{displaymath}
    holds \emph{if and only if}:
    \begin{equation}
        b_{n} = (-1)^{n-1}
            \left|
            \begin{array}{ccccc}
                a_1 & a_2 & \ldots & a_{n-1} & a_{n}\\
                1 & a_1 & \ldots & a_{n-2} & a_{n-1}\\
                0   & 1 & \ldots & a_{n-3} & a_{n-2}\\
                \vdots & \vdots & \vdots & \vdots & \vdots\\
                0 & 0 & \ldots & a_{1} & a_{2}\\
                0 & 0 & \ldots & 1 & a_{1}\\
            \end{array}
            \right|
        \label{eq:eplett:det:inverse:identity:lemma}
    \end{equation}
    As we have seen in
    \autoref{eq:shapiro:catalan:triangle:convolution:for:generic:coefficient},
    we can rewrite theorem's \ac{rhs}, calling the new term $b_{j}$:
    \begin{displaymath}
        c_{j-1}=\sum_{k=1}^{j}{(-1)^{k-1}d_{jk}}
            = \sum_{k=1}^{j}{(-1)^{k-1}\sum_{i_{1}+\ldots+i_{k}=j}{c_{i_{1}}\cdots c_{i_{k}}}}=b_{j}
    \end{displaymath}
    % TODO in order to be truly precise, we should prove that the term abstracted out by `b_{j}'
    % actually equals the determinant of Catalan matrix.
    Applying \autoref{eq:eplett:det:inverse:identity:lemma} \emph{from right to left},
    it is necessary to find a sequence $\vect{a}$ such that:
    \begin{displaymath}
        a_{n} = c_{n-1}+a_{1}c_{n-2}+a_{2}c_{n-3}+\ldots+a_{n-1}c_{0}
    \end{displaymath}
    according to \citeauthor{feller:intro:combinatorial:analysis}, page $94$ of
    \cite{feller:intro:combinatorial:analysis}, the following combination over
    Catalan numbers holds, for $n>0$:
    \begin{displaymath}
        c_{n}=\sum_{k=1}^{n}{c_{k-1}c_{n-k}}\quad\wedge\quad c_{0}=1
    \end{displaymath}
    therefore setting $a_{n}=c_{n}$ sequence $\vect{a}$ is found and theorem
    is proved.

\end{proof}
\quad
\\\\
The above proof shows another interesting identity which relates Catalan
numbers with matrix determinants\marginpar{yet another characterization for
coefficient $c_{j}$ using matrix theory}:
\begin{displaymath}
    c_{n-1} = (-1)^{n-1}
        \left|
        \begin{array}{ccccc}
            c_1 & c_2 & \ldots & c_{n-1} & c_{n}\\
            1 & c_1 & \ldots & c_{n-2} & c_{n-1}\\
            0   & 1 & \ldots & c_{n-3} & c_{n-2}\\
            \vdots & \vdots & \vdots & \vdots & \vdots\\
            0 & 0 & \ldots & c_{1} & c_{2}\\
            0 & 0 & \ldots & 1 & c_{1}\\
        \end{array}
        \right|
\end{displaymath}

Taking apart the sum in theorem's \ac{rhs}, we can restate it as:
\begin{displaymath}
    c_{j-1} + \sum_{{k \text{ is even}}}{d_{jk}}
        = \sum_{{k \text{ is odd}}}{d_{jk}}\qquad\text{where } k\in\mathbb{N}\setminus \lbrace0\rbrace
\end{displaymath}
Since $d_{j0}$ has no meaning by definition of the triangle, we can
attach to it a combinatorial meaning: let $d_{j0}$ denotes the
number of pairs of paths that intersect for the first time at
step $j$ and possibly after again. Therefore $d_{j0}=c_{j-1}$, so
we can rewrite one more time:
\begin{displaymath}
    \sum_{{k \text{ is even}}}{d_{jk}}
        = \sum_{{k \text{ is odd}}}{d_{jk}} \qquad\text{where } k\in\mathbb{N}
\end{displaymath}
This last version supplies a combinatorial
interpretation in terms of \emph{non-intersecting} pairs of paths:
\begin{quote}
    \marginpar{a combinatorial interpretation of \citeauthor{eplett:1979}'s result}
    consider the set $S$ of pairs of paths with distance $j$. Then,
    the subset of $S$ composed of \emph{non-intersecting} pairs of paths
    with \emph{even} distance augmented by the subset of $S$ of
    pairs of paths that \emph{intersect} for the first time at step $j$
    equals, in number, the subset of $S$ is composed of pairs of paths
    with \emph{odd} distance
\end{quote}
\begin{proof}
    Consider a pair of paths $(\vect{\rho},\vect{\sigma})$ of length $j$ with
    \emph{even} distance $k$.  If a pair of steps, such that they \emph{do not
    point to the same direction}, is applied to $(\vect{\rho},\vect{\sigma})$
    then a new pair of paths $(\vect{\rho}^{\prime},\vect{\sigma}^{\prime})$ of
    length $j+1$ with \emph{odd} distance $k+1$ is built. This production is a
    bijection, therefore the number of pairs of paths with \emph{even} distance
    equal the one with \emph{odd} distance, under the constraint that paths
    have the same length them all, as required.
\end{proof}
\quad\\\\
Although identity stated in \autoref{thm:eplett:identity} can be consider
\marginpar{\autoref{thm:eplett:identity} can be applied to Renewal arrays too}
useless for our work, it is precious for two reasons: first, it characterize
Catalan numbers using matrix theory and, second, allows
\citeauthor{rogers:eplett:identity} to find further results about the theory of
\emph{Renewal arrays}, as described in \cite{rogers:eplett:identity}.


\documentclass{article}
\usepackage{fullpage}
\usepackage{nopageno}
\usepackage{amsmath}
\allowdisplaybreaks

\newcommand{\abs}[1]{\left\lvert #1 \right\rvert}

\begin{document}
\title{Notes}
\date{January 22, 2014}
\maketitle

\section*{prototype problem}
lesson 2

PDE is $u_t=\alpha^2u_{xx}$ on $0<x<L,0<t<\infty$

initial conditions $u(x,0)=?$ on $0<x<L,t=0$

boundary conditions $u(0,t)=T_1$ and $u(L,t)=T_2$ where $x=0,L$ and $0\leq t<\infty$

other types:
\begin{align*}
  u_t&=\alpha^2 u_{xx}-\beta (u-u_0), \beta > 0\\
  u_t&=\alpha^2 u_{xx}+f(x,t)\\
  u_t&=\alpha^2 u_{xx}-\omega u_x
\end{align*}

\section*{steady state solution}
a solution independant of time. $u=U(x)$

PDE becomes $0=\alpha^2 U_{xx}$
\begin{align*}
  U''(x)&=0\\
  U(x)&=c_2x+c_1\\
  U(0)&=T_1\\
  U(L)&=T_2\\
  U(x)&=T_1+c_2x\\
  U(L)&=T_2=T_1+c_2L\\
  c_2&=\frac{T_2-T_1}{L}\\
  U(x)&=T_1+\frac{T_2-T_1}{L}x
\end{align*}
\section*{energy conservation stuff}
the temperature of the bar determines the total heat energy
\begin{align*}
  E&=\int_0^L{cu(x,t),\mathrm{d}x}\\
  c&=\text{specific heat} \left(\frac{cal}{\mathrm{d}y cm}\right)\\
  \frac{\mathrm{d}E}{\mathrm{d}t}&=\frac{\mathrm{d}}{\mathrm{d}t}\int_0^L{cu,\mathrm{d}x}=c\int_0^L{\frac{\partial u}{\partial t},\mathrm{d}x}=c\int_0^L{\alpha^2 u_{xx},\mathrm{d}x}=\alpha^2 c(u_x(L,t)-u_x(0,t))
\end{align*}
for steady state: $\frac{\mathrm{d}E}{\mathrm{d}t}=\alpha^2 c(\frac{T_2-T_1}{L}-\frac{T_2-T_1}{L})=0$
\section*{lesson 3}
fourier's law of heat flow: the rate of flow of heat energy at the position $x_0$ (in positive direction in bar) is equal to $-k\frac{\partial u}{\partial x}(x_0,t)$

see page 22 in text

rate of heat flow is $\frac{\text{calories/sec}}{\text{cm}^2}=\frac{\text{cal}}{\text{sec deg cm}}\cdot\frac{\text{deg}}{\text{cm}}$

heat flow at $x=L$ is $\alpha^2 c u_x(L,t)$ and heat flow at $x=0$ is $\alpha^2 c u_2(0,t)$
\section*{boundary conditions}
at a boundary, common conditions are:
\begin{align*}
  u&=g(t)\\
  u_x+\lambda u&=g(t)\\
  u_x&=g(t) \text{most commonly} u_x=0 \text{called insulated condition}
\end{align*}
\end{document}


% !TEX root = scombinatorics.tex
\documentclass[scombinatorics.tex]{subfiles}
\begin{document}
\chapter{Stability}
\label{sauer}

\def\medrel#1{\parbox[t]{5ex}{$\displaystyle\hfil #1$}}
\def\ceq#1#2#3{\parbox[t]{20ex}{$\displaystyle #1$}\medrel{#2}{$\displaystyle #3$}}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{The order property}\label{ladder}

The \emph{chain index\/} of $\phi(\U\,;b)_{b\in\V}$, or of $\phi(x\,;z)$ when $\U$ and $\V$ are clear, is the maximal length (that is, $n+1$) of a chain of the form

\ceq{\ssf{ch}\hfill\phi(A\,;b_0)\ \subset}{\dots}{\subset\ \phi(A\,;b_n)}

for some set $A\subseteq\U$ and some $b_0,\dots,b_n\in\V$.
Note that we allow $\phi(A\,;b_0)$ to be empty.
This choice produces a small asymmetry below in the definition of ladder; see also Fact~\ref{fact_stability_dual}.

\begin{example}
  If $\phi(\U\,;b)_{b\in\V}$ consists of just one set, the chain index is $1$.
  If it contains two distinct sets, the  chain index is at least $2$ and it is exactly $2$ if there are no more two sets, or if all sets are disjoint.\QED
\end{example}

If a maximal length does not exist, we say that $\phi(x\,;z)$ is \emph{unstable,} or that it has the \emph{order-property.}
Otherwise we say that it is \emph{stable.}

In place of requiring the existence of the chain in \ssf{ch}, we could equivalently ask for a pair of tuples $a_1,\dots,a_n\in\U$ and $b_0,\dots,b_n\in\V$ such that

\ceq{\ssf{ld}\hfill\phi(a_h\,;b_k)}
{\IFF}
{h\le k.}

We call this pair of tuples a \emph{ladder\/} of length $n+1$.
We may also say \emph{ladder index\/} instead of chain index.
Setting $A=\{a_1,\dots,a_n\}$ we easily obtain a chain from a ladder, the converse is left as an easy exercise for the reader.

\begin{exercise}
  Let $\phi(x\,;z)$ have chain index $n+1$ or more.
  Let $A\subseteq\U$ be a minimal set such that a chain as in \ssf{ch} obtains for some $b_0,\dots,b_n\in\V$.
  Prove that there is a ladder $a_1,\dots,a_n$ and $b_0,\dots,b_n$ such that $A=\{a_1,\dots,a_n\}$ and conclude that $\phi(x\,;z)$ has ladder index $n+1$.\QED
\end{exercise}

The following facts are obvious but worth noting.

\begin{fact}\label{fact_stability_dual}
  Let $\phi(x\,;z)$ have ladder index $n+1$.
  Then $\phi(x\,;z)^{\rm op}$ has ladder index $\ge n$.\QED
\end{fact}

\begin{fact}\label{fact_stability_neg}
  Let $\phi(x\,;z)$ have ladder index $n$.
  Then $\neg\phi(x\,;z)$ has ladder index $n$.\QED
\end{fact}

\begin{proof}
  If for all $h\in(n]$ and $k\in[n]$

  \ceq{\hfill\neg\phi(a_h\,;b_k)}
  {\IFF}
  {h\le k}

  then $a'_h=a_{n+1-h}$ and $b'_k=b_{n-k}$ satisfy

  \ceq{\hfill\phi(a'_h\,;b'_k)}
  {\IFF}
  {\phi(a_{n+1-h}\,;b_{n-h})}

  \ceq{}
  {\IFF}
  {n-k>n+1-h}

  \ceq{}
  {\IFF}
  {h\le k}
\end{proof}

The following definition is connected with those above, though in a less evident manner.
We write ${}^n2$ for the set of binary sequences of length $n$ or, more precisely, the set of functions $s:[n)\to[2)$.
We write $s_h$ for the value of $s$ at $h$, and $s{\restriction} h$ for the restriction of $s$ to $[h)$.
We define ${}^{<n}2=\big\{r\, :\, r\in {}^h2,\ h\in[n)\big\}$.

A \emph{branching tree\/} of height $n$ for the formula $\phi(x\,;z)$ is a function

\ceq{\hfill\bar{a}\ :\ {}^{<n}2}{\to}{\U}
\nopagebreak[4]\par
\ceq{\hfill r}{\mapsto}{a_r},

which we may also present by writing $\bar a=\<a_r:r\in{}^{<n}2\>$, such that

\ceq{\ssf{2r}\hfill\0}
{\neq}
{\bigcap_{h=0}^{n-1}\neg^{s_h}\,\phi(a_{s\restriction h}\,;\V)}\hfill for all $s\in {}^n2$.

where $\neg^i$, for $i$ a non negative integer, denotes a negation symbol repeated $i$ times.
In other words \ssf{2r} requires the existence of some $\<b_s:s\in{}^n2\>$ such that

\ceq{\hfill\phi(a_{s\restriction h}\,;b_s)}
{\IFF}
{s_h=0}\hfill for all pairs $s\in {}^n2$ and $h\in[n)$

or, with slightly different notation,

\ceq{\hfill\phi(a_r\,;b_s)}
{\IFF}
{r^\frown0\subseteq s}\hfill for all pairs $r\subset s\in {}^n2$.

It helps to represent a branching tree as follows.
For definiteness, fix $n=3$.
Consider a full binary tree of height $n+1$ and assign to each internal node (different from root and leaves) a formula as depicted below.
Then \ssf{2r} requires that all formulas in each branch $s\in2^n$ are satified by some $b_s\in\V$.
\medskip

% Set the overall layout of the tree
\tikzstyle{level 1}=[level distance=3.5cm, sibling distance=2.5cm]
\tikzstyle{level 2}=[level distance=3.5cm, sibling distance=1.2cm]
\tikzstyle{level 3}=[level distance=2.5cm, sibling distance=0.5cm]
\tikzstyle{level 4}=[level distance=0.5cm, sibling distance=0.5cm]

% Define styles for bags and leafs
\tikzstyle{bag0} = [text width=2.5ex, align=left]
\tikzstyle{bag} = [text width=7.5ex, align=right]
%\tikzstyle{end} = [circle, minimum width=3pt,fill, inner sep=0pt]

\begin{tikzpicture}[grow=right]
\node[bag0] {{$\top$}}
    child {
        node[bag] {$\phi(a_{\0};z)$}
            child {
                node[bag] {$\phi(a_1;z)$}
                    child {
                       node[bag] {\footnotesize$\phi(a_{11};z)$\rlap{ ----- $b_{111}$}}
                       edge from parent
                    }
                    child {
                       node[bag] {\footnotesize$\llap{$\neg$}\phi(a_{11};z)$\rlap{ ----- $b_{110}$}}
                       edge from parent
                    }
                 edge from parent
            }
            child {
                node[bag] {\llap{$\neg$}$\phi(a_1;z)$}
                edge from parent
                    child {
                       node[bag] {\footnotesize$\phi(a_{10};z)$\rlap{ ----- $b_{101}$}}
                       edge from parent
                    }
                    child {
                       node[bag] {\footnotesize\llap{$\neg$}$\phi(a_{10};z)$\rlap{ ----- $b_{100}$}}
                       edge from parent
                    }
                 edge from parent
            }
       edge from parent
    }
    child {
        node[bag] {\llap{$\neg$}$\phi(a_{\0};z)$}
            child {
                node[bag] {$\phi(a_0;z)$}
                    child {
                       node[bag] {\footnotesize$\phi(a_{01};z)$\rlap{ ----- $b_{011}$}}
                       edge from parent
                    }
                    child {
                       node[bag] {\footnotesize\llap{$\neg$}$\phi(a_{01};z)$\rlap{ ----- $b_{010}$}}
                       edge from parent
                    }
                 edge from parent
            }
            child {
                node[bag] {\llap{$\neg$}$\phi(a_0;z)$}
                edge from parent
                    child {
                       node[bag] {\footnotesize$\phi(a_{00};z)$\rlap{ ----- $b_{001}$}}
                       edge from parent
                    }
                    child {
                       node[bag] {\footnotesize\llap{$\neg$}$\phi(a_{00};z)$\rlap{ ----- $b_{000}$}}
                       edge from parent
                    }
                 edge from parent
            }
        edge from parent
    };
\end{tikzpicture}
\smallskip

The Shelah \emph{2-rank\/} of $\phi(x\,;z)$ is the maximal height of a branching tree for $\phi(x\,;z)$.
If such a maximal integer does not exist, we say that the 2-rank is infinite.

\begin{example}
  If $\phi(\U\,;b)_{b\in\V}$ consists of just one set, the only branching tree for $\phi(x\,;z)$ is the empty tree.
  Therefore the 2-rank is $0$.
  If there are at least two distinct definable sets, then we can always find $a_\0, b_0,b_1$ such that $\phi(a_\0,b_0)\niff\phi(a_\0,b_1)$ hence the 2-rank is at least $1$.\QED
\end{example}

A branching tree $\bar a'=\<a'_r:r\in{}^{<m}2\>$ is a \emph{subtree\/} of $\bar a$ if there is an $\subseteq$-preserving map $f:{}^{<m}2\to{}^{<n}2$ such that $a'_r=a_{fr}$.

The theorem below needs the following Ramsey-like lemma.

% \begin{lemma}\label{lem_Ramsey_on_trees}
%   Let $\bar a=\<a_r\, :\, r\in{}^{<2m}2\>$ be a branching tree for $\phi(x\,;z)$.
%   Let $k\in[2m]$ be given.
%   Then, for every $2$-coloring of $\range(\bar a)$, there is a branching tree $\bar a'=\<a'_r\, :\, r\in{}^m2\>$ such that  $\range(\bar a')$ is a monochromatic subset of $\range(\bar a)$.\QED
% \end{lemma}

% As it happens, a more general lemma is easier to prove.

\begin{lemma}\label{lem_Reamsey_tree}
  Let $\bar a=\<a_r\, :\, r\in{}^{<n}2\>$ be a branching tree for $\phi(x\,;z)$.
  Let $k\in[n]$ be given.
  Then, for every red-blue coloring of $\range(\bar a)$,  there is a monochromatic branching subtree, say $\bar a'=\<a'_r\, :\, r\in{}^{n'}2\>$, and either all nodes of $\bar a'$ are red and $n'=k$, or they are all blue and $n'=n-k$.
\end{lemma}

\begin{proof}
  Induction on $n$.
  First, note that the lemma is trivial when $k=0$ or $k=n$.
  In particular the lemma holds for $n=1$.

  Assume the lemma true for $n$ and prove it for $n+1$.
  Let  $\bar a=\<a_r\, :\, r\in{}^{n+1}2\>$ be given.
  Fix some $k\in[n+1]$.
  We want a branching tree $\bar a'$ that is either red of height $k$ or blue of height $n+1-k$.

  If we discard the trivial cases, we can assume $k\in(n]$.

  For $i=0,1$ we define $\bar a_i=\<a_{i^\frown r}\;:\;r\in {}^{<n}2\>$.

  First suppose that $a_\0$ is blue.
  If, for either $i=0$ or $i=1$, there is a red branching tree $\bar a'_i$ of height $k$, we are done.
  Otherwise, for both $i=0,1$ there is a blue branching tree $\bar a'_i$ of height $n-k$.
  Then we graft these two trees on $a_\0$, which is also blue, and obtain the required blue tree of height $n-k+1$.

  Now suppose that $a_\0$ is red.
  If, for either $i=0$ or $i=1$, there is a blue branching tree $\bar a'_i\subseteq \bar a_i$ of height $n-(k-1)$, we are done.
  Otherwise, we graft on $a_\0$ two red trees of height $k-1$ to obtain a red tree of height $k$.
\end{proof}

We are now ready to characterize stability via the 2-rank.
The proof is based on Hodges~\cite{hodges}.
It is a direct proof which yields an explicit bound on the 2-rank given the ladder index (it yields also the converse, but this is easy).
This bound may be far from optimal.

Shelah was the first to prove the equivalence \ssf{1}$\IFF$\ssf{2} below.
His proof is model theoretic and does not gives explicit bounds.
However it introduces some deep insight on sable formulas that we will present in the next section.

\begin{theorem}\label{thm_hodges}
  The following are equivalent
  \begin{itemize}
    \item[1.] $\phi(x\,;z)$ is stable;
    \item[2.] $\phi(x\,;z)$ has finite 2-rank.
  \end{itemize}
  Precisely, if $n_{\rm ld}$ and $n_{\rm 2r}$ are the ladder index and the 2-rank, respectively, then

  \ceq{\hfill n_{\rm ld}}{<}{2^{n_{\rm 2r}+1};}

  \ceq{\hfill n_{\rm 2r}}{<}{2^{n_{\rm ld}+1}-2.}
\end{theorem}

\begin{proof}[Proof (\kern.1ex\ssf{2}\kern.3ex\boldmath$\IMP$\ssf{1})]
  % \def\ceq#1#2#3{\parbox[t]{29ex}{$\displaystyle #1$}\medrel{#2}{$\displaystyle #3$}}
  % \ssf{1}$\IMP$\ssf{2}
  % We prove the contrapositive.
  % If there is a binary tree of height $n$ then there is a ladder of length $n$.
  % This also proves the first inequality of the proposition.

  % Let $\{a_s\; :\; s\in2^{<n}\}$ and $\{b_s\; :\; s\in2^{n}\}$ satisfy \ssf{2r}.
  % Apply \ssf{2r} to sequences of the form $1^k\,0^{n-k}$ for $0\le k\le n$.

  % % Define $a'_1,\dots,a'_n$ and $b'_0,\dots,b'_n$, where $a'_h=a_{1^{h-1}}$ and $b'_k=b_{1^k0^{n-k}}$.
  % % By \ssf{2r} we have

  % \ceq{\hfill\phi(a_{1^k\,0^{n-k}\,\restriction\, h-1}\;;\,b_{1^k\,0^{n-k}})}
  % {\IFF}
  % {\big(1^k0^{n-k}\big)_{h-1}=1}

  % \ceq{}
  % {\IFF}
  % {h\le k}

  We prove the contrapositive.
  We show that if there is a ladder of length $m=2^n$, say $a_1,\dots,a_{m-1}$ and $b_0,\dots,b_{m-1}$, then there is a branching tree $\bar a'$ of height $n$.
  This also proves the first inequality above.
  In fact, if $n_{\rm ld}\ge 2^{n_{\rm 2r}+1}$, there would exist a branching tree of height $n_{\rm 2r}+1$ which is a contradiction.

  The branching tree $\bar a'=\<a'_r\, :\, r\in{}^{<n}2\>$ is defined as follows

  \quad $a'_r=a_h$\quad  where $h$ is obtained reading $r^\frown1^\frown0^{n-|r|-1}$ as an $n$-digit binary number.

  To verify \ssf{2r} we define for $s\in{}^n2$

  \quad $b'_s=b_k$\quad  where $k$ is obtained reading $s$ as an $n$-digit binary number.

  Then it is easy to verify that for all pairs $r\subset s\in{}^n2$

  \ceq{\hfill\phi(a'_r\,;b'_s)}
  {\IFF}
  {\phi(a_h\,;b_k)}\hfill where $h$ and $k$ are like above

  \ceq{}
  {\IFF}
  {h\le k}

  \ceq{}
  {\IFF}
  {r^\frown1^\frown0^{n-|r|-1}\ \le\ s}\hfill  as $n$-digit binary numbers

  \ceq{}
  {\IFF}
  {r^\frown1\ \subseteq\ s}

  \textbf{(\ssf{1}\kern.2ex\boldmath$\IMP$\ssf{2}\kern.1ex)}\
  We prove the contrapositive.
  We claim that if there is a branching tree $\bar a$ of height $2^n-2$ then there is a ladder $a_1,\dots,a_{n-1}$ and $b_0,\dots,b_{n-1}$, of length $n$, such that $a_1,\dots,a_{n-1} \in \range(\bar a)$ and $b_0,\dots,b_{n-1} \in \{b_s:s\in{}^{2^n-2}2\}$.
  This yields also the second inequality of the theorem.
  In fact, if $n_{\rm 2r}\ge 2^{n_{\rm ld}+1}-2$, there would exist a ladder of length $n_{\rm ld}+1$ which is a contradiction.

  As $n_{\rm ld}\ge 1$, we start the induction from $n=2$.
  In this case the claim is witnessed by ladder $a_\0$ and $b_0,b_1$.
  Now we assume the claim is true for $n$ and prove it for $n+1$.

  Let $\<a_r\, :\, r\in{}^{<\, 2m+2}2\>$, where $m=2^n-2$, be a branching tree of height $2^{n+1}-2$.
  To each $b\in\{b_s:s\in{}^{2m+2 }2\}$ we associate a red-blue coloring of $\range(\bar a)$ as follows.
  A node $a\in\range(\bar a)$ is colored

  \qquad\qquad \llap{red}\qquad if $\phi(a\,;b)$ holds;

  \qquad\qquad \llap{blue}\qquad otherwise, that is, $\neg\phi(a\,;b)$.

  We consider two cases that are exhaustive by Lemma~\ref{lem_Reamsey_tree}.
  Note that we are applying the lemma only to the subtree $\<a_{1^\frown r}:r\in{}^{2m+1}2\>$.

  Case 1: for some $b$ there is a red subtree of $\<a_{1^\frown r}:r\in{}^{2m+1}2\>$ of height $m+1$.
  Let $\bar a'$ be this red tree and consider its subtree $\<a'_{0^\frown r}\,:\,r\in {}^{<\,m}2\>$.
  By induction hypothesis, there are $A\subseteq\{a'_{0^\frown r}\,:\,r\in {}^{<\,m}2\}$ and $b_0,\dots,b_{n-1}$ such that

  \ceq{(1)\hfill\phi(A\,;b_0)\ \subset}{\dots}{\subset\ \phi(A\,;b_{n-1})}

  Let $A'=A\cup\{a'_\0\}$ then

  \ceq{(2)\hfill\phi(A'\,;b_0)\ \subset}{\dots}{\subset\ \phi(A'\,;b_{n-1})}

  In fact, as $b_0,\dots,b_{n-1}\in\neg\phi(a'_\0\,;\V)$, this is the same chain as (1).
  Therefore, if we extend the chain on the right with $\phi(A'\,;b)=A'$, we obtain the required chain of length $n+1$.

  Case 2: for every $b$ there is a blue subtree of $\<a_{1^\frown r}:r\in{}^{2m+1}2\>$ of height $m$.
  Pick any $b\in\{b_s:s\in{}^{2m+2}2\}$ such that $\neg\phi(a_\0, b)$ and let $\bar a'$ the corresponding blue subtree.
  Apply the induction hypothesis to obtain $A\subseteq\range(\bar a')$ and $b_0,\dots,b_{n-1}$ such that (1).
  We claim that (2) above holds with $A'=A\cup\{a_\0\}$.
  In fact, $b_0,\dots,b_{n-1}\in\phi(a_\0\,;\V)$ so (2) is the chain in (1) with all sets augmented by $a_\0$.
  We can extend the chain on the left with $\phi(A'\,;b)=\0$ and obtain the required chain of length $n+1$.
\end{proof}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Approximable sets}

The notion of approximable set is a combinatorial counterpart of the model theoretical notion of externally definable set.

\begin{definition}\label{def_approx}
  We say that $\Aa\subseteq\U$ is \emph{approximable\/} if for every finite set $A\subseteq\U$ there is a $b\in\V$ such that $\phi(A\,;b)=\Aa\cap A$.
  If we also have that $\phi(\U\,;b)\subseteq\Aa$, then we say that $\Aa$ is approximable \emph{from below.}\QED
\end{definition}

The following is immediate.

\begin{fact}
  The following are equivalent for every $\Aa\subseteq\U$
  \begin{itemize}
    \item[1.] $\Aa$ is approximable from below;
    \item[2.] for every finite set $A\subseteq\Aa$ there is a $b\in\V$ such that $A\subseteq\phi(\U\,;b)\subseteq\Aa$.\QED
  \end{itemize}
\end{fact}

Towards the main theorem of this section we prove three separated lemmas.

\begin{lemma}
  Let $\phi(x\,;z)$ be a stable formula.
  Every set $\Aa\subseteq\U$ approximable by $\phi(x\,;z)$ is approximable from below by the formula

  \ceq{\hfill \psi(x\,;z_0,\dots,z_n)}{=}{\bigwedge_{i=0}^n\phi(x\,;z_i)}

  where $n+1$ is the ladder index of $\phi(x\,;z)$.
\end{lemma}

\begin{proof}
  Let $A\subseteq\Aa$ be finite.
  We prove that $A\subseteq\psi(\U\,;b_0,\dots,b_n)\subseteq\Aa$ for some $b_0,\dots,b_n$.
  To obtain the $b_k$, we construct a ladder inductively.
  Pick any $b_0$ be such that $A\subseteq\phi(\U\,;b_0)$, which we can do by approximability.
  Now, suppose that $a_1,\dots,a_k$ and $b_0,\dots,b_k$ have been defined.
  If

  \ceq{\hfill A}{\subseteq}{\bigcap_{i=0}^k\phi(\U\,;b_i)\medrel{\subseteq}\Aa}

  we set $b_{k+1}=\dots=b_n=b_k$ and stop as we already have the required parameters.
  Otherwise pick any element

  \ceq{\hfill a_{k+1}}{\in}{\bigcap_{i=0}^k\phi(\U\,;b_i)\sm\Aa}

  and some $b_{k+1}$ such that

  \ceq{\hfill A}{\subseteq}{\phi(\U\,;b_{k+1})\medrel{\subseteq}\U\sm\{a_1,\dots,a_{k+1}\}}.

  Such a parameter $b_{k+1}$ exists because $\Aa$ is approximable (apply Definition~\ref{def_approx} with $A\cup\{a_1,\dots,a_{k+1}\}$ for $A$).
  Note that at stage $n$ we have constructed a ladder of length $n$ for $\neg\phi(x\,;z)$.
  In fact for all $h\in(n]$ and $k\in[n]$ we have

  \ceq{\hfill\neg\phi(a_h\,;b_k)}
  {\IFF}
  {h\le k.}

  As $\phi(x\,;z)$ has ladder index $n+1$, by Fact~\ref{fact_stability_neg} it is not possible to further prolong this chain, hence

  \ceq{\hfill A}{\subseteq}{\bigcap_{i=0}^n\phi(\U\,;b_i)\medrel{\subseteq}\Aa}

  as required.
\end{proof}

We prove that the formula $\psi(x\,;z_0,\dots,z_n)$ in the lemma above is itself stable, though with a larger ladder index.

\begin{lemma}
  Let $\psi_i(x\,;z)$, where $i=1,\dots,m$, be formulas with ladder index $n_i$. Let

  \ceq{\hfill \phi(x\,;z)}{=}{\bigwedge_{i=1}^m\phi_i(x\,;z)}

  Then $\phi(x\,;z)$ has ladder index $< R(n_1+1,\dots, n_m+1)$, the Ramsey number for $m$-colorings.
\end{lemma}

\begin{proof}
  Suppose for a contradiction that there is a ladder $a_1,\dots,a_n$ and $b_0,\dots,b_n$, where $n=R(n_1+1,\dots, n_m+1)-1$.
  Let $C_i$ contains the pairs $\{h,k\}$ such that $\neg\phi_i(a_h\,;b_k)$ and $0\le k<h\le n$.
  Then from \ssf{ld} we obtain

  \ceq{\hfill\bigcup_{i=1}^mC_i}{=}{\binom{[n]}{2}}

  By the definition of $n$, for some $i\in[m]$, there is a set $H$ of cardinality $n_i+1$ such that $H^{(2)}\subseteq C_i$.
  Assume $i{=}1$ for definiteness.

  Write $a'_1,\dots,a'_{n_1}$ and $b'_0,\dots,b'_{n_1}$ for the tuples obtained by restricting $a_1,\dots,a_n$ and $b_0,\dots,b_n$ to the indexes in $H$.
  These tuples witness that $\phi_1(x\,;z)$ has ladder index at least $n_1+1$, which contradicts the assumption of the lemma.
\end{proof}

To apply the proposition to the formula $\psi(x\,;z_0,\dots,z_n)$ in the lemma above, let $z=z_0,\dots,z_n$ and let $\phi_i(x\,;z)=\phi(x\,;z_i)$.
That is, $\phi_i(x\,;z)$ defines a relation between $\U$ and $\V^{n+1}$ that depends only on the $i$-th coordinate.
The ladder index of every $\phi_i(x\,;z)$ is the same as $\phi(x\,;z_0)$ as a relation between $\U$ and $\V$.

\begin{lemma}
  If $\Aa$ is approximated from below by a stable formula $\phi(x\,;z)$ then for some $b_0,\dots,b_n\in\V$
  \\[-1ex]
  \ceq{\hfill \Aa}{=}{\bigcup^n_{i=0}\phi(\U\,;b_i)}

  where $n+1$ is the ladder index of $\phi(x\,;z)$.
\end{lemma}

\begin{proof}
  Let $A\subseteq\U$ be finite.
  To obtain the $b_k$, we construct a ladder by stages.
  Pick any $b_0$ be such that $\phi(\U\,;b_0)\subseteq\Aa$.
  Now, suppose that $a_1,\dots,a_k$ and $b_0,\dots,b_k$ have been defined.
  If
  \\[-1ex]
  \ceq{\hfill\Aa}{\subseteq}{\bigcup_{i=1}^k\phi(\U\,;b_i)}

  we set $b_{k+1}=\dots=b_n=b_k$ and stop.
  As the construction guarantees the converse inclusion, we have the required parameters.
  Otherwise pick any element

  \ceq{\hfill a_{k+1}}{\in}{\Aa\sm\bigcup_{i=1}^k\phi(\U\,;b_i)}

  and some $b_{k+1}$ such that

  \ceq{\hfill \{a_1,\dots,a_{k+1}\}}{\subseteq}{\phi(\U\,;b_{k+1})\medrel{\subseteq}\Aa}.

  Such a parameter $b_{k+1}$ exists because $\Aa$ is approximable from below.
  Note that at stage $n$ we have constructed a ladder of length $n$ for $\phi(x\,;z)$.
  In fact for all $h\in(n]$ and $k\in[n]$ we have

  \ceq{\hfill\neg\phi(a_h\,;b_k)}
  {\IFF}
  {h\le k.}

  As $\phi(x\,;z)$ has ladder index $n+1$, it is not possible to prolonge this chain, hence

  \ceq{\hfill\Aa}{=}{\bigcup_{i=0}^n\phi(\U\,;b_i)}

  as required.
\end{proof}

The main theorem of this section is an immediate corollary of the three lemmas above.

\begin{theorem}\label{thm_stable_definability}
  Let $\phi(x\,;z)$ be stable.
  Then there are $m, n$ such every set $\Aa\subseteq\U$ approximable by $\phi(x\,;z)$ is definable by $\psi(x\,;\bar b)$, where

  \ceq{\hfill\psi(x\,;\bar z)}{=}{\bigvee_{j=0}^m\bigwedge_{i=0}^n\phi(x\,;z_{i,j})}

  and $\bar b\in\V^{n\times m}$ is some $n{\times}m$-tuple of parameters.\QED
\end{theorem}

Note that the numbers $m,n$ in the theorem above do not depend on the set $\Aa$ approximated by $\phi(x\,;z)$. As a matter of fact, $m,n$ only depend on the ladder index of $\phi(x\,;z)$.

We conclude this section with the sketch of an argument that shows that stable formulas have finite 2-rank, that is, \ssf{1}$\IMP$\ssf{2} in Theorem~\ref{thm_hodges}.

As a matter of fact, below we prove an apparently weaker claim
\begin{itemize}
  \item[\#] if there is a branching tree of height $\omega$, say $\{a_s:s\in2^{<\omega}\}$, the ladder index is infinite.
\end{itemize}
In general, infinite 2-rank does not implies the existence of a branching tree of height $\omega$.
Nevertheless, by standard model theoretic argument of compactness, \# suffices to obtain \ssf{1}$\IMP$\ssf{2} in Theorem~\ref{thm_hodges}.
Model theory is beyond the scope of this notes, hence here we only present the argument that proves \#.

First note that Theorem~\ref{thm_stable_definability} remains true when $\U$ is replaced by a subset $\U'\subseteq\U$.
It is also clear that the formula $\psi(x\,;\bar z)$ that proves the theorem for $\U$, works also for any $\U'\subseteq\U$ (in fact, the ladder index does not decrease when moving to a subset).

For $s\in2^\omega$, let $\U_s=\{a_{s\restriction n}:n<\omega\}\subseteq\U$.
Let $\Aa_s=\{a_{s\restriction n}:n<\omega,\ s_n=1\}$.
Then $\Aa_s\subseteq\U_s$ is approximable with respect to the collection $\phi(\U_s\,;b)_{b\in\V}$.
Therefore, from the theorem above, we obtain $\Aa_s=\psi(\U_s\,;\bar b_s)$ for some  $\bar b_s\in\V^{n\times m}$, where the formula $\psi(x\,;\bar z)$ does non depend on $s$.

For $s\neq s'$, let $n$ be least such that $s_n\neq s'_n$.
Then $a_{s\restriction n}=a_{s'\restriction n}$ belongs to $\U_s\cap\U_{s'}$ and to $\Aa_s\simdiff\Aa_{s'}$.
Therefore $\bar b_s\neq\bar b_{s'}$, hence there is a continuum of such tuples $\bar b_s$.
On the other hand, without loss of generality we can assume that $\V$ is a countable set.
A contradiction.

% Assume the 2-rank is infinite and reason for a contradiction.
% Assume for the moment that the rank is $\omega$, in the sense that there is an infinite branching tree $\<a_r:r\in2^{<\omega}\>$.
% Let $\<b_s:s\in2^{\omega}\>$ be witnesses of \ssf{2r}.
% Let $Q\subseteq\{b_s:s\in2^{\omega}\}$ the set of sequences that are eventually $0$.
% Note that in the proof of Theorem~\ref{thm_stable_definability} we can require that $\bar b\in Q^{n\times m}$.
% But there are

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%\section{Stable Erd\H{o}s-Hajnal}

\end{document}


\newcommand\lbxmonad{\texttt{xmonad}\xspace}

\section{Functional Correctness Invariants}\label{sec:structures}

So far, we have considered a variety of general, application independent
correctness criteria. Next, let us see how we can use \toolname to specify
and statically verify critical, application specific correctness properties,
using two illustrative case studies: red-black trees and the stack-set data
structure introduced in the \lbxmonad system.

\subsection{Red-Black Trees}\label{sec:redblack}

Red-Black trees have several non-trivial invariants that are ideal for
illustrating the effectiveness of refinement types and contrasting with
existing approaches based on GADTs~\cite{Kahrs01}.
%
The structure can be defined via the following Haskell type:
%
\begin{code}
  data Col    = R | B
  data Tree a = Leaf
              | Node Col a (Tree a) (Tree a)
\end{code}
%
However, a @Tree@ is a valid Red-Black tree only if it
satisfies three crucial invariants:
%
\begin{itemize}
  \item{\emphbf{Order:}}
    The keys must be binary-search ordered, \ie the key at each node must
    lie between the keys of the left and right subtrees of the node,
  \item{\emphbf{Color:}}
    The children of every \emph{red} @Node@ must be colored \emph{black},
    where each @Leaf@ can be viewed as black,
  \item{\emphbf{Height:}}
    The number of black nodes along any path from each @Node@ to its @Leaf@s
    must be the same.
\end{itemize}

Red-Black trees are especially tricky as various operations create
trees that can temporarily violate the invariants. Thus, while
the above invariants can be specified with singletons and GADTs,
encoding all the properties (and the temporary violations) results
in a proliferation of data constructors that can somewhat obfuscate
correctness. In contrast, with refinements, we can specify and verify
the invariants in isolation (if we wish) and can trivially compose
them simply by \emph{conjoining} the refinements.

\mypara{Color Invariant}
To specify the color invariant, we define a \emph{black-rooted tree} as:
%
\begin{code}
  measure isB           :: Tree a -> Prop
    isB (Node c x l r)  = c == B
    isB (Leaf)          = True
\end{code}
%
and then we can describe the color invariant simply as:
%
\begin{code}
  measure isRB          :: Tree a -> Prop
    isRB (Leaf)         = True
    isRB (Node c x l r) = isRB l && isRB r &&
                          c = R => (isB l && isB r)
\end{code}
%
The insertion and deletion procedures create intermediate \emph{almost}
red-black trees where the color invariant may be violated at the root.
Rather than create new data constructors we define almost red-black
trees with a measure that just drops the invariant at the root:
%
\begin{code}
  measure almostRB          :: Tree a -> Prop
    almostRB (Leaf)         = True
    almostRB (Node c x l r) = isRB l && isRB r
\end{code}

\mypara{Height Invariant}
To specify the height invariant, we define a black-height measure:
%
\begin{code}
  measure bh          :: Tree a -> Int
    bh (Leaf)         = 0
    bh (Node c x l r) = bh l + if c = R then 0 else 1
\end{code}
%
and we can now specify black-height balance as:
%
\begin{code}
  measure isBal          :: Tree a -> Prop
    isBal (Leaf)         = true
    isBal (Node c x l r) = bh l = bh r
                         && isBH l && isBH r
\end{code}
%
Note that @bh@ only considers the left sub-tree,
but this is legitimate, because @isBal@ will
ensure the right subtree has the same @bh@.

\mypara{Order Invariant}
We refine the data definition of @Tree@
to encode the ordering property:
%
\begin{code}
  data Tree a
    = Leaf
    | Node { c   :: Col
           , key :: a
           , lt  :: Tree {v:a | v < key }
           , rt  :: Tree {v:a | key < v } }
\end{code}
%

\mypara{Composing Invariants}
Finally, we can compose the invariants and define a
Red-Black tree with the alias:
%
\begin{code}
  type RBT a = {v:Tree a | isRB v && isBal v}
\end{code}
%
An almost Red-Black tree is the above with @isRB@
replaced with @almostRB@, \ie does not require any
new types or constructors.
If desired, we can ignore a particular invariant
simply by replacing the corresponding refinement
above with @true@.
Given the above -- and suitable signatures \toolname
verifies the various insertion, deletion and rebalancing
procedures for a Red-Black Tree library.

\subsection{Stack Sets in XMonad}\label{sec:xmonad}

\lbxmonad is a dynamically tiling \texttt{X11}
window manager that is written and configured in Haskell.
The set of windows managed by XMonad is organized into a
hierarchy of types. At the lowest level we have a
\emph{set} of windows @a@ represented as a @Stack a@
%
\begin{code}
  data Stack a = Stack { focus :: a
                       , up    :: [a]
                       , down  :: [a] }
\end{code}
%
The above is a zipper~\cite{zipper} where @focus@ is the
``current" window and @up@ and @down@ the windows ``before"
and ``after" it.
%
Each @Stack@ is wrapped inside a @Workspace@ that also has
information about layout and naming:
%
\begin{code}
  data Workspace i l a = Workspace
     { tag    :: i
     , layout :: l
     , stack  :: Maybe (Stack a) }
\end{code}
%
which is in turn, wrapped inside a @Screen@:
%
\begin{code}
  data Screen i l a sid sd = Screen
    { workspace    :: Workspace i l a
    , screen       :: sid
    , screenDetail :: sd }
\end{code}
%
The set of all screens is represented by the top-level zipper:
%
\begin{code}
  data StackSet i l a sid sd = StackSet
    { cur :: Screen i l a sid sd
    , vis :: [Screen i l a sid sd]
    , hid :: [Workspace i l a]
    , flt :: M.Map a RationalRect }
\end{code}

\mypara{Key Invariant: Uniqueness of Windows}
The key invariant for the @StackSet@ type is that each window @a@
should appear at most once in a @StackSet i l a sid sd@. That is,
a window should \emph{not be duplicated} across stacks or workspaces.
Informally, we specify this invariant by defining a measure for the
\emph{set of elements} in a list, @Stack@, @Workspace@ and @Screen@,
and then we use that measure to assert that the relevant sets are
disjoint.

\mypara{Specification: Unique Lists} To specify that the set of elements
in a list is unique, \ie there are no duplicates in the list we first define
a measure denoting the set using Z3's~\citep{z3} built-in theory of sets:
%
\begin{code}
  measure elts  :: [a] -> Set a
    elts ([])   = emp
    elts (x:xs) = cup (sng x) (elts xs)
\end{code}
%
Now, we can use the above to define uniqueness:
%
\begin{code}
  measure isUniq  :: [a] -> Prop
    isUniq ([])   =  true
    isUniq (x:xs) =  notIn x xs && isUniq xs
\end{code}
%
where @notIn@ is an abbreviation:
%
\begin{code}
  predicate notIn X S = not (mem X (elts S))
\end{code}

\mypara{Specification: Unique Stacks}
We can use @isUniq@ to define unique, \ie, duplicate free,
@Stack@s as:
%
\begin{code}
  data Stack a = Stack
   { focus :: a
   , up    :: {v:[a] | Uniq1 v focus}
   , down  :: {v:[a] | Uniq2 v focus up} }
\end{code}
%
using the aliases
%
\begin{code}
  predicate Uniq1 V X    = isUniq V  && notIn X V
  predicate Uniq2 V X Y  = Uniq1 V X && disjoint Y V
  predicate disjoint X Y = cap (elts X) (elts Y) = emp
\end{code}
%
\ie the field @up@ is a unique list of elements different
from @focus@, and the field @down@ is additionally disjoint
from @up@.

\mypara{Specification: Unique StackSets}
It is straightforward to lift the @elts@ measure to
the @Stack@ and the wrapper types @Workspace@ and
@Screen@, and then correspondingly lift @isUniq@ to
@[Screen]@ and \hbox{@[Workspace]@.}
%
Having done so, we can use those measures to refine
the type of @StackSet@ to stipulate that there are
no duplicates:
%
\begin{code}
  type UniqStackSet i l a sid sd
    = {v: StackSet i l a sid sd | NoDups v}
\end{code}
%
using the predicate aliases
%
\begin{code}
  predicate NoDups V
    =  disjoint3 (hid V) (cur V) (vis V)
    && isUniq (vis V) && isUniq (hid V)

  predicate disjoint3 X Y Z
    =  disjoint X Y && disjoint Y Z && disjoint X Z
\end{code}
%
\toolname automatically turns the record selectors of
refined data types to measures that return the values
of appropriate fields, hence @hid x@ (resp. @cur x@, @vis x@)
are the values of the \hbox{@hid@,} @cur@ and @vis@ fields of
a @StackSet@ named @x@.

%%%% \begin{code}
%%%% data Stack a = Stack { focus :: a
%%%%                      , up    :: ULNEq a focus
%%%%                      , down  :: ULNEq a focus }
%%%%
%%%% data StackSet i l a sid sd = StackSet
%%%%    { lcurrent  ::  Screen i l a sid sd
%%%%    , lvisible  :: [Screen i l a sid sd]
%%%%    , lhidden   :: [Workspace i l a]
%%%%    , lfloating :: M.Map a RationalRect
%%%%    }
%%%% \end{code}
%%%% %
%%%% data Stack a = Stack { focus  :: !a
%%%%                      , up     :: [a]
%%%%                      , down   :: [a] }
%%%%
%%%% data Stack a = Stack { focus :: a
%%%%                      , up    :: UListDif a focus
%%%%                      , down  :: UListDif a focus }
%%%%
%%%% data Workspace i l a = Workspace  { tag :: !i, layout :: l, stack :: Maybe (Stack a) }
%%%%
%%%% data Workspace i l a = Workspace  { tag :: i, layout :: l, stack :: Maybe (UStack a) }
%%%%
%%%% type UStack a = {v:(Stack a) | (ListDisjoint (getUp v) (getDown v))}
%%%%
%%%%
%%%% data Screen i l a sid sd = Screen { workspace     :: !(Workspace i l a)
%%%%                                   , screen        :: !sid
%%%%                                   , screenDetail  :: !sd }
%%%%
%%%% data StackSet i l a sid sd =
%%%%     StackSet { current  :: !(Screen i l a sid sd)    -- ^ currently focused workspace
%%%%              , visible  :: [Screen i l a sid sd]     -- ^ non-focused workspaces, visible in xinerama
%%%%              , hidden   :: [Workspace i l a]         -- ^ workspaces not visible anywhere
%%%%              , floating :: M.Map a RationalRect      -- ^ floating windows
%%%%              }
%%%%
%%%% A workspace is just a @Stack@ of virtual workspaces
%%%% tagged with a tag @i@ and its layout @l@
%%%% @Workspace i l a@.
%%%%
%%%% To view a workspace on a physical screen one needs to
%%%% associate the workspace with physical screen's id @sid@
%%%% and details @sd@,
%%%% forming the new data structure @Screen i l a sid sd@.
%%%%
%%%% Xinerama in X11 allows viewing multiple virtual workspaces
%%%% simultaneously.
%%%% %
%%%% While only one the current one will ever be in focus (i.e. will
%%%% receive keyboard events), other workspaces may be passively
%%%% viewable.
%%%% %
%%%% We thus need to track which virtual workspaces are
%%%% associated (viewed) on which physical screens.
%%%% %
%%%% To keep track of
%%%% this, \lbxmonad's main data structure  @StackSet i l a sid sd@
%%%% keeps, apart from the current screen,
%%%% separate lists of visible but non-focused
%%%% workspaces (@Screen@) , and non-visible workspaces (@Workspace@).

%%%% \mypara{Unique Stack}
%%%% Assume the existence of a predicate
%%%% @ULNeq (X::a) (XS::[a])@ that ensures that
%%%% (1)~the list @XS@ has no duplicates and
%%%% (2)~@X@ is not an element of @XS@.
%%%% %
%%%% With that magical predicate we define an \emph{almost unique}
%%%% stack:
%%%% \begin{code}
%%%% data Stack a = Stack { focus :: a
%%%%                      , up    :: ULNEq a focus
%%%%                      , down  :: ULNEq a focus }
%%%% \end{code}
%%%% The stack has a @focus@ element @a@ and
%%%% and two unique lists of @a@'s @up@ and @down@ of the focus.
%%%%
%%%% The above Stack is almost unique, as an element
%%%% may appear both in the @up@ and the @down@ lists.
%%%% %
%%%% We define a type alias for @U@nique@Stack@
%%%% that rejects with possibility:
%%%%
%%%% \begin{code}
%%%% type UStack a = {v:(Stack a) |  (LDisjoint (up v) (down v))}
%%%%
%%%% predicate LDisjoint X Y =
%%%%   (Set_emp (Set_cap (elts X) (elts Y)))
%%%% \end{code}
%%%%
%%%%
%%%% Note that the above definitions crucially depend on set theoretic properties.
%%%% Thus, verification of \lbxmonad is achieved using an SMT back-end
%%%% that supports set theory (like Z3~\citep{z3}).
%%%%
%%%% We slightly modify the above measure definition
%%%% to define @dups@, a measure that returns the
%%%% duplicate elements of a list.
%%%% %
%%%% \begin{code}
%%%%   measure dups :: [a] -> Set a
%%%%   dups ([])  = emp v
%%%%   dups(x:xs) = if mem x (elts xs)
%%%%                  then cup (sng x) (dups xs)
%%%%                  else (dups xs)
%%%% \end{code}
%%%%
%%%% Using @dups@ we define the magical list type @ULNEq a N@
%%%% as a list @v@ that has no duplicates, \ie the set @dups v@
%%%% is empty, and @N@ does not belong to the set @elts v@.
%%%%
%%%% \begin{code}
%%%% type ULNEq a N = {v:[a] | ( (UL v) && (not (LElt N v))}
%%%% predicate LElt N LS  = (Set_mem N (elts LS))
%%%% predicate UL     LS  = (Set_emp (dups LS)   )
%%%% \end{code}
%%%%
%%%% Throughout verification
%%%% we need to establish and use the invariant
%%%% that each Stack is Unique.
%%%% %
%%%% This is achieved by the following annotation
%%%% \begin{code}
%%%% using (Stack a) as (UStack a)
%%%% \end{code}
%%%% that allows \toolname to
%%%% (1)~ use the invariant:
%%%% each time a Stack value is retrieved from the environment
%%%% \toolname strengthens its type with the disjointness information;
%%%% (2)~ prove the invariant:
%%%% each time @Stack@ data constructor is used,
%%%% an disjoint constraint should be proved.
%%%% Failure to prove this constraint will raise an
%%%% ``Invariant Check'' error.
%%%%
%%%% \mypara{Unique StackSet}
%%%% Establishing Uniqueness on StackSets is a generalization of the above procedure.
%%%%
%%%% The definition of a @StackSet@ includes the @current@ Screen, the list of @visible@ screens,
%%%% and the list of @hidden@ workspaces.
%%%% \begin{code}
%%%% data StackSet i l a sid sd = StackSet
%%%%    { lcurrent  ::  Screen i l a sid sd
%%%%    , lvisible  :: [Screen i l a sid sd]
%%%%    , lhidden   :: [Workspace i l a]
%%%%    , lfloating :: M.Map a RationalRect
%%%%    }
%%%% \end{code}
%%%% %
%%%% \toolname automatically turns the record selectors of refined data types
%%%% to measures that return the appropriate fields.
%%%% %
%%%% Thus we infix the refined selectors with an @l@
%%%% to distinguish between the haskell (\eg, @current@)
%%%% and the logical (\eg, @lcurrent@) selectors.
%%%%
%%%% To prove absence of duplicates we need to @use@
%%%% only @StackSet@s that have no duplicates:
%%%% \begin{code}
%%%% using (StackSet i l a sid sd)
%%%%  as  {v:StackSet i l a sid sd|(NoDuplicates v)}
%%%% \end{code}
%%%%
%%%% @NoDuplicates@ ensures that the elements of
%%%% @hidden@, @current@, and @visible@
%%%% workspaces are mutually disjoint
%%%% and that the @visible@ and @hidden@ workspaces
%%%% have no duplicates.
%%%% %
%%%% \begin{code}
%%%% predicate NoDuplicates SS =
%%%%     (Disjoint3  (workspacesElts (lhidden  SS))
%%%%                 (screenElts     (lcurrent SS))
%%%%                 (screensElts    (lvisible SS)))
%%%%   &&
%%%%     (Set_emp (screensDups    (lvisible SS)))
%%%%   &&
%%%%     (Set_emp (workspacesDups (lhidden  SS)))
%%%% \end{code}
%%%% %
%%%% Again we used recursively defined measures to grap
%%%% the elements and the duplicates of the structures.
%%%% For example, @screenElts@ returns
%%%% the elements of the stack of the workspace of the screen,
%%%% and is used by @screensDup@ to grap the duplicates of
%%%% a list of Screens.
%%%%
\mypara{Verification}
\toolname uses the above refined type to verify the key invariant,
namely, that no window is duplicated.
%
% However, the verification process, while eventually successful,
% revealed several limitations of our approach.
%
Three key actions of the, eventually successful, verification process
can be summarized as follows:
\begin{itemize}
\item\emph{Strengthening library functions.}
  \lbxmonad repeatedly concatenates the lists of a Stack. %edit to fix overful box
  %
  To prove that for some \hbox{@s:Stack a@,} @(up s ++ down s)@ is a unique list,
  the type of @(++)@ needs to capture that concatenation of two unique and
  disjoint lists is a unique list.
  %
  For verification, we assumed that Prelude's @(++)@ satisfies this property.
  %
  But, not all arguments of @(++)@ are unique disjoint lists:
  @"StackSet" ++ "error"@ is a trivial example that does not satisfy
  the assumed preconditions of @(++)@ thus creating a type error.
  %
  Currently, \toolname does not support intersection types,
  thus we used an unrefined @(++.)@ variant of @(++)@ for such cases.

\item\emph{Restrict the functions' domain.}
%% \RJ{Seems like you HAVE to do this -- has nothing to do with LH?}
  @modify@ is a @maybe@-like function that given a default value @x@,
  a function @f@, and a StackSet @s@, applies @f@ on the @Maybe@
  values inside @s@.
  %
\begin{code}
modify :: x:{v:Maybe (Stack a) | isNothing v}
       -> (y:Stack a -> Maybe {v:Stack a | SubElts v y})
       -> UniqStackSet i l a s sd
       -> UniqStackSet i l a s sd
\end{code}
	%
        Since inside the StackSet @s@ each @y:Stack a@ could be replaced
    with either the default value @x@ or with @f y@, we need to
    ensure that both these alternatives will not insert duplicates.
	%
	This imposes the curious precondition that the default
	value should be @Nothing@.

	\item\emph{Code inlining}
    %
    Given a tag @i@ and a StackSet @s@,  @view i s@ will set the current Screen
    to the screen with tag @i@, if such a screen exists in @s@.
    %
    Below is the original definition for @view@ in case when a screen with tag
    @i@ exists in visible screens
    %
\begin{code}
view :: (Eq s, Eq i) => i
     -> StackSet i l a s sd
     -> StackSet i l a s sd
view i s
  | Just x <- find ((i==).tag.workspace) (visible s)
  = s { current = x
      , visible = current s
                : deleteBy (equating screen) x (visible s) }
\end{code}
    %
    Verification of this code is difficult as we cannot suitably type @find@.
    %
    Instead we \emph{inline} the call to @find@ and the field update into a
    single recursive function @raiseIfVisible i s@ that in-place replaces @x@
    with the current screen.
\end{itemize}

Finally, \lbxmonad comes with an extensive suite of QuickCheck properties,
that were formally verified in Coq~\cite{Swierstra2012}. In future work~\ref{chapter:conclusion},
it would be interesting to do a similar verification with \toolname,
to compare the refinement types to proof-assistants.

%%% TODO \subsection{QuickCheck Properties}
%%% TODO
%%% TODO \lbxmonad is tested against $113$ \texttt{quickcheck} properties.
%%% TODO %
%%% TODO Of those $15$ check the uniqueness invariant
%%% TODO and the rest $113$ check various functional properties.
%%% TODO %
%%% TODO We started the endeavour of verifying these properties with \toolname.
%%% TODO %
%%% TODO We looked at a sample of $15$ properties to conclude that
%%% TODO which we categorized as follows:
%%% TODO \begin{itemize}
%%% TODO \item\emph{Easy to be proved.}
%%% TODO Consider the \texttt{quickcheck} property that checks that @view@ing
%%% TODO a @StackSet a@ is idempotent:
%%% TODO \begin{code}
%%% TODO prop_view_idem (x :: T) (i :: NonNegative Int)
%%% TODO   = i `tagMember` x ==> view i (view i x) == (view i x)
%%% TODO \end{code}
%%% TODO %
%%% TODO The above property directly translated to a haskell function
%%% TODO \begin{code}
%%% TODO type Valid     = {v:Bool | (Prop v) }
%%% TODO
%%% TODO prop_view_idem :: StackSet i l a sid sd -> i -> Valid
%%% TODO prop_view_idem x i
%%% TODO   | i `tagMember` x = view i (view i) == v
%%% TODO   | otherwise       = True
%%% TODO \end{code}
%%% TODO %
%%% TODO By the above type signature,
%%% TODO \ie by the result type @Valid@,
%%% TODO we specify that the function should always returns True.
%%% TODO %
%%% TODO When typechecking the above function,
%%% TODO \toolname proves that the property holds.
%%% TODO %
%%% TODO \toolname is able to verify this property as the result type of @view@
%%% TODO is strengthens with a refinement
%%% TODO (in this case @EqTag x i => x = v@)
%%% TODO that directly implies this property.
%%% TODO
%%% TODO The above is generalizing to (10/17) properties that we checked:
%%% TODO strengthening the function types by refinements that \toolname can prove
%%% TODO is sufficient to verify these properties.
%%% TODO
%%% TODO \item\emph{Can be estimated.}
%%% TODO In some other properties (like checking that @view@ing is reversible),
%%% TODO two StackSets (@s1@ and @s2@) were normalized before being compared,
%%% TODO that is their elements were first sorted.
%%% TODO %
%%% TODO In our logic we do not support any operation that can normalize structures in such a way.
%%% TODO %
%%% TODO Thus we cannot prove this exact property.
%%% TODO %
%%% TODO Instead we approximated it, by proving that proving that @s1@ and @s2@
%%% TODO have the same sets of elements.
%%% TODO %
%%% TODO We approximated (3/17) of the properties.
%%% TODO
%%% TODO \item\emph{Their proof cannot be supported, currently.} [1]
%%% TODO One \texttt{quickcheck} property checks
%%% TODO that @i@ cannot belong to an empty stackset.
%%% TODO %
%%% TODO We used abstract refinements to encode empty stacksets.
%%% TODO %
%%% TODO Proving the above property would be easy
%%% TODO if we could mix abstract and concrete refinements in logical formulas
%%% TODO or if \toolname supported sum types.
%%% TODO %
%%% TODO Both the alternatives constitutes features that
%%% TODO we would like to extend \toolname with in the near future.
%%% TODO %
%%% TODO Still, currently we are not able to prove such kind of properties.
%%% TODO \item\emph{Cannot be expressed}
%%% TODO Other properties %, like @prop_focus_left_master@
%%% TODO check that the order of the windows is not affected by certain operations.
%%% TODO %
%%% TODO Though not infeasible we acknowledge that \toolname
%%% TODO is not appropriate for reasoning about order preserving
%%% TODO and verification of such properties
%%% TODO would require many code modifications.
%%% TODO %
%%% TODO (3/17) are order preserving properties.
%%% TODO \end{itemize}