%!TEX root = ../thesis.tex
\chapter{Preliminaries}
\label{preliminaries}

\section{Overview}
\label{preliminaries:overview}

Cryptography is the art and science of securing digital information, transactions, and distributed computations in the presence of third parties~\cite{Katz:2014:IMC:2700550}. Cryptography is directly related to data privacy and anonymity requirements. The blockchain is a good example of cryptography embracement to enable the sought trust needed for the exchange of digital assets. In this section we review the basic building blocks that cryptography provides to a data sharing system when the blockchain is used. In this Section, cryptographic schemes are introduced in order to lay the ground for the following research. As a result, the exposition style will not be formal in well known cases.

\section{Cryptographic Hash Functions}
\label{preliminaries:hash}

A \textit{hash function} is a function which takes an input of arbitrary length and returns a fixed-length value~\cite{crypto_101,boneh_crypto,kiagias:crypto,Katz:2014:IMC:2700550}. The hash output value is called \textit{digest}.

Hash functions have many applications. They are used in data structures -- such as hash tables -- in authentication schemes, password verification and data identifiers to name just a few.

A hash function guarantees at a minimum that for the same input yields the same output. The size of the output is fixed, thus the output range is finite. For this reason it is possible two different inputs produce the same output. This phenomenon is called \textit{collision}.

\textit{Cryptographic hash functions} have much stronger properties than regular hash functions. Ideal cryptographic hash functions should be easily computable, noninvertible and collision-resistant~\cite{Katz:2014:IMC:2700550, kiagias:crypto, crypto_101}. A cryptographic hash function $H$ is a deterministic polynomial algorithm that takes as input any given string $x \in \{0, 1\}^{*}$ and outputs a string $H(x) \in \{0, 1\}^{k}$ where $k$ is of fixed size. In the case of a hash function $H$, a collision is a pair of distinct messages $m_0, m_1$ where $m_0 \neq m_1$ and $H(m_0) = H(m_1)$. A hash function $H$ is collision-resistant if it is infeasible for any polynomial-time algorithm to find collisions.

Three levels of security~\cite{Katz:2014:IMC:2700550} can be identified:

\begin{itemize}
  \item \textbf{Preimage resistance}: Given a digest $h$ it is hard to find any message $m$ with $H(m) = h$
  \item \textbf{Second preimage resistance}: For any given message $m_0$ it is hard to find a second message $m_1 \neq m_0$ such as $H(m_0) = H(m_1)$
  \item \textbf{Collision resistance}: It is hard to find a pair of messages $m_0, m_1$ where $m_0 \neq m_1$ and $H(m_0) = H(m_1)$
\end{itemize}

Collision resistance is the strongest security property and a requirement for cryptographic hash functions.

In a data sharing system, cryptographic hash functions can be used to provide file integrity verification and provenance tracking~\cite{10.1109/SPW.2015.27, Azaria2016}. File modifications in transit can be easily detected, as all changes output a different digest. A digest of a dataset serves as a means of unique file identification; unique persistent identifiers (PID) can be used as pointers to a data location. Any change to the PID is visible and trackable~\cite{dist_pid}.

Cryptographic hash functions are heavily used in the blockchain. They are used to create unique transactions and block IDs, to provide proofs of inclusion -- meaning to prove if a transaction is contained in a block -- and, most importantly, to achieve decentralized consensus among the participants. In particular, Bitcoin makes use of the SHA256 and RIPEMD160 hash functions. That said, cryptographic hash functions play an important role in the blockchain ecosystem.

\section{Symmetric-key cryptography}
\label{preliminaries:sym}

In a symmetric cryptosystem two parties share a common \textit{secret key} agreed prior to communication. The key is used for both encryption and decryption. When a party wants to securely send a message she has to use the secret key to encrypt it and then sent it. The receiver uses the same secret key to decrypt and recover the message. More formally, a symmetric cryptosystem is composed of the following algorithms~\cite{Katz:2014:IMC:2700550, kiagias:crypto}:

\begin{itemize}
  \item A \textbf{key generation algorithm} $\calg$ that takes as input a security parameter $1^{n}$ and outputs a key $k$.
  \item An \textbf{encryption algorithm} $\cale$ that takes as input a key $k$ and a plaintext $m$ and outputs a ciphertext $c$.
  \item A \textbf{decryption algorithm} $\cald$ that takes as input a key $k$ and a ciphertext $c$ and outputs a plaintext $m$.
\end{itemize}

The set of all possible keys which can derive from the key generation algorithm $\calg$ is called the \textit{key space} $\calk$. Respectively, the set of all possible plaintext is called the \textit{plaintext message space} denoted $\calm$, and the set of all possible ciphertexts is called \textit{ciphertext message space} denoted $\calc$. In practice, keys are usually of some fixed length; 256-bit keys are very common. On the other hand, messages and ciphertexts can be of arbitrary length. For example, a message may be a video or a music file or even a single bit.

A symmetric cryptosystem must satisfy the \textit{correctness} property: for all $m \in \calm$ and $k \in \calk$, it holds that:

\begin{equation*}
  \cald_{k}(\cale_{k}(m)) = m
\end{equation*}

Any deterministic cryptosystem can not be secure~\cite{Katz:2014:IMC:2700550, kiagias:crypto}. For this reason, randomness is essential to any encryption scheme.

In the following chapters the notions of cipher and symmetric encryption scheme or symmetric scheme are identical and will be used interchangeably.

\subsection{Block Ciphers}
\label{preliminaries:sym:block}

A block cipher is a deterministic algorithm that encrypts blocks -- a sequence of bits -- of fixed length. The plaintext and the ciphertext is always of the same size. The size is fixed by the block cipher and is called the \textit{block size}. The message space $\calm$ and ciphertext space $\calc$ are the same finite set $\{ 0, 1\}^{n}$ and the key space is  $\calk = \{ 0, 1\}^{l}$.

Formally, a block cipher is a keyed permutation function $F: \{ 0, 1\}^{n} \times \{ 0, 1\}^{l} \rightarrow \{ 0, 1\}^{n}$ where $n$ is the block size and $l$ the key size. Usually, the block size and the key size are the same; common key and block sizes range from $128$ to $512$ bits. The function $F$ must be \textit{one-to-one} for every key $k \in \calk$ and both $F$ and its inverse $F^{-1}$ should be easily computed; there is polynomial-time algorithm that given $k$ computes $F$ and $F^{-1}$. The number of total permutation a block cipher can produce is $2^{n}!$.

The security of a block cipher is much stronger than semantic security~\cite{boneh_crypto}: A permutation produced by $F$ is indistinguishable from a random permutation. Cryptographic schemes based on block ciphers with rigorous proofs of security can, therefore, be constructed.

\begin{figure}[!ht]
    \centering
    \begin{tikzpicture}[node distance=2.5cm,auto,>=latex']
      \node [cipher, minimum size=7em] (a) {AES};
      \draw[<-] (a.west)  -- node[above]{$128$ bits} node[left, xshift=-2em]{$m$} ++(-4em,0em);
      \draw[->] (a.east)  -- node[above]{$128$ bits} node[right, xshift=2em]{$c$} ++(4em,0em);
      \draw[<-] (a.north)  -- node[right]{$128$ bits} node[above, yshift=2em]{$k$} ++(0em,4em);
    \end{tikzpicture}
  \caption{Block cipher AES}
  \label{fig:sym:block:aes}
\end{figure}

\subsubsection[Modes of Operation]{Modes of Operation~\cite{Katz:2014:IMC:2700550}}
\label{preliminaries:sym:modes}

A mode of operation is a way to encrypt arbitrary-length messages using block ciphers of fixed message length. A message is broken into $l$ blocks of size $n$, the block cipher operating on each block. If the size of the last block is less than the block size, the block is padded to a full size block. In most modes of operation, a random initial vector (IV) of length $n$ is required. The IV ensures distinct ciphertexts for each encryption even for the same plaintext and key. The IV is not secret as it is crucial for completing decryption. For a mode to be secure, the IV must be distinct and random in each encryption~\cite{Katz:2014:IMC:2700550}

Several modes of operation are presented below. These modes are vulnerable either to padding oracle attacks~\cite{padding_attacks} -- attacks that exploit the padding validation to decrypt the ciphertext -- or malleable~\cite{malleability} -- the property of transforming one ciphertext into another which decrypts to a different plaintext. To countermeasure padding oracle attacks, or changes to the ciphertext, message authentication~\cite{Katz:2014:IMC:2700550} should be used along with encryption to detect tampering with the ciphertext. Notable modes that combine encryption with authentication are Counter with CBC-MAC (CCM), Offset Codebook Mode (OCB) and Galois/Counter Mode (GCM).

\epar{Electronic Codebook (ECB)}
\label{preliminaries:sym:modes:ecb}

The Electronic Codebook (ECB) is the simplest mode of operation. Given a plaintext $m = m_1, m_2, \dots, m_l$ each block is encrypted separately. The ciphertext is $c = F_k(m_1), F_k(m_2), \dots, F_k(m_l)$. ECB mode is not secure and should never be used.

\epar{Cipher Block Chaining (CBC)}
\label{preliminaries:sym:modes:cbc}

The Cipher Block Chaining (CBC) mode outputs a sequence of cipher blocks where each plaintext block is XORed with the previous ciphertext block. Each ciphertext is dependent on all preceding blocks. First, a random IV of length $n$ is selected. The first plaintext block is XORed with the IV. The second block is XORed with the first cipher block $c_1$. In general, let $c_0 = IV$ then $c_i = F_k(c_{i-1} \xor m_i) \mbox{, } \forall i \in [1, l]$.

The main drawback of CBC mode is that encryption and decryption are sequential -- meaning that they cannot be parallelized.

\epar{Output Feedback (OFB)}
\label{preliminaries:sym:modes:ofb}

The Output Feedback (OFB) mode uses the block cipher to generate a pseudorandom stream which is then XORed with the plaintext. The stream is generated only by repeatedly encrypting the IV independently of the plaintext. The stream is generated as follows. Set the $i$-th block of the stream to $r_i = F_k(r_{i-1})$ where $r_0 = IV \rselect{\{ 0, 1 \}^{n}}$. The ciphertext is produced by XORing the plaintext with the appropriate stream block; that is, $c_i = m_i \xor r_i$.

As in CBC, the encryption and decryption cannot be parallelized. On the other hand, the pseudorandom stream can be computed independently of the actual message encryption and can be prepared ahead of time.

\epar{Counter (CTR)}
\label{preliminaries:sym:modes:ctr}

The Counter (CTR) mode, like OFB, also generates a pseudorandom stream. First, a random $CTR \rselect{\{ 0, 1 \}^{n}}$ is chosen -- much like the IV in previous modes. The stream is generated as $r_i = F_k(CTR + i)$ where $r_0 = CTR$. Same as before, the ciphertext is computed as $c_i = m_i \xor r_i$.

CTR mode has many advantages. One of the main advantages of CTR mode is that both encryption and decryption can be fully parallelized. Secondly, as with OFB, the stream can be computed in advance. Finally, it is possible to decrypt the $i$-th block of the ciphertext without having to decrypt any other cipher block. This property is called random access.

\begin{figure}[!ht]
    \centering
    \begin{tikzpicture}[node distance=2.5cm,auto,>=latex']
      \node [cipher] (a) {$F_k$};
      \node [cipher, right of=a] (b) {$F_k$};
      \node [cipher, right of=b] (c) {$F_k$};
      \draw[<-] (a.north)  -- node[above, yshift=2em]{$m_1$} ++(0em,4em);
      \draw[<-] (b.north)  -- node[above, yshift=2em]{$m_2$} ++(0em,4em);
      \draw[<-] (c.north)  -- node[above, yshift=2em]{$m_3$} ++(0em,4em);
      \draw[->] (a.south)  -- node[below, yshift=-2em]{$c_1$} ++(0em,-4em);
      \draw[->] (b.south)  -- node[below, yshift=-2em]{$c_2$} ++(0em,-4em);
      \draw[->] (c.south)  -- node[below, yshift=-2em]{$c_3$} ++(0em,-4em);
    \end{tikzpicture}
  \caption{ECB mode}
  \label{fig:sym:block:ecb}
\end{figure}

\begin{figure}[!ht]
    \centering
    \begin{tikzpicture}[node distance=3cm,auto,>=latex']
      \node [cipher] (a) {$F_k$};
      \node [cipher, right of=a] (b) {$F_k$};
      \node [cipher, right of=b] (c) {$F_k$};
      \node [above of=a, node distance=2cm] (xor1) {$\xor$};
      \node [above of=b, node distance=2cm] (xor2) {$\xor$};
      \node [above of=c, node distance=2cm] (xor3) {$\xor$};

      \node[left of=a] (iv) {$IV$};

      \draw[<-] (xor1.north)  -- node[above, yshift=1em]{$m_1$} ++(0em,2em);
      \draw[<-] (a.north)  -- (xor1.south) node[above, yshift=1em]{};

      \draw[<-] (xor2.north)  -- node[above, yshift=1em]{$m_2$} ++(0em,2em);
      \draw[<-] (b.north)  -- (xor2.south) node[above, yshift=1em]{};

      \draw[<-] (xor3.north)  -- node[above, yshift=1em]{$m_3$} ++(0em,2em);
      \draw[<-] (c.north)  -- (xor3.south) node[above, yshift=1em]{};

      \draw[->] (a.south)  -- node[below, yshift=-2em]{$c_1$} ++(0em,-4em);
      \draw[->] (b.south)  -- node[below, yshift=-2em]{$c_2$} ++(0em,-4em);
      \draw[->] (c.south)  -- node[below, yshift=-2em]{$c_3$} ++(0em,-4em);

      \draw[->] (iv.south)  -- node[below, yshift=-2.5em]{$IV$} ++(0em,-5em);

      \draw[->] ([yshift=-4em]a.center) -- ++(3.5em,0em) -- ++(0em,8.7em) -- (xor2.west);
      \draw[->] ([yshift=-4em]b.center) -- ++(3.5em,0em) -- ++(0em,8.7em) -- (xor3.west);

      \draw[->] (iv.north) -- ++(0em, 3.95em) -- (xor1.west);

    \end{tikzpicture}
  \caption{CBC mode}
  \label{fig:sym:block:cbc}
\end{figure}

\begin{figure}[!ht]
    \centering
    \begin{tikzpicture}[node distance=3cm,auto,>=latex']
      \node [cipher] (a) {$F_k$};
      \node [cipher, right of=a] (b) {$F_k$};
      \node [cipher, right of=b] (c) {$F_k$};
      \node [below of=a, node distance=2cm] (xor1) {$\xor$};
      \node [below of=b, node distance=2cm] (xor2) {$\xor$};
      \node [below of=c, node distance=2cm] (xor3) {$\xor$};

      \node[left of=a] (iv) {$IV$};

      \draw[->] (a.south)  -- (xor1.north);
      \draw[->] (xor1.south)  -- node[below, yshift=-1em]{$c_1$} ++(0em,-2em);
      \draw[<-] (xor1.west)  -- node[left, xshift=-1em]{$m_1$} ++(-2em,0em);

      \draw[->] (b.south)  -- (xor2.north);
      \draw[->] (xor2.south)  -- node[below, yshift=-1em]{$c_2$} ++(0em,-2em);
      \draw[<-] (xor2.west)  -- node[left, xshift=-1em]{$m_2$} ++(-2em,0em);
      \draw[->] ([yshift=-3em]a.center) -- ++(3.5em,0em) -- ++(0em,7.7em) --  ++(3.6em,0em) -- (b.north);

      \draw[->] (c.south)  -- (xor3.north);
      \draw[->] (xor3.south)  -- node[below, yshift=-1em]{$c_3$} ++(0em,-2em);
      \draw[<-] (xor3.west)  -- node[left, xshift=-1em]{$m_3$} ++(-2em,0em);
      \draw[->] ([yshift=-3em]b.center) -- ++(3.5em,0em) -- ++(0em,7.7em) --  ++(3.6em,0em) -- (c.north);

      \draw[->] (iv.north) -- ++(0em, 4em) -- ++(7.1em, 0em) -- (a.north);
      \draw[->] (iv.south)  -- node[below, yshift=-3.5em]{$IV$} ++(0em,-6em);

    \end{tikzpicture}
  \caption{OFB mode}
  \label{fig:sym:block:ofb}
\end{figure}

\begin{figure}[!ht]
    \centering
    \begin{tikzpicture}[node distance=3cm,auto,>=latex']
      \node [cipher] (a) {$F_k$};
      \node [cipher, right of=a] (b) {$F_k$};
      \node [cipher, right of=b] (c) {$F_k$};
      \node [below of=a, node distance=2cm] (xor1) {$\xor$};
      \node [below of=b, node distance=2cm] (xor2) {$\xor$};
      \node [below of=c, node distance=2cm] (xor3) {$\xor$};

      \draw[<-] (a.north)  -- node[above, yshift=1em]{$CTR + 1$} ++(0em,2em);
      \draw[<-] (b.north)  -- node[above, yshift=1em]{$CTR + 2$} ++(0em,2em);
      \draw[<-] (c.north)  -- node[above, yshift=1em]{$CTR + 3$} ++(0em,2em);

      \node[left of=a] (iv) {$CTR$};

      \draw[->] (a.south)  -- (xor1.north);
      \draw[->] (xor1.south)  -- node[below, yshift=-1em]{$c_1$} ++(0em,-2em);
      \draw[<-] (xor1.west)  -- node[left, xshift=-1em]{$m_1$} ++(-2em,0em);

      \draw[->] (b.south)  -- (xor2.north);
      \draw[->] (xor2.south)  -- node[below, yshift=-1em]{$c_2$} ++(0em,-2em);
      \draw[<-] (xor2.west)  -- node[left, xshift=-1em]{$m_2$} ++(-2em,0em);

      \draw[->] (c.south)  -- (xor3.north);
      \draw[->] (xor3.south)  -- node[below, yshift=-1em]{$c_3$} ++(0em,-2em);
      \draw[<-] (xor3.west)  -- node[left, xshift=-1em]{$m_3$} ++(-2em,0em);

      \draw[->] (iv.south)  -- node[below, yshift=-3.5em]{$CTR$} ++(0em,-6em);

    \end{tikzpicture}
  \caption{CTR mode}
  \label{fig:sym:block:ctr}
\end{figure}

\section{Public Key Cryptography}
\label{preliminaries:pub}

As we see in~\ref{preliminaries:sym} a secret key needs to be agreed upon prior to communication. In 1976, Whitfield Diffie and Martin Hellman published a paper called New Directions in Cryptography~\cite{Diffie:2006:NDC:2263321.2269104} which changed completely the way we communicate. The two cryptographers proposed a protocol that enabled two parties, having no prior communication, to establish a secret key over an insecure channel in the presence of eavesdropping adversaries. The protocol uses two keys, one for encryption and one for decryption. The encryption key is called the \textit{public key} and the decryption key is called the \textit{secret key} (or private). Every party has a key pair, consisting of a public and a secret key. The public is available to anyone who wants to sent an encrypted message to the key holder -- the receiver may post the public key online beforehand. The receiver of the message decrypts the ciphertext with the use of her private key. Only the owner of the private key can decrypt a message that was encrypted using the corresponding public key. Any key pair is essentially an identity and the blockchain smartly utilizes it to provide anonymous identities to the users of the system.

A public-key encryption scheme is composed of the following probabilistic, polynomial-time algorithms~\cite{Katz:2014:IMC:2700550, kiagias:crypto}:

\begin{itemize}
  \item The \textbf{key generation algorithm} $\calg$: Takes as input a security parameter $1^{n}$ it and outputs a key pair ($p_k$, $s_k$).
  \item The \textbf{encryption algorithm} $\cale$: Takes as input a public key $p_k$ and a plaintext $m$ and outputs a ciphertext $c$.
  \item The \textbf{decryption algorithm} $\cald$: Takes as input a private key $s_k$ and a ciphertext $c$ and outputs a plaintext $m$.
\end{itemize}

Likewise, a public-key cryptosystem must satisfy the correctness property: for all $m \in \calm$ and $(p_k, s_k) \in \calk$, it holds that:

\begin{equation*}
  \cald_{s_k}(\cale_{p_k}(m)) = m
\end{equation*}

Many important and widely used public-key schemes base their security on mathematical problems that, under certain conditions, are assumed to be hard; they cannot be solved in polynomial time. Such problems are the discrete logarithm and the factoring problem.

\subsection[Discrete Logarithm and Diffie-Hellman Assumptions]{Discrete Logarithm and Diffie-Hellman Assumptions~\cite{Katz:2014:IMC:2700550, kiagias:crypto}}
\label{preliminaries:pub:dlog}

In cryptography a system is considered to be secure if it is provable secure. There are cryptosystems which are perfectly secure~\cite{shannon_otp}, like the \textit{one-time pad}~\cite{shannon_otp}, and others that perfect security cannot be achieved. In the second case security can be proven by computational security assumptions, in other words a reduction to a particular problem which under certain conditions is assumed to be hard to solve in polynomial-time. Significant cryptographic schemes like the Diffie-Hellman key exchange and El Gamal encryption and signature protocol are built according to the discrete log computational hardness assumption.

\begin{dfn}
  Let $\G$ be a cyclic group of order $q$ and let $g$ be a generator of $\G$. The \textit{discrete log problem} (DLOG) is as follows: given a random element $h \in \G$, find an integer $x \in \Z_q$ such that $g^{x} = h$.
\end{dfn}

\begin{dfn}
 The \textit{computational Diffie-Hellman problem} (CDH) is as follows: given a cyclic group $\G$ of order $q$, a generator $g \in \G$, $g^{a}$ and $g^{b}$ where $a, b \rselect{\Z_q}$, compute $g^{ab}$.
\end{dfn}

\begin{dfn}
 The \textit{decisional Diffie-Hellman problem} (DDH) is as follows: given a cyclic group $\G$ of order $q$, a generator $g \in \G$, and $g^{a}, g^{b}, g^{c}$ where $a, b, c \rselect{\Z_q}$, decide if $c = ab$ or $c \rselect{\Z_q}$.
\end{dfn}

The DLOG problem is believed to be hard for specific group families of $\G$. For example, solving the DLOG for the subgroup of order $q$ of $\Z^{*}_{p}$, where $p$ and $q$ are primes of size at least $2048$-bits and $256$-bits respectively, is considered infeasible. This assumption is called the \textit{discrete log assumption}.

The DDH problem is weaker than the CDH problem. It holds that $DDH \leq CDH$; if an adversary can solve CDH she can compute $g^{ab}$ and compare it to $g^{c}$ and easily solve the DDH.

\section{Digital signatures}
\label{preliminaries:sign}

A \textit{digital signature} is a fundamental cryptographic primitive. It is considered to be the equivalent to a handwritten signature. It is a scheme that demonstrates the authenticity of digital messages or documents.

In a digital signature scheme, each party holds a unique key pair $(p_k, s_k)$. A message $m$ is uniquely signed with the \textit{signing key} $s_k$ and the \textit{verification key} $p_k$ is used to verify the signature. Only someone who knows $s_k$ can sign a message, but all parties that have access to $p_k$ can verify a signature.

Digital signatures have the following important properties:

\begin{itemize}
  \item \textbf{Authentication}: The message is signed by a known sender
  \item \textbf{Non-repudiation}: The sender cannot deny sending the message
  \item \textbf{Integrity}: The message is not altered in transit
\end{itemize}

Digital signatures are commonly used for software distribution and financial transactions and in cases where forgery detection is important. The blockchain uses digital signatures to provide asset ownership; the rightful owner signs the transaction to prove her possession of the asset.

A digital signature scheme is composed of the following probabilistic polynomial-time algorithms~\cite{Katz:2014:IMC:2700550,kiagias:crypto}:

\begin{itemize}
  \item The key \textbf{generation algorithm} $Gen$: Takes as input a security parameter $1^{n}$ and outputs a key pair ($p_k$, $s_k$).
  \item A \textbf{signing algorithm} $Sign$: Takes a signing key $s_k$ and a message $m$ and produce a digital signature $\sigma$ of $m$
  \item A \textbf{deterministic verification} algorithm $Verify$: Takes a verification key $p_k$ and a signature $\sigma$. It outputs $b=1$ or $b=0$ ($true$ or $false$) to indicate if the signature is valid.
\end{itemize}

The primary goal of digital signatures is \textit{unforgeability}; an adversary cannot create a new valid message-signature pair without the corresponding signing key.

\subsection{El Gamal Signature Scheme}
\label{preliminaries:sign:el_gamal}

The \textit{El Gamal Signature Scheme}~\cite{el_gamal} is a digital signature scheme based on the difficulty of the discrete logarithm problem (§~\ref{preliminaries:pub:dlog}).

The scheme works as follows:

\begin{itemize}
  \item \textbf{Key Generation}:
    \begin{enumerate}
      \item Choose a cryptographic hash function $H$ where $H: \{0, 1\}^{*} \rightarrow \{0, 1\}^{n}$
      \item Choose a prime $p$ such that the DLOG problem is difficult
      \item Find a generator $g$ of the group $\Z^{*}_{p}$
      \item Choose randomly $x \rselect{\Z_q}$
      \item Compute $h = g^{x} modp$
      \item Return $(h, x)$ where $h$ is the public key and $x$ the private key
    \end{enumerate}
  \item \textbf{Sign}: Sign a message $m \in \{0, 1\}^{*}$ with a private key $x$
    \begin{enumerate}
      \item Choose randomly $k \rselect{\Z_q}$ such that $gcd(k, p - 1) = 1$
      \item Compute $r = g^{k}modp$
      \item Compute $s = k^{-1}(H(m) + xr) mod(p - 1)$
      \item Return the signature $(r, s)$
    \end{enumerate}
  \item \textbf{Verify}: Verify a signature $(r, s)$ of the message $m$ with a public key $h$
    \begin{enumerate}
      \item Verify that $r \in \Z_q$ and $s \in \Z_q$. Else ouput $0$.
      \item Compute $v = H(m)$
      \item If $v \stackrel{?}{=} (h^{r}r^{s}) modp$ then output $1$ else $0$.
    \end{enumerate}
\end{itemize}

\subsection{Digital Signature Algorithm (DSA)}
\label{preliminaries:sign:dsa}

The \textit{Digital Signature Algorithm} (DSA)~\cite{dsa_nist} is a variant of the El Gamal signature scheme. The DSA was standardized by the National Institute of Standards and Technology (NIST). The main advantage of DSA over El Gamal Signature is the size of the signature. DSA produces signatures of $320$-bit in size, in comparison to El Gamal where at least $2048$-bit signatures are required for it to be secure according to contemporary security standards~\cite{dsa}.

The algorithm works as follows~\cite{dsa}:

\begin{itemize}
  \item \textbf{Key Generation}:
    \begin{enumerate}
      \item Choose a cryptographic hash function $H$ where $H: \{0, 1\}^{*} \rightarrow \{0, 1\}^{n}$
      \item Choose a prime $q$ of size $n$
      \item Choose a prime $p$ such that $p - 1$ is a multiple of $q$ of size $l$. The size of $l$ must be a multiple of $64$ between $512$ and $1,024$
      \item Choose randomly $a \rselect{\Z_p}$
      \item Compute $g = a^{(p - 1)/q} mod p$
      \item Choose randomly $x \rselect{\Z_q}$
      \item Compute $h = g^{x} modp$
      \item Return $((p, q, g), h, x)$ where $(p, q, g)$ is the public parameters of the algorithm, $h$ is the public key and $x$ the private key.
    \end{enumerate}
  \item \textbf{Sign}: Sign a message $m \in \{0, 1\}^{*}$ with a private key $x$
    \begin{enumerate}
      \item Choose randomly $k \rselect{\Z_q}$
      \item Compute $r = (g^{k}modp)modq$
      \item Compute $s = k^{-1}(H(m) + xr) modq$
      \item Return the signature $(r, s)$
    \end{enumerate}
  \item \textbf{Verify}: Verify a signature $(r, s)$ of the message $m$ with a public key $h$
    \begin{enumerate}
      \item Verify that $r \in \Z_q$ and $s \in \Z_q$. Else ouput $0$.
      \item Calculate $w = s^{-1}modq$
      \item Calculate $u_1 = (H(m)w)modq$
      \item Calculate $u_2 = (rw)modq$
      \item Calculate $v = ((g^{u_1}h^{u_2})modp)modq$
      \item If $v \stackrel{?}{=} r$ then output $1$ else $0$.
    \end{enumerate}
\end{itemize}

\section{Elliptic-curves}
\label{preliminaries:el_curves}

\textit{Elliptic curves} (ECC) play an import role in cryptography. All cryptosystems presented in previous chapters are built over multiplicative groups of integers modulo a sufficient large prime $p$~\cite{kiagias:crypto, boneh_crypto}. Elliptic curves are additive \textit{abelian groups}~\cite{kiagias:crypto}; a group satisfying associativity, commutativity, and existence of identity element and of inverse element under the addition group operation~\cite{elliptic_curves_2}.

There are two apparent benefits for using curves over modular groups~\cite{kiagias:crypto}. The first is cost efficiency. In practice, cryptosystems that their security depends on the discrete log problem or the factorisation problem on a modular group, such as the El Gamal or the RSA, the primes have to be at least 2048 bits for the system to be secure. On the other hand, elliptic curves offer similar security using much smaller key sizes. A 233-bit elliptic curve key gives the same level of security as a 2,240-bit RSA key~\cite{ecc_rsa_bits, ecc_rsa_bits_1} and a 333-bit elliptic curve key as a 4096-bit RSA key~\cite{blake1999elliptic}. The second reason is that a way to generalize the attacks against the discrete logarithm problem on a modular group to elliptic curves~\cite{kiagias:crypto} has not been found yet.

Cryptography is primarily interested in elliptic curves over $\F_p$: the field of integers modulo $p$, where $p$ is a prime number. An elliptic curve $E$ over $\F_p$ is defined by the equation of the form~\cite{elliptic_curves, elliptic_curves_2}:

\begin{equation*}
  y^2 = x^3 + ax + b
\end{equation*}

where $a, b \in \F_p$. A pair $(x, y)$ where $x, y \in \F_p$ is a point on the curve if it satisfies the equation where $E$ is defined. There is a special point, called \textit{point at infinity} and denoted by $\infty$, where is also on the curve and serve as the \textit{identity element}~\cite{elliptic_curves_2}.

\begin{figure}
  \centering
  \begin{tikzpicture}
    \begin{axis}[
            xmin=-4,
            xmax=5,
            ymin=-5,
            ymax=5,
            xlabel={$x$},
            ylabel={$y$},
            scale only axis,
            axis lines=middle,
            domain=-1.3247:2,
            y domain=-3:3,
            samples=200,
            smooth,
            clip=false,
            axis equal image=false,
            ticks=none
        ]

    \addplot[red] {sqrt(x^3-x+1)} node[right, black] {$y^2 = x^3 - x + 1$};
    \addplot[red] {-sqrt(x^3-x+1)};

    \end{axis}
    \end{tikzpicture}
  \caption{Elliptic curve}
\end{figure}

\subsection[Points addition]{Points addition~\cite{elliptic_curves}}
\label{preliminaries:el_curves:addition}

Let $P = (x_1, y_1)$ and $Q = (x_2, y_2)$ be two points on the elliptic curve $E$ where $P \neq Q$ and $P, Q \neq \infty$. Any two points on a curve add to produce a third point on the curve. A third point $R = (x_3, y_3)$ on the curve $E$ is defined as:

\begin{equation*}
  R = P + Q
\end{equation*}

We can find the third point $R$ as follows:

\begin{enumerate}
  \item Draw the line $L$ through $P$ and $Q$.
  \item Find the third point $-R$ that $L$ intersects with.
  \item Reflect $-R$ across the $x$-axis to obtain $R$
\end{enumerate}

The slope of the line $L$ can be found as

\begin{equation*}
  m = \dfrac{y_2 - y_1}{x_2 - x_1}
\end{equation*}

and assuming $x_1 \neq x_2$ the equation of $L$ is

\begin{equation*}
  y = m(x - x_1) + y_1
\end{equation*}

To find the intersection with $E$, substitute $y$ to get

\begin{equation*}
  (m(x - x_1) + y_1)^{2} = x^3 + ax + b
\end{equation*}

The three roots of cubic polynomial correspond to the three points of intersection of $L$ with $E$. As we already know the two of the tree roots, since $P$ and $Q$ are points on both $L$ and $E$, finding the third root is easy. For a cubic polynomial $x^{3} + ax^{2} + bx + c$ with roots $r, s, t$ it holds that~\cite{elliptic_curves}

\begin{equation*}
  x^{3} + ax^{2} + bx + c = (x - r)(x - s)(x - t) = x^{3} - (r + s + t)x^{2} + \dots
\end{equation*}

Therefore,

\begin{equation*}
  r + s + t = -a
\end{equation*}

Knowing the two roots $r, s$ we can recover the third as $t = -a - r  - s$.

So, to find the third point where $L$ intersects with $E$ we obtain

\begin{equation*}
  x = m^{2} + - x_1 - x_2
\end{equation*}

and

\begin{equation*}
  y = m(x - x_1) + y_1
\end{equation*}

Finally, to reflect $-R$ to the $x$-axis to obtain $R$ we change the sign of $y_1$. The final equations that give the third point are

\begin{align*}
  x_3 = m^{2} + - x_1 - x_2, && y_3 = m(x_1 - x_3) - y_1
\end{align*}

\begin{figure}
  \centering
  \begin{tikzpicture}
    \begin{axis}[
            xmin=-4,
            xmax=5,
            ymin=-5,
            ymax=5,
            xlabel={$x$},
            ylabel={$y$},
            scale only axis,
            axis lines=middle,
            domain=-1.3247:2,
            y domain=-3:3,
            samples=200,
            smooth,
            clip=false,
            axis equal image=false,
            ticks=none,
        ]

    \addplot[red] {sqrt(x^3-x+1)} node[right, black] {};
    \addplot[red] {-sqrt(x^3-x+1)};
    \addplot[blue, domain=-3:3,] {0.27*x + 0.87};

    \draw [fill=black] (axis cs:-1.25, 0.535) circle (2pt);
    \draw [fill=black] (axis cs:0.165, 0.9) circle (2pt);
    \draw [fill=black] (axis cs:1.165, 1.17) circle (2pt);
    \draw [fill=black] (axis cs:1.165, -1.17) circle (2pt);

    \draw [dashed] (axis cs:1.165, 1.17) -- (axis cs:1.165,-1.17);

    \draw[color=black] (axis cs:-1.4, 0.635) node [left]{$P$};
    \draw[color=black] (axis cs:0.0, 1.5) node [left]{$Q$};
    \draw[color=black] (axis cs: 1.4, 1.6) node [left]{$-R$};
    \draw[color=black] (axis cs: 3.7, -1) node [left]{$R = P + Q$};

    \end{axis}
    \end{tikzpicture}
  \caption{Addition of points on elliptic curves}
\end{figure}

\subsection[Points doubling]{Points doubling~\cite{elliptic_curves}}
\label{preliminaries:el_curves:doubling}

Let $P = (x_1, y_1)$ a point on the elliptic curve $E$ where $P \neq -P$ and $P \neq \infty$. Then $2P = (x_3, y_3)$. Unlike ~\ref{preliminaries:el_curves:addition} where there are two points, in point doubling we have only one point, thus we cannot draw the line $L$. In that case, we use the tangent line $L$ to the curve $E$ at point $P$.

The slope of $L$ can be found as:

\begin{equation*}
  m = \dfrac{dy}{dx} = \dfrac{3x_1^{2} + a}{2y_1}
\end{equation*}

Assuming $y_1 \neq 0$ the equation of $L$ is

\begin{equation*}
  y = m(x - x_1) + y_1
\end{equation*}

Therefore, proceeding as in~\ref{preliminaries:el_curves:addition}, we obtain

\begin{align*}
  x_3 = m^{2} + - 2x_1, && y_3 = m(x_1 - x_3) - y_1
\end{align*}

\subsection{Elliptic curve discrete logarithm problem (ECDLP)}

Cyclic subgroups of some elliptic curve groups can be used to implement secure systems based on the discrete logarithm problem. The DLOG is assumed to be hard, like in multiplicative groups.

\begin{dfn}
  The elliptic curve discrete logarithm problem (ECDLP) is as follows: given an elliptic curve $E$ over a finite field $\F_p$ and two points $P, Q \in E$, find an integer $d \in \Z_p$ such that $Q = dP$.
\end{dfn}

The parameters that describe an elliptic curve $E$ defined over a finite field $\F_p$, a base (generator) point $P \in E$, and its order $q$ should be chosen carefully so that the ECDLP is resistant to all known attacks.

\subsection[Key generation]{Key generation~\cite{elliptic_curves_2}}
\label{preliminaries:el_curves:key_gen}

Let $E$ be an elliptic curve over $\F_p$ and $P$ a generator point in $E$ of order $q$. The key pair generation algorithm is defined as follows:

\begin{enumerate}
  \item Select a random integer $d \rselect{\in \Z_q}$
  \item Compute $Q = dP$
  \item Return the tuple $(Q, d)$ where $Q$ is the public key and $d$ the secret key
\end{enumerate}

The prime $p$, the curve $E$ the generator point $P$, its order $q$ and the public key $Q$ are public. Finding the secret key $d$ is equivalent to solving the ECDLP.

\subsection{Elliptic Curve Digital Signature Algorithm (ECDSA)}
\label{preliminaries:sign:el_curves:ecdsa}

The \textit{Elliptic Curve Digital Signature Algorithm} (ECDSA)~\cite{ecdsa} is a variant of the Digital Signature Algorithm (DSA) which uses elliptic Curves. It is the most widely adopted elliptic curve-based signature scheme~\cite{elliptic_curves_2}.

Let $E$ be an elliptic curve over $\F_p$, a generator point $P$ of order $q$ and $H$ a cryptographic hash function where $H: \{0, 1\}^{*} \rightarrow  \{0, 1\}^{q}$. The ECDSA is defined as follows~\cite{elliptic_curves_2}:

\begin{itemize}
  \item \textbf{Key generation}: Run elliptic curve key generation algorithm defined in~\ref{preliminaries:el_curves:key_gen} and get a key pair $(Q, d)$.
  \item Sign: Sign a message $m$ with a private key $d$
    \begin{enumerate}
      \item Choose randomly $k \rselect{\Z_q}$
      \item Compute the point $kP = (x_1, y_1)$
      \item Compute $r = x_1modq$. If $r \stackrel{?}{=} 0$ then go to step 1
      \item Compute $e = H(m)$
      \item Compute $s = k^{-1} (e + dr) modq$. If $s \stackrel{?}{=} 0$ then go to step 1
      \item Return the signature $(r, s)$
    \end{enumerate}
  \item \textbf{Verify}: Verifies a signature $(r, s)$ of the message $m$ with a public key $Q$
    \begin{enumerate}
      \item Verify that $r \in \Z_q$ and $s \in \Z_q$. Else ouput $0$.
      \item Compute $e = H(m)$
      \item Compute $w = s^{-1}modq$
      \item Compute $u_1 = (ew)modq$ and $u_2 = (rw)modq$
      \item Compute $X = u_1P + u_2Q$
      \item If $X \stackrel{?}{=} \infty$ output $0$
      \item Take $x_1$ cordinate of $X$ and compute $v = x_1modq$
      \item If $v \stackrel{?}{=} r$ then output $1$ else $0$.
    \end{enumerate}
\end{itemize}

Blockchain uses elliptic curves for key pair generation and transaction signing (ECDSA). Bitcoin and Ethereum use a specific elliptic curve for ECDSA~\cite{ecdsa} whose parameters are defined in the secp256k1 standard~\cite{secp}.

\section{Homomorphic Encryption}
\label{preliminaries:homo}

\textit{Homomorphic encryption} allows to perform specific types of computation on encrypted data. Computations performed over a ciphertext return encrypted results. When the results are decrypted they match the results of the operations as if they had been performed on the plaintext. An encryption scheme is called homomorphic when it has the homomorphic property. In particular, if for all $m_1, m_2 \in \calm$ and $k \in \calk$ (secret key or public key):

\begin{equation*}
  Enc_k(m_1) \otimes Enc_k(m_2) = Enc_k(m_1 \oplus m_2)
\end{equation*}

then the encryption scheme is homomorphic.

Homomorphic encryption schemes are by nature \textit{malleable} and have weaker security properties than non-homomorphic schemes. Various known encryption schemes are homomorphic such as the unpadded RSA and El Gamal.

\section[Zero Knowledge Proofs]{Zero Knowledge Proofs~\cite{kiagias:crypto}}
\label{zkp}

A \textit{proof of knowledge} is a protocol that enables one party to convince another of the validity of a \textit{statement}.
In a \textit{zero-knowledge proof}~\cite{zkp} this is accomplished without revealing any information beyond the legitimacy of the proof~\cite{kiagias:crypto}.
In other words, one party can prove to another party that a given statement is true, without conveying any information apart from the fact that the statement is indeed true.

Let $\calp$ be a prover and $\calv$ the verifier. $\calp$ must convince $\calv$ that she has some
knowledge of a statement $x$ without explicitly stating what she knows. We call this knowledge a \textit{witness} $w$.
Both parties are aware of a predicate $R$ that will attest to $w$ being a valid witness to $x$~\cite{kiagias:crypto}. In general,

\begin{itemize}
  \item The predicate $R$ is assumed to be polynomial-time computable.
  \item The prover $\calp$ has $R,x$, and $w$ such that $R(x,w) = 1$. She wishes to prove possesion of $w$ by producing a proof of knowledge $\pi$.
  \item The verifier $\calv$ has $R,x$, and $\pi$.
  \item Given $R$ it is hard to find a corresponding $w$ such as $R(x,w) = 1$
  \item The prover $\calp$ is unwilling to reveal $w$; otherwise the solution is trivial.
  \item The verifier $\calv$ can efficiently check the validity of $\pi$.
\end{itemize}

\subsection{Examples}

\subsubsection{The strange cave of Ali Baba}
\label{zkp:examples}

Let's bring in all cryptographers' old friends, Alice and Bob, and let them play the following game: at the bottom of the cave~\cite{Quisquater:1989:EZP:118209.118269} of figure~\ref{fig:zkp:alibaba} there is a magic door that
can only open with a secret password. The cave has one entrance on one side and a magic door blocking the entrance on the opposite side. Bob knows the secret password and he wants to prove that to Alice without revealing the password.
Bob proposes the following game to prove that he can open the magic door: Alice has to wait outside of the cave, while Bob enters the cave and
takes either the left or the right path. Alice cannot see which path Bob is taking. Then, Alice enters; standing at the entrance of the cave, she calls
Bob to come out from either the left or the right passage. Bob does so, using the secret password if necessary.

If Bob does not know the secret password he has $1/2$ change of guessing correctly as Alice chooses at random which path Bob is taking. If this process is repeated $k$ times the probability of Bob convincing Alice that he knows the secret password without actually knowing is exponentially reduced -- at most $1/2^{k}$.

\subsubsection{The colour-blind friend}

Now, suppose that Bob is color-blind~\cite{zkp:colour_blind} and Alice keeps two balls of the same size in her hands, one red and one green.
To Bob they seem identical and he is not sure which one is which. Alice wants to prove him that indeed they are of different colour,
without revealing which one is red and which is green. To prove her knowledge, she tells Bob to hold the two balls, one on each hand. Alice can see
at this point which ball is in which hand. Next, he can either switch hands behind his back or leave them be. Finally, he reveals them. Alice can say with certainty whether he switched hands or not. Have the balls had the same color, they would have been indistinguishable. There would have been no way Alice could guess the right answer with probability higher than $1/2$. If they repeat this $k$ times the probability that Alice succeeds when the balls are identical is at most $1/2^{k}$.

\begin{figure}[t!]
  \centering
  \begin{subfigure}[t]{0.30\textwidth}
    \centering
    \resizebox{\linewidth}{!}{
      \begin{tikzpicture}[scale=1]
        % Cave %
        \draw(0,5) -- (2,5) -- (2,8) -- (10,8) -- (10,4);
        \draw(0,4) --(2,4) -- (2,1) -- (10,1) -- (10, 4);
        \draw(9,4.5) -- (10,4.5);
        \draw(3,5) -- (3,7) -- (9,7) -- (9,5);
        \draw(3,5) -- (3,2) -- (9,2) -- (9,5);
        % Actors %
        \draw[fill] (1,5.6) circle [radius=0.1];
        \node [below] (alice) at (1,5.5) {Alice};
        \draw[fill] (2.5,4.6) circle [radius=0.1];
        \node [below] (bob) at (2.5,4.5) {Bob};
        % Arrows %
        \draw [dashed, ->] (2.5,4.6) -- (2.5,6);
        \draw [dashed, ->] (2.5,3.9) -- (2.5,2);

      \end{tikzpicture}
    }
    \caption{Alice stands outside and Bob choose randomly a path, left or right}
    \label{fig:zkp:alibaba:a}
  \end{subfigure}
  \begin{subfigure}[t]{0.30\textwidth}
    \centering
    \resizebox{\linewidth}{!}{
      \begin{tikzpicture}[scale=1]
        % Cave %
        \draw(0,5) -- (2,5) -- (2,8) -- (10,8) -- (10,4);
        \draw(0,4) --(2,4) -- (2,1) -- (10,1) -- (10, 4);
        \draw(9,4.5) -- (10,4.5);
        \draw(3,5) -- (3,7) -- (9,7) -- (9,5);
        \draw(3,5) -- (3,2) -- (9,2) -- (9,5);
        % Actors %
        \draw[fill] (2.5,4.6) circle [radius=0.1];
        \node [below] (alice) at (2.5,4.5) {Alice};
        \draw[fill] (9.5,4.3) circle [radius=0.1];
        \node [below] (bob) at (9.5,4.2) {Bob};
        % Speech Bubble %
        \node[overlay,draw,cloud callout,callout relative pointer={(0.2cm,-0.7cm)},%
        aspect=2.5,fill=white!90] at ($(alice)+(-0.5cm,2.3cm)$) {Left};

      \end{tikzpicture}
    }
    \caption{Alice calls to Bob, asking him to come out either the left or the right passage}
    \label{fig:zkp:alibaba:b}
  \end{subfigure}
  \begin{subfigure}[t]{0.30\textwidth}
    \centering
    \resizebox{\linewidth}{!}{
      \begin{tikzpicture}[scale=1]
        % Cave %
        \draw(0,5) -- (2,5) -- (2,8) -- (10,8) -- (10,4);
        \draw(0,4) --(2,4) -- (2,1) -- (10,1) -- (10, 4);
        \draw(9,4.5) -- (9.5,4.5);
        \draw(3,5) -- (3,7) -- (9,7) -- (9,5);
        \draw(3,5) -- (3,2) -- (9,2) -- (9,5);
        % Actors %
        \draw[fill] (2.5,4.6) circle [radius=0.1];
        \node [below] (alice) at (2.5,4.5) {Alice};
        \draw[fill] (2.5,7.8) circle [radius=0.1];
        \node [below] (bob) at (2.5,7.7) {Bob};
        % Speech Bubble %
        \node[overlay,draw,cloud callout,callout relative pointer={(0.2cm,-0.7cm)},%
        aspect=2.5,fill=white!90] at ($(alice)+(-0.5cm,2.3cm)$) {OK};

      \end{tikzpicture}
    }
    \caption{Bob complies appearing at the exit Alices names}
    \label{fig:zkp:alibaba:c}
  \end{subfigure}
  \caption{Ali Baba Cave}
  \label{fig:zkp:alibaba}
\end{figure}

\subsection[Formal Definition]{Formal Definition~\cite{kiagias:crypto}}
\label{zkp:definition}

Let $<\calp, \calv>$ be a pair of interactive programs. Define $\text{out}^{\calp}_{\calp, \calv}(x,w,z)$
to be the output of $\calp$ when both $\calp$ and $\calv$ are executed with the public input $x$ and private
inputs $w$ and $z$ ($\calp$ determines $w$ and $\calv$ choose $z$); $\text{out}^{\calv}_{\calp, \calv}(x,w,z)$
is similar defined for $\calv$. The PPT interactive protocol $<\calp, \calv>$ is a \textit{zero-knowledge proof}
for a language $L \in NP$ with knowledge error $k$ and zero-knowledge distance $\e$ if the following
properties hold~\cite{kiagias:crypto}.

\begin{enumerate}
  \item \textbf{Completeness:} If $x \in L$ and $R(x,w) = 1$ for some witness $w$, then $\text{out}^{\calv}_{\calp, \calv}(x,w,z)$ = 1
    for all string $z$ with overwhelming probability in $v$.
  \item \textbf{Soundness:} For any polynomial-time program $\calp^{*}$ define for arbitrary $x,w,z,$
    \begin{equation*}
      \pi_{x,w,z} = \Prob[\text{out}^{\calv}_{\calp^{*}, \calv}(x,w,z) = 1].
    \end{equation*}
    A protocol $<\calp, \calv>$ satisfies soundness if there are non-negligible functions $s(v), q(v)$ such for all $\calp^{*}$ here exists a probabilistic
    Turing machine (PTM) program $K$, called a knowledge extractor with the following property. Suppose that

    \begin{equation*}
      \widetilde{\pi} = \Prob[K(x,w,z) = w^{'} : R(x, x^{'}) = 1].
    \end{equation*}
    Then it holds that $\pi_{x,w,z} \geq s(|x|)$ implies that $\widetilde{\pi}_{x,w,z} \geq q(\abs{x})$.

  \item \textbf{(Statistical) Zero-knowledge:} For each polynomial-time program $\calv^{*}$, there is a PTM program $S$, called the \textit{simulator}, such that for all
    $x,w$ with $R(x,w) = 1$, the random variables $S(x,z)$ and $\text{out}^{\calv^{*}}_{\calp, \calv^{*}}(x,w,z)$ are statistically indistinguishable for all strings $z$:
    \begin{equation*}
      \forall \cala \abs[\Big]{\Prob[\cala(S(x,z) = 1)] - \Prob[\cala(\text{out}^{\calv^{*}}_{\calp, \calv^{*}}(x,w,z)) = 1]} < \e.
    \end{equation*}
\end{enumerate}

Completeness is very similar to correctness. Assuming both the prover and verifier follow the protocol faithfully, completeness guarantees that the
protocol will succeed with a sufficiently high probability.
Soundness ensures that if the statement is false, no cheating prover can convince the honest verifier that it is true, except with some small probability.
Intuitively, statistical zero-knowledge is a property that prohibits a verifier from extracting information from an honest prover. A weaker version of zero-knowledge is \textit{honest-verifier zero-knowledge} (HVZK) where it is assumed that the verifier executes the protocol faithfully, but makes additional computations.

\subsection{Verifiable Computation (VC)}
\label{zkp:vc}

In devices such as mobiles or IoT devices where the computational power is often limited, the need to outsource computation to one or more powerful workers on the cloud emerges. Yet, confidence is required for the working entity to assure computation is done properly. The client should be able to verify the correctness of the output. This way, the client is protected from malicious or malfunctioning workers, and the legitimate worker is no longer accountable for the computation~\cite{pinocchio-nearly-practical-verifiable-computation}. This scheme is called \textit{public verifiable computation} (VC)~\cite{pinocchio-nearly-practical-verifiable-computation}.

In a public verifiable computation scheme the client outsources the evaluation of a function $F$ on input $u$ -- for example, a query. The client then can verify the correctness of the computation of $F(u)$ doing less work than the initial computation of $F(u)$. The outsource function $F$ can take two inputs $u$ and $w$, where $w$ is the worker's private input -- for example, a data set. In this case, the scheme is a \textit{Zero-Knowledge Verifiable Computation} (or non-interactive zero knowledge (NIZK) proof~\cite{Blum:1991:NZ:123137.123145}) if the client learns nothing about the worker's input except the computation's output~\cite{pinocchio-nearly-practical-verifiable-computation}.

Such schemes are not interactive, which means that no interaction is necessary between prover and verifier (worker and client), and a \textit{common reference string} (CRS) shared between them is enough to achieve computational zero-knowledge~\cite{Blum:1991:NZ:123137.123145}.

Formally, as defined by Parno et. al~\cite{pinocchio-nearly-practical-verifiable-computation}, a public Zero-Knowledge verifiable computation scheme $\calv \calc$ consists of a set of three polynomial-time algorithms:

\begin{itemize}
  \item $(EK_F, VK_F) \leftarrow \text{KeyGen}(F, 1^{\lambda})$: The \textbf{randomized key generation algorithm}. It takes as input the outsourced function $F$ and a security parameter ${\lambda}$; it outputs a public evaluation key $EK_F$ and a public verification key $VK_F$.
  \item $(y, \pi_y) \leftarrow \text{Compute}(EK_F, u)$: The \textbf{deterministic worker algorithm}. It takes as input the public evaluation key $EK_F$ and a public input $u$; it outputs $y \leftarrow F(u, w)$, where $w$ is an auxiliary private input, and a proof $\pi$ of $y$'s correctness.
  \item $\{0, 1\} \leftarrow \text{Verify}(VK_F, u, y, \pi_y)$:  The \textbf{deterministic verification algorithm}. It takes as input the public verification key $VK_F$, the public input $u$, the output $y$ and the proof $\pi_y$; It outputs $1$ if $F(u) = y$ and $0$ otherwise.
\end{itemize}

\subsection{zk-SNARKs}
\label{zkp:snarks}

A \textit{Non-interactive Zero-Knowledge proof} (NIKZ)~\cite{Blum:1991:NZ:123137.123145} is a zero-knowledge proof where sharing a common reference string (CRS) between the prover and the verifier ahead of time is enough to implement zero knowledge protocols without the need for interaction between the participants of the protocol. The \textit{zkSNARKs} protocols are non-interactive zero-knowledge proof protocols which have some extra properties regarding the size of proof and the verification time.

The acronym zkSNARK stands for \textit{`Zero-Knowledge Succinct Non-Interactive Argument of Knowledge'} in which each individual part -- informally defined -- have the following meaning~\cite{zksnarks_nutshell, zcash, 184425, Bitansky:2012:ECR:2090236.2090263, zksnark_basics}:

\begin{itemize}
  \item \textbf{Zero-Knowledge}: The verifier learns nothing but the validity of the computation
  \item \textbf{Succinct}: The proofs are sort and easy to verify in comparison to the actual computation (constant size, and polynomial verifiable in the size of the proof).
  \item \textbf{Non-Interactive}: There is no or little interaction in one step. Anyone can verify the proof, no need for new interaction (publicly verifiable).
  \item \textbf{ARgument}: Soundness (§~\ref{zkp:definition}) holds only against computationally bounded provers.
  \item \textbf{of Knowledge}: If the verifier accepts a proof output by a computationally bounded prover, then the prover has a witness for the given instance.
\end{itemize}

The first zkSNARKs constructions where inspired by the \textit{PCP} theorem allowing faster and shorter proofs~\cite{zksnark_basics}. In this section an analysis of the zk-SNARK model proposed by Gennaro et al~\cite{ggpr} and the Pinnochio protocol proposed by Parno et al~\cite{pinocchio-nearly-practical-verifiable-computation} is attempted, without getting into rigorous mathematical proofs, security assumptions or implementations. The purpose of this chapter is to provide a high level understanding of zkSNARKs and their core mechanisms.

\subsection{Main idea}
\label{zkp:snarks:main_idea}

In order to be able to construct a zkSNARKs for a computation problem it has to be encoded in a specific form, an equivalent to the original problem, from which zkSNARKs can derive. This form is called \textit{Quadratic Arithmetic Program} (QAP).

At a high level, zkSNARKs consists of four basic steps (Figure ~\ref{fig:zkp:zksnark_flow}):

\begin{enumerate}
  \item Computation to Arithmetic circuit~\cite{pinocchio-nearly-practical-verifiable-computation}
  \item Arithmetic circuit to Rank 1 Constraint System (R1CS)~\cite{ggpr}
  \item R1CS to Quadratic Span Program (QAP)~\cite{ggpr}
  \item QAP to zkSNARK~\cite{pinocchio-nearly-practical-verifiable-computation}
\end{enumerate}

\begin{figure}[ht!]
  \center
  \begin{tikzpicture}[
    flow/.style={rectangle, minimum width=2cm, minimum height=1cm, text centered, draw=black,font=\footnotesize},
    scale=0.8
  ]
    \node[flow] (comp) at (0, 0) {Computation};
    \node[flow] (alg) at (4, 0) {Arithmetic Circuit};
    \node[flow] (r1cs) at (8, 0) {R1CS};
    \node[flow] (qap) at (12, 0) {QAP};
    \node[flow] (zk) at (16, 0) {zkSNARK};

    \draw[->] (comp) -- (alg);
    \draw[->] (alg) -- (r1cs);
    \draw[->] (r1cs) -- (qap);
    \draw[->] (qap) -- (zk);

  \end{tikzpicture}
  \caption{Steps of zk-SNARK}
  \label{fig:zkp:zksnark_flow}
\end{figure}

\subsubsection{Arithmetic circuits}
\label{zkp:snarks:circuits}

An \textit{arithmetic circuit} $C$ over a finite field $\F_p$ is a circuit that contains
only addition and multiplication gates. It takes as inputs elements in $\F_p$ and its gates output elements in $\F_p$~\cite{184425, zcash}. The outputs are determined by the inputs which pass through the gates where their values are changed accordingly. Any program  can be reduced to  an arithmetic circuit~\cite{pankova_succinct_2013, 10.1007/978-3-642-40084-1_6} and normally the circuit is associated to the function it computes -- the outsource function upon which the prover works.

A legal or a \textit{valid assignment} for an arithmetic circuit $C$ is a tuple $(c_1, c_2, \dots, c_n) \in \F_p$ such that $C(c_1, c_2, \dots, c_k) = (c_{k+1}, c_2, \dots, c_n)$ where $k$ is the number of all input and $n - k$ the number of all outputs of the circuit. Given a circuit evaluation, the task of the prover is to convince the verifier that evaluations of intermediate gates exist, so that the circuit indeed produces such an output with such an input~\cite{pankova_succinct_2013}. For example, if Alice wants to prove to Bob that she knows $c_1, c_2, c_3 \in \F_p$, such that $(c_{1}c_{2})(c_1 + c_3) = 7$, first she has to encode the computation to an arithmetic circuit $C$ (the presentation of $C$ is shown in Figure~\ref{fig:zkp:circuit}). Then she wants to prove that she knows a valid assignment $(c_1, c_2, c_3, c_4, c_5)$, where $c_4 = c_{1}c_{2}$ and $c_5 = c_{4}(c_1 + c_3)$, such that $c_5 = 7$.

\begin{figure}[ht!]
  \center
  \begin{tikzpicture}[
        gate/.style={
        circle,
        minimum size=1cm,
        draw
      },
      node distance=2cm
    ]

    \node[gate] (c1) at (0, 0) {$c_1$};
    \node[gate] (c2) at (2, 0) {$c_2$};
    \node[gate] (c_3) at (4, 0) {$c_3$};

    \node[gate] (g1) at (1, 2) {$*$};
    \node[gate] (_g) at (3, 2) {$+$};

    \node[gate] (g2) at (2, 4) {$*$};

    \draw[->] (c1) -- (g1);
    \draw[->] (c1) -- (_g);
    \draw[->] (c2) -- (g1);

    \draw[->] (c_3) -- (_g);

    \draw[->] (g1) -- (g2);
    \draw[->] (_g) -- (g2);

    \draw[->] (g2) -- ++(0, 2);

  \end{tikzpicture}
  \caption{A simple arithmetic circuit}
  \label{fig:zkp:circuit}
\end{figure}

\subsubsection[Quadratic Arithmetic Program (QAP)]{Quadratic Arithmetic Program (QAP)~\cite{zksnark_basics, zcash_snarks}}
\label{zkp:snarks:qap}

Geranno et. al~\cite{ggpr} showed how to efficiently encode computations to quadratic programs called Quadratic Arithmetic Programs (QAP), to obtain zk-SNARKs. QAPs play an important role as they enable the prover to construct the proof $\pi$ where she claims that she knows a valid assignment of a circuit $C$.

A  QAP $Q(C) = (L, R, O, T)$ for a given circuit $C$ is a set of three polynomials

\begin{align*}
  L = \sum_{i=1}^{m}c_{i}L_{i} && R = \sum_{i=1}^{m}c_{i}R_{i} && O = \sum_{i=1}^{m}c_{i}O_{i} && (m \geq n)
\end{align*}

and a target polynomial $T$ such that $T$ divides the polynomial:

\begin{equation*}
  P = LR - O
\end{equation*}

if and only if $(c_1, c_2, \dots, c_n)$ is a valid assignment for $C$. The prover constructs the polynomial for its proof $\pi$ and the verifier checks the divisibility of $P$ by $T$. Identically, $P = TH$ for some polynomial $H$.

To translate the $C$ into a QAP the wires and gates must be labeled in a specific way:

\begin{itemize}
  \item Each multiplication gate has exactly two input wires: a left and a right wire
  \item Each multiplication gate has a unique label
  \item Addition gates are not labeled
  \item Outgoing wires to more than one gate are labeled as one wire
  \item Outgoing wires from an addition gate to a multiplication gate are not labeled; the inputs of an addition gate go directly to the multiplication gate
\end{itemize}

A label assignment of the circuit of Figure~\ref{fig:zkp:circuit} is shown in Figure~\ref{fig:zkp:circuit_label}.

\begin{figure}[ht!]
  \center
  \begin{tikzpicture}[
        gate/.style={
        circle,
        minimum size=1cm,
        draw
      },
      node distance=2cm
    ]

    \node[gate] (c1) at (0, 0) {$c_1$};
    \node[gate] (c2) at (2, 0) {$c_2$};
    \node[gate] (c_3) at (4, 0) {$c_3$};

    \node[gate, label={left:$g_1$}] (g1) at (1, 2) {$*$};
    \node[gate] (_g) at (3, 2) {$+$};

    \node[gate, label={right:$g_2$}] (g2) at (2, 4) {$*$};

    \draw[->] (c1) -- (g1) node[midway,left] {$w_1$};
    \draw[->] (c1) -- (_g);
    \draw[->] (c2) -- (g1) node[midway,right] {$w_2$};

    \draw[->] (c_3) -- (_g) node[midway,right] {$w_3$};

    \draw[->] (g1) -- (g2) node[midway,left] {$w_4$};
    \draw[->] (_g) -- (g2);

    \draw[->] (g2) -- ++(0, 2) node[midway,left] {$w_5$};

  \end{tikzpicture}
  \caption{Circuit label assignment}
  \label{fig:zkp:circuit_label}
\end{figure}

The circuit is ready to be transformed into a QAP. Let $M$ be the set that contains the indexes of the multiplication gates and $W$ the set that contains the input and output wires. The points in $M$ are called target points. For each gate $g \in M$ we construct a set of left, right, and output polynomials as follows: for each wire a polynomial is constructed in such way that it evaluates at zero on each target point except those that correspond to the multiplication gate.

\textit{QAP construction of circuit of Figure~\ref{fig:zkp:circuit_label}}: Gate $g_1$, with target point $1$, has $w_1$ as left wire, $w_2$ as right wire and $w_4$ as output label. As the polynomial on point $1$ that corresponds to $g_1$ evaluates to $1$ and on point $2$ corresponding to $g_2$ evaluates to $0$, we construct $L_1 = R_2 = O_4 = 2 - x$. Similar, for gate $g_2$ $L_4 = R_1 = R_3 = O_5 = x - 1$. Note that the wires $w_2$ and $w_3$ are both right inputs of $g_2$.

The wire polynomials:

\begin{align*}
  L_1 = (2 - x) && L_2 = 0 && L_3 = 0 && L_4 = (x - 1) && L_5 = 0
\end{align*}
\begin{align*}
  R_1 = (x - 1) && R_2 = (2 - x) && R_3 = (x - 1) && R_4 = 0 && R_5 = 0
\end{align*}
\begin{align*}
  O_1 = 0 && O_2 = 0 && O_3 = 0 && O_4 = (2 - x) && O_5 = (x - 1)
\end{align*}

The total left, right and output polynomials:

\begin{align*}
  L &= \sum_{i=1}^{5}c_{i}L_{i} & R &= \sum_{i=1}^{5}c_{i}R_{i} & O &= \sum_{i=1}^{5}c_{i}O_{i} \\
    &= c_1L_1 + c_4L_4 & &= c_1R_1 + c_2R_2 + c_3R_3 & &= c_4O_4 + c_5O_5 \\
    &= c_1(2 - x) + c_4(x - 1) & &= c_1(x - 1) + c_2(2 - x) + c_3(x - 1) & &= c_4(2 - x) + c_5(x - 1)
\end{align*}

If we evaluate these polynomials at target points $1$ and $2$ we get:

\begin{align*}
  P(1) &= L(1)R(1) - O(1) & P(2) &= L(2)R(2) - O(2) \\
       &= c_1c_2 - c_4 & &=c_4(c_1 + c_3) - c_5
\end{align*}

Hence, $T(x) = (x - 1)(x - 2)$ divides $P(x)$ if and only if $1, 2$ are roots of $P(x)$. Identically, the tuple $(c_1, c_2, \dots, c_5)$ is a valid assignment for $C$.


\subsection{Summary of the important contributions}
\label{sec:summ-import-results}

%% Theoretical part: generic formulation
In this paper, the characteristic structure of the solution of hyperbolic problems in elastic-plastic solids in two space dimensions has been highlighted.
First, a thermodynamically-consistent formulation leading to the writing of a hyperbolic system involving the fourth-order elastic-plastic stiffness tensor as been proposed.
The aforementioned tensor can be easily specialized to plane stress and plane strain problems in such a way that the quasi-linear form derived provides a generic framework for the study of all mechanical problems in two space dimensions.

%% Characteristic analysis
Second, the characteristic analysis of the hyperbolic plane strain and plane stress problems has been carried out.
As already emphasized for simpler two-dimensional problems in prior works \cite{Rakhmatulin,CRISTESCU19591605} the solutions involve slow and fast simple waves.
The characteristic equations governing the evolution of the system inside the simple waves have then been derived as a set of ODEs by applying the method of characteristics.

%% Mathematical properties of the loading paths
Third, some mathematical properties of these characteristic equations have been highlighted for plane strain and plane stress, despite the complexity of the equations.
As an interesting result of this work, it has been shown that the loading paths followed inside slow and fast waves are perpendicular in the stress space.
Although this feature has been already emphasized in \cite{Clifton} for a combined longitudinal and torsional loading, the property is in fact due to the symmetry of the acoustic tensor and is therefore valid for all two-dimensional problems.

%% Numerical results
At last, to overcome the mathematical complexity of the characteristic equations, numerical investigations have been proposed.
The loading paths depicted in the stress space or in the deviatoric plane then enable the identification of symmetry properties that are not proofed mathematically.
Moreover, the integral curves holding inside fast waves are restricted to the initial yield surface for both plane stress and plane strain situations.
In the former case, the paths end as soon as a direction of pure shear is reached in the deviatoric plane, whereas in the latter one, the paths appears to be radial once  a direction of pure tension/compression is achieved.
On the other hand, the loading through the simple waves exhibit rough changes regardless of the kinematic considered for low hardening moduli (\textit{i.e. $C=\mathcal{O}(10^8)$}).
It has moreover been shown numerically that this inflection corresponds, for plane stress, to the reaching of the maximum shear stress on the current yield surface for a given longitudinal stress.
For plane strain, a similar response is also seen but before the \textit{maximum-shear-stress} condition is achieved.
% Similar conclusions can be drawn for plane strain.
Nevertheless, increasing the hardening modulus leads to loading paths whose direction changes before the \textit{maximum-shear-stress} condition is achieved for plane stress, and which reach a direction of pure shear at the same time as the maximum shear stress.

\subsection{Concluding remarks}
\label{sec:concludingRemarks}

%% Perspectives
The results of the present paper allow a better understanding of the physical response of linearly hardening elastic-plastic solids to dynamic loadings.
However, the singularities that have been highlighted numerically still need to be identified mathematically.
%It would also be interesting to consider different hardenings (\textit{i.e. kinematic, non-linear etc.}).
Notice that kinematic hardening should yield identical results for the monotonic loadings considered here, but would greatly influence the response for unloading or reverse plastic loading.
  These waves must also be the object of an analysis for two-dimensional problems in order to construct the solution of the Riemann problem.
As a more long-term perspective, the elementary loading paths studied here could be used in order to enrich numerical methods based on the use of Riemann solvers.
In fact, following the idea of \textsc{Lin} and \textsc{Ballman} \cite{Lin_et_Ballman}, a numerical procedure that accounts for both elastic and plastic characteristics can be developed in order to improve the tracking of waves in elastic-plastic solids.
% Nonetheless, the hyperbolic problems in elastoplastic media may involve not only simple waves but also shocks so that the effects of the latter must be investigated as well.

%%% Local Variables:
%%% mode: latex
%%% TeX-master: "manuscript"
%%% End:


\section{Introduction}

\subsection{Longest Common Subsequence}
\begin{frame}
    \frametitle{Longest Common Subsequence}
    \begin{itemize}
        \setlength\itemsep{1em}
        \item
            The {\em longest common subsequence} (LCS) is a famous
            problem in string processing.
        \item
            For example,
            \begin{itemize}
                \setlength\itemsep{1em}
                \item
                    Revision control systems like SVN and Git.
                \item
                    The sequence alignment in bioinformatics.
            \end{itemize}
    \end{itemize}
\end{frame}

\begin{frame}
    \frametitle{Definition of Longest Common Subsequence}
    %\setlength\itemsep{1em}
    Given two strings $A = a_1 \; a_2 \cdots a_n$ and $B = b_1 \; b_2
    \cdots b_m$.
    \begin{definition}
        Subsequence $S = s_1 \; s_2 \cdots s_r$ of $A$, we define a
        \emph{correspondence sequence} of $A$ and $S$, $C(A, S) = c_1 \;
        c_2 \cdots c_r$ to be a strictly increasing sequence of integers
        such that $s_i = a_{c_i}$ $1 \le i \le r$
	\end{definition}
	\begin{definition}
        A common subsequence $S$ of $A$ and $B$, if there exists
        correspondence sequence $C(A, S)$ and $C(B, S)$.
	\end{definition}
\end{frame}

\subsection{Variable Gapped LCS}
\begin{frame}
    \frametitle{Definition of Variable Gapped LCS}
    Given two strings $A$, $B$, and two gap values $G_{A}$, $G_{B}$
    \begin{definition}
        It is a LCS and satisfy the constraints as follows:
        \begin{align*}
            C(A, S)[i] - C(A, S)[i-1] \le G_{A}(c_i) \\
            C(B, S)[i] - C(B, S)[i-1] \le G_{B}(c_i)
        \end{align*}
    \end{definition}
\end{frame}

\begin{frame}
    \frametitle{An Example for Variable Gapped LCS}
    \begin{figure}[!thb]
      \centering
      \includegraphics[width=0.5\linewidth]{\GraphicPath/fig-VGLCSex.pdf}
      \includegraphics[width=0.5\linewidth]{\GraphicPath/fig-VGLCSex2.pdf}
      \caption{A VGLCS example} \label{fig:VGLCSex}
    \end{figure}
\end{frame}

\begin{frame}
    \frametitle{Efficient Serial Algorithm}
    \begin{itemize}
        \setlength\itemsep{1em}
        \item
            Peng gives a $O(n m \alpha(n))$ algorithm \footnote{$\alpha$
            is the inverse of Ackermann's function.}, and
        \item
            An asymptotically better $O(n m)$ algorithm.
        \item
            Both of algorithms uses disjoint-set data structure.
    \end{itemize}
\end{frame}

\subsection{Contribution}
\begin{frame}
    \frametitle{Contribution}
    \begin{itemize}
        \setlength\itemsep{1em}
        \item
            In this paper, we propose our $O(nm)$ algorithm which is {\em
            easy} to implement and runs {\em efficiently} in a {\em
            parallel} environment.
        \item
            Our parallel algorithm uses a more powerful {\em sparse table}
            instead of the disjoint set.
        \item
            For sparse table algorithm, we propose the {\em parallel}
            building LCA table algorithm and its {\em dynamic} Catalan
            index computing algorithm.
    \end{itemize}
\end{frame}


\chapter{Classical Mechanics}

Classical Mechanics describes everything in the world as if they have an exact position $\textbf{x}$ and velocity $\dot{\textbf{x}}$, which in principle could be known simultaneously. There happens to be real physical limit as to how well we can know both of these quantities at the same time (from the Heisenberg Uncertainty principle), but that limit is so small that for everyday objects, Classical Mechanics works just fine.

\section{Lagrangian Formalism}
When dealing with conservative forces, there turns out to be a nice way to figure out all of Newton's laws without having to draw out all of the free body diagrams. In fact, when this method was first proposed, Lagrange bragged that he had \emph{no pictures or diagrams} in his book\cite{lagrange}. The Lagrangian is defined as
\begin{align}
L\equiv T-V
\end{align}
Where $T$ is the kinetic energy and $U$ is the potential energy. For each coordinate $q_i$ (usually things like $x,y,z$), we get an equation
\begin{align}
\boxed{\frac{d}{dt}\Big(\frac{\partial L}{\partial \dot{q}_i}\Big) = \frac{\partial L}{\partial q_i} }
\end{align}
These are called the \textbf{Euler-Lagrange equations}. Basically all Classical Mechanics problems boil down to finding a useful set of coordinates to describe your system, then writing out $T$ and $U$ in terms of them, then solving a system of equations given by these.

     An easy way to find the Lagrangian for any system is to identify the coordinate of each of its masses in cartesian coordinates, then rewriting it in terms of coordinates that best suit the problem.
     \begin{align}
        x_1(q_1,q_2,...)\\
        y_1(q_1,q_2,...)
     \end{align}

     We can then just take the time derivative of each of them to solve for the $\dot{q}$ term.

\subsection{Action}
\cite{dhoker_cm}The action is a scalar quantity defined by
\begin{align}
S[q] = \int_{t_1}^{t_2} dt L (q_1,...q_N, \dot{q}_1, ..., \dot{q}_N, t)
\end{align}
The $[q]$ means that it takes as an argument a \emph{function} not just a variable. These types of mathematical objects are called functionals, and take entire trajectories as their argument instead of just one point. In order to find the action, we would have to know exactly the path that $q_1, q_2, q_3, ...$ had all taken, then we integrate the Lagrangian, which is a function of those variables from $t_1$ to $t_2$.

The importance of the action is that for \emph{any} real physical system, the "path" which all of the coordinates $\textbf{q} = (q_1,q_2,q_3,...)$ follow will be one for which the action will always be at an extremum or saddle point.
\begin{align}
    \frac{\partial S}{\partial \textbf{q}(t)} = 0
\end{align}
This weird fact is called Hamilton's Principle. Apparently the extremization of the action is a direct consequence of the second law of thermodynamics, that entropy is always increasing.\cite{stackexchange_action} Knowing that the integral of the Lagrangian extremizes the Action, we can actually derive Lagrange's equations of motion using variational calculus.

To do so, we consider two possible Lagrangians, one is a function of all of the coordinates that truly minimize the action, $q_1, q_2, q_3, ... $ etc, and one is a set that is infinitesimally close to them $q_1', q_2', q_3', ...$ related by
\begin{align}
    q_i'(t) = q_i(t) + \epsilon s(t)
\end{align}
The differences in the Lagrangians of each case is
\begin{align}
    \delta L(q,\dot{q},t) &= L(q',\dot{q}',t) - L(q,\dot{q},t)\\
\end{align}
Since the difference in the Lagrangian will be small (from the small change in $q$) we can look at the first order in the Taylor expansion of the difference, which is
\begin{align}
    \delta L(q,\dot{q},t) &= \frac{\partial L}{\partial q} \delta q + \frac{\partial L}{\partial \dot{q}}\delta \dot{q}\\
    &\approx \epsilon\Big( \frac{\partial L}{\partial q} s + \frac{\partial L}{\partial \dot{q}}\dot{s}\Big)
\end{align}
Now looking at the change in the action, we have
\begin{align}
    \delta S[q] = \epsilon\int_{t_1}^{t_2} dt \Big( \frac{\partial L}{\partial q} s + \frac{\partial L}{\partial \dot{q}}\dot{s}\Big)
\end{align}
We can integrate the $\dot{s}$ term by parts and find
\begin{align}
    \delta S[q] = \epsilon\int_{t_1}^{t_2} dt \Big( \frac{\partial L}{\partial q}  - \frac{d}{dt}\frac{\partial L}{\partial \dot{q}}\Big)s(t)
\end{align}
If we want the difference in the action between the two paths to be zero (giving us our original path back) and know that $s(t)$ is an entirely arbitrary function, we have to have the integrand be zero
\begin{align}
    \frac{\partial L}{\partial q}  - \frac{d}{dt}\frac{\partial L}{\partial \dot{q}} = 0
\end{align}
These are of course the Euler-Lagrange equations of motion for a system.

%TODO- Also do a simple example where you get back Newton's laws in an easy case

%Equivalent Lagrangians

%$$L(q') = L(q) + \frac{d}{dt}\Lambda(q,t)$$

%For finding equivalent Lagrangians, you will write the new $q'$ as

%$$q'_i = q_i + \epsilon \delta q_i$$

%Using the above equation, you can find that

%$$\frac{\partial L(q')}{\partial \epsilon}|_{\epsilon = 0} = \sum \frac{\partial L}{\partial q_i}\delta q_i + \frac{\partial L}{\partial \dot{q}_i}\delta \dot{q}_i = \frac{d\Lambda}{dt}$$

\subsection{Holonomic Constraints}
This is essentially when you want to say that a particle must travel along some path, or that the length of a rope is only so long, etc. Basically you can write out the constraint as a formula, lets do the length of a string hanging off a ledge.

\begin{align}
    l = x + z
\end{align}
Which would be if we have the horizontal component of the string given by $x$ and vertical by $z$. Our constraint equation is thus
\begin{align}
    \phi(x,z,t) = 0 = l - x - z
\end{align}
From here, we use Lagrange multipliers (Section \ref{lagrange-mult}) within Lagrange's equations over all our constraints...

$$\frac{d}{dt}\frac{\partial L}{\partial\dot{q}_i} - \frac{\partial L}{\partial q_i} - \sum_\alpha \lambda_\alpha \frac{\partial \phi_\alpha}{\partial q_i} = 0$$

So for each constraint, you have another Lagrange multiplier. To solve for $\lambda_\alpha$ and, and therefore the equations of motion, first look for equations that don't contain the term (i.e. $\partial\phi_\alpha/\partial q_i = 0$), solve those equations, then plug their solution into ones that do, eventually finding them.

You can also solve for one of the coordinates in terms of the other ones in the constraint, and plug it in explicitly to the Lagrangian, then find the E.L. Equations from there.

\subsection{Normal Modes}
The normal modes of a system are when all parts of the system are oscillating with the same frequency. So to solve these, we take the ansatz usually that
\begin{align}
    q_1(t) = Ae^{i\omega t} && q_2(t) = Be^{i\omega t}
\end{align}
Then we can use these in the equations of motion, and solve for the frequencies, usually in a quadratic equation.

\subsection{Equilibrium}

We know that a system is in equilibrium if the forces acting on it are equal to zero. This means that

$$\frac{\partial V}{\partial q_i}|_{q_i=q_i^0} = 0$$

This means that the variable $q_i$ will not be accelerated and is in equilibrium. The equilibrium point can be solved for by calculating this quantity, then solving for what $q_i^0$ must be. We can then find what small oscillations around the equilibrium would be by guessing a solution of the form

\begin{align}
q_i(t) = q_i^0 + \eta_i(t)
\end{align}

From here, we just plug this into the Euler-Lagrange equations for $q_i$, and solve for the equations of motion for $\eta(t)$, which tells us how the system moves for small oscillations around an equilibrium.

\subsection{Noether's Theorem}
The essence of what this theorem says is that for every symmetry we can find in our system, there will be some kind of "conserved quantity" associated with it that does not change with time.
Plug in conserved charges in equations of motion, \emph{not} Lagrangian.
$$Q = \sum\frac{\partial L}{\partial\dot{q}_i}\delta q_i - \Lambda$$

$Q$ is a conserved quantity, i.e. $dQ/dt = 0$
Some nice examples of Noether charges are things like the energy of the system, or the angular momentum.

%TODO Add more here

\subsection{Solving the Equations of Motion}
\begin{enumerate}
    \item Write out the kinetic and potential energies in a nice choice of coordinates.
    \item Find all the Holonomic constraints and plug them in (or do it the other way)
    \item Find EL equations
    \item Find Noether Charges
    \item Plug in Noether charges into EL equations.
\end{enumerate}

\section{Hamiltonian Formalism}
In a way identical to what we do for thermodynamics, we can make a \emph{Legendre transform} of our variables into a new set. We start by defining the canonical momentum as
\begin{align}
p_i \equiv \frac{\partial L}{\partial \dot{q}_i}
\end{align}

$$H = \sum\frac{dL}{d\dot{q_i}}d\dot{q_i} - L$$

\section{Virial Theorem}
Imagine we have some value called $G$ that is defined as
\begin{align}
G = \sum_{k=1}^N \textbf{p}_k\cdot\textbf{r}_k
\end{align}
Where $\textbf{p}_k$ is the momentum of the $k$th particle of $N$, and $\textbf{x}_k$ it's coordinate. It can be shown\cite{goldstein} that this quantity is identical to half the time derivative of the moment of inertia with
\begin{align}
G = \frac{1}{2}\frac{dI}{dt}
\end{align}
The trick to derive the Virial theorem is to take the time derivative of $G$, giving us
\begin{align}
\frac{dG}{dt} &= \sum_{k=1}^N \Big[\textbf{p}_k\cdot\frac{d\textbf{r}_k}{dt} + \frac{d\textbf{p}_k}{dt}\cdot\textbf{r}_k\Big]\\
&= \sum_{k=1}^N \Big[m\frac{d\textbf{r}_k}{dt}\cdot\frac{d\textbf{r}_k}{dt} + \textbf{F}_k\cdot\textbf{r}_k\Big]\\
&= 2T - \sum_{k=1}^N \textbf{F}_k\cdot\textbf{r}_k
\end{align}
The total force on any one particle $\textbf{F}_k$ is given by the sum of all of the individual forces from each of the other particles, or
\begin{align}
\textbf{F}_k = \sum_{j\neq k}^N \textbf{F}_{jk}
\end{align}
This lets us rewrite the second term as
\begin{align}
\sum_{k=1}^N \textbf{F}_k = \sum_{k=1}^N \sum_{j\neq k}^N \textbf{F}_{jk}\cdot\textbf{r}_k = \sum_{k=1}^N \sum_{j\neq k}^N \textbf{F}_{jk}\cdot(\textbf{r}_k - \textbf{r}_j)
\end{align}
Where the last bit is kosher because no particle has a self force or $\textbf{F}_{jj} = 0$. The usefulness of the theorem come when we have a potential between each particle is a power series of the form $V(\textbf{r}_k - \textbf{r}_j)  = \alpha |\textbf{r}_j-\textbf{r}_k|^n$, since
\begin{align}
\textbf{F}_{jk}\cdot(\textbf{r}_k - \textbf{r}_j) = \Big[-\nabla_k V(\textbf{r}_k - \textbf{r}_j) \Big]\cdot(\textbf{r}_k - \textbf{r}_j) = n V(\textbf{r}_k - \textbf{r}_j)
\end{align}
Therefore
\begin{align}
n \sum_{k=1}^N \sum_{j\neq k}^N V(\textbf{r}_k - \textbf{r}_j) = nV
\end{align}
Where $V$ is the total potential energy of the system. Therefore if we look at the average, and have a \emph{stably bound system} we have that
\begin{align}
\Big\langle\frac{dG}{dt}\Big\rangle = 0 = 2\langle T \rangle - n\langle V \rangle
\end{align}
Where $n$ of course is the power of the potential.

%TODO \section{Hamilton-Jacobi Equations}
%Someday...

\section{Special Relativity}
It turns out that both space and time get jumbled together when you move fast enough. Special relativity is able to talk about two frames (i.e. two people) which move at a constant velocity with respect to one another. The theory was developed as a consequence of the strange fact that the speed of light, found in Maxwell's equations, was found to be \emph{completely independent} of whatever frame you are in.

\centerline{\includegraphics[width=0.5\textwidth]{physics/images/relativity}}

With relativity, we always talk about "frames" which are just places that you, as an observer would see things from. Galilean relativity (or "common sense" relativity) says that if you have light of speed $c$ in one frame $F$, which is moving at speed $v$ towards an observer in frame $F'$, the speed of light should be
\begin{align}
    c' = v+ c
\end{align}
If for instance the like was going towards the origin $O$ in frame $F$. This would be \emph{faster} than what Maxwell's equation's say, so something has to give. Einstein fixed this by positing that both \emph{space and time themselves} are changed between frames with different velocities. When you look at something that is moving, it is shrunken in the direction of travel compared to how it sees itself. Additionally the amount of time it takes for an event to take place (ball thrown, clock tick, etc) takes \emph{longer} in the frame that sees the event as moving, than it would in a frame at which the the event takes place at rest.

To illuminate, lets pretend we have a person on earth (frame $F$) and a person on a spaceship (frame $F'$) moving away from the earth in the positive $x$ direction with speed $v$. The earth measures everything with coordinates $(t,x,y,z)$ and the person on the ship measures everything with coordinates $(t',x',y',z')$. Both of these coordinate systems are \emph{completely normal} in their own frames. If they had a ball on earth and measured it's radius as $r$, the ruler with which they measure it on the ship would say it is the same $r$ when the entire ship, ball, ruler system is moving together.

Lets pretend that right when the spaceship passes the earth, they are able to align their coordinate system somehow so everything is zero. The usefulness of special relativity is know how everyone on the ship (in $F'$) sees things after doing some mathematics with all of the things you are capable of measuring in $F$. It turns out that the transformation is given by %\footnote{do someday, classical HW 3}
\begin{align}\label{lorentzcontract}
    t' &= \gamma\Big(t -\frac{vx}{c^2} \Big)\\
    x' &= \gamma(x - vt)\\
    y' &= y\\
    z' &= z
\end{align}
Where
\begin{align}
\gamma =\frac{1}{ \sqrt{1-\frac{v^2}{c^2}}  }
\end{align}
% TODO We can remember these equations as follows. In Galilean relativity, after drawing out the frames, we would have
%\begin{align}
%   x' = x - vt
%\end{align}
%Both are modulated by $\gamma$, to keep the expression finite when $v$ gets larger and larger. The sign on the time matches $x$, and must match units and $t$. ...  TODO

We can do something interesting from here, lets look at the following quantity
\begin{align}
    s^2 &= -c^2t'^2 +x'^2 + y'^2 + z'^2\\
    &= \frac{c^2(t^2 - \frac{vx}{c^2})^2}{1-\frac{v^2}{c^2}}  + \frac{(x - vt)^2}{1-\frac{v^2}{c^2}} + y^2 + z^2\\
    &= -c^2t^2 + x^2 + y^2 + z^2
\end{align}
It turns out this quantity is \emph{invariant} when we change between frames. These type of things are incredibly important when dealing with topics in special relativity

\subsection{Four Vectors}
A nice way to write things that give us invariants easily is in four vector notation. We can define the position \emph{contravariant} vector with
$$ x^\mu \equiv (x^0, x^1,x^2,x^3) = (ct,x,y,z) $$
Remember the signs by knowing all the vectors with \textit{upper} indices have all \textit{positive} quantities. We can then define a \emph{covariant} with
\begin{align}
     x_\mu \equiv (-x^0, x^1,x^2,x^3) = (-ct,x,y,z)
\end{align}
We see that if we dot these two vectors we get
\begin{align}
    s^2 = x_\mu x^\mu = -c^2t^2 + x^2 + y^2 + z^2
    \end{align}
This one tells us things about how events are causally connected to one another, since

$$s^2 = - c^2(t_2-t_1)^2 + (\textbf{x}_2-\textbf{x}_1)^2$$

\begin{itemize}
\item $s^2 = 0$ Lightlike, only massless particles moving at $c$ will have this 0
\item $s^2 > 0$ Spacelike, in every frame, there will always be some separation of space between the events. Causally unrelated
\item $s^2 < 0$ Timelike, time separates these events in all frames.
\end{itemize}

Another useful thing that comes up often is the \textbf{Minkowski Metric} defined as

\begin{align}
\eta_{\mu\nu} = \left(
{\begin{array}{cccc}
-1&0&0&0\\
0&1&0&0\\
0&0&1&0\\
0&0&0&1
\end{array}}
\right)
\end{align}
This transforms a contravariant into a covariant with
\begin{align}
    x_\mu = \eta_{\mu\nu}x^\nu
\end{align}
Also important is the 4-gradient

\begin{align}
\partial_\mu &\equiv \frac{\partial}{\partial x^\mu} = (\frac{\partial t}{\partial x^0}\frac{\partial}{\partial t}, \frac{\partial x}{\partial x^1}\frac{\partial}{\partial x}, \frac{\partial y}{\partial x^2} \frac{\partial}{\partial y},\frac{\partial z}{\partial x^3}\frac{\partial}{\partial z} ) = (\frac{1}{c} \partial_t, \partial_x,\partial_y,\partial_z)
\end{align}

Be aware that the lower index partial is with respect to the upper index $x$. Similarly this gives
$$\partial^\mu = (-\frac{1}{c}\partial_t,\partial_x,\partial_y, \partial_z)$$

\subsection{Relativistic Kinematics}
The key equation to remember is
\begin{align}\label{relenergy}
    E^2 = p^2c^2 +m^2c^4
\end{align}
We can define the \emph{four momentum} as
\begin{align}
    p^\mu = (E/c,p_x,p_y,p_z)
\end{align}
Notations can sometimes swap the minus signs, but it seems easier to remember that all raised index vectors are entirely positive. The covariant is the same with the front sign swapped. We see that if we rearrange equation \ref{relenergy} we can find
\begin{align}
- m^2c^2 = -\frac{E^2}{c^2} + p^2 = p_\mu p^\mu
\end{align}
Usually in the problems here you are given two objects with momentum $p_1^\mu$ and $p_2^\mu$ respectively, that turn into a new particle with four-vector $p_3^\mu$. We know that in general
\begin{align}
    p_3^\mu = p_1^\mu + p_2^\mu
\end{align}
Which means we just add each of the components of the vector like normal, which gives us the new 4 momentum. From here, we can find the invariant mass of the system just doing
\begin{align}
    -m_3^2c^2 = (p_{1\mu} + p_{2\mu})(p_1^\mu + p_2^\mu)
\end{align}
Proper time is Lorentz invariant and defined as

\begin{equation}\label{propertime}
c^2d\tau^2 = -\eta_{\mu\nu}dx^{\mu}dx^{\nu}
\end{equation}
The 4-velocity is then defined as

$$u^\mu \equiv \frac{d x^\mu}{d\tau}$$
Plugging in our definition back into equation \ref{propertime} we get that
\begin{align}
-c^2 &= u_\mu u^\nu\\
 &= -c^2\frac{d t}{d \tau}^2 + \frac{d x}{d \tau}^2 + \frac{d y}{d \tau}^2 + \frac{d z}{d \tau}^2\\
 &= -c^2\frac{d t}{d \tau}^2(1- \frac{v^2}{c^2})
\end{align}
This gives us time dilation with $\gamma d\tau = dt$. Replugging this into the definition of the 4-velocity, we get

$$u^\mu = (\gamma c, \gamma v_x, \gamma v_y,\gamma v_z)$$
This allows us to then define the 4-momentum of a massive particle as
$$p^\mu \equiv mu^\mu = (\gamma mc, \gamma mv_x, \gamma mv_y,\gamma mv_z)$$
The Lorentz force equation is given by

$$\frac{dp^\mu}{d\tau} = eF^{\mu\nu}\frac{dx^\nu}{d\tau}$$

There is a similar way to write the boost in momentum and energy as we did for space and time
\begin{align}
    E' &= \gamma(E - vp_x)\\
    p_x' &= \gamma(p_x - vE/c^2)\\
    p_y' &= p_y\\
    p_z' &= p_z
\end{align}
If the other frame $F'$ is moving with velocity $v$ in the $x$ direction relative to frame $F$.

\section{Rotation}\label{classicalrot}

\begin{figure}\label{rotation}
\centerline{\includegraphics[width=0.7\textwidth]{physics/images/rotation}}
\caption{The left is an \emph{active} rotation, which involves physical rotation of an object. The right is a \emph{passive} rotation which involves instead the rotation of the coordinate system.}
\end{figure}

$$R(\hat{n},\theta)$$

$R$ is a rotation matrix, $\hat{n}$ is what axis you are choosing to rotate around, points along that axis. $\theta$ determines how far around that axis you are going to rotate. Directions are chosen from the cross product, for instance if it is $\hat{z}$, we know $x\times y=z$, so that requires use to have it such that it looks like $x$ chases $y$, or $x$ will move towards $y$ in the direction it is closest to it from. This turns out to happen for all of the pairs, when said in order, i.e.

\begin{align}
x\times y &= z\\
y\times z &= x\\
z\times x &= y\\
\end{align}

If you ever find them in the opposite order, it is equivalent to going the opposite direction. There are two typical conventions for rotations outline in Figure \ref{rotation}. In most cases, we only care about the active rotation, given around the $\hat{z}$ axis below with

\begin{align}
R(\hat{z},\theta) =  \left(
{\begin{array}{ccc}
\cos\theta&-\sin\theta&0\\
\sin\theta&\cos\theta&0\\
0&0&1\\
\end{array}}
\right)
\end{align}

Similar rotations around $\hat{x},\hat{y}$ can be found easily by cyclically permutating the vectors and realigning, with

\begin{align}\left(
{\begin{array}{c}
x_1\\
y_1\\
z_1\\
\end{array}}\right) &\rightarrow
\left(
{\begin{array}{c}
z_1\\
x_1\\
y_1\\
\end{array}}\right) \\
\left(
{\begin{array}{c}
z_1'\\
x_1'\\
y_1'\\
\end{array}}\right) &=
\left(
{\begin{array}{ccc}
\cos\theta&-\sin\theta&0\\
\sin\theta&\cos\theta&0\\
0&0&1\\
\end{array}}
\right)\left(
{\begin{array}{c}
z_1\\
x_1\\
y_1\\
\end{array}}\right)\\
\rm{Reorder}\implies
\left(
{\begin{array}{c}
x_1'\\
y_1'\\
z_1'\\
\end{array}}\right)
&= \left(
{\begin{array}{ccc}
\cos\theta&0 &\sin\theta\\
0&1&0\\
-\sin\theta&0&\cos\theta\\
\end{array}}
\right)\left(
{\begin{array}{c}
x_1\\
y_1\\
z_1\\
\end{array}}\right)
\end{align}
This is a rotation around the $\hat{y}$ axis, as that direction is unaffected.

\subsection{Rotating Frames}
Given a rotating frame $r$ which is rotating with constant angular velocity $\omega$ and we want to find a non-rotating frame $s$ where Newton's laws apply, we have that
\begin{align}
\textbf{v}_s = \textbf{v}_r + \boldsymbol{\omega}\times\textbf{r}
\end{align}
Where $r$ is the distance from the center of rotation. To find the acceleration, we must also consider the unit vectors as a function of time, with %\todo{Fix this, do in index notation}
\begin{align}
\textbf{a}_s = \frac{d\textbf{v}_s}{dt} &= \frac{d}{dt}\Big[|v_x|\hat{x} + |v_y|\hat{y} + |v_z|\hat{z} + \boldsymbol{\omega}\times(|r_x|\hat{x} + |r_y|\hat{y} + |r_z|\hat{z})\Big]\\
&= \Big[|\dot{v}_x|\hat{x} + |\dot{v}_y|\hat{y} + |\dot{v}_z|\hat{z} + \boldsymbol{\omega}\times(|\dot{r}_x|\hat{x} + |\dot{r}_y|\hat{y} + |\dot{r}_z|\hat{z})\Big] \\
&+ \Big[|v_x|\dot{\hat{x}} + |v_y|\dot{\hat{y}} + |v_z|\dot{\hat{z}}  +\boldsymbol{\omega}\times(|r_x|\dot{\hat{x}} + |r_y|\dot{\hat{y}} + |r_z|\dot{\hat{z}})\Big]\\
\end{align}
In general the time derivative of any unit vector in a rotating frame is given by
\begin{align}
\dot{\hat{u}} = \boldsymbol{\omega}\times\hat{u}
\end{align}
We also know that $\dot{r}_i = v_i$ and $\dot{v}_i = a_i$ since they are simply the rate of change of the objects position and velocity. Thus we have
\begin{align}
\textbf{a}_s &= \textbf{a}_r + \boldsymbol{\omega}\times\textbf{v}_r + \boldsymbol{\omega}\times\textbf{v}_r + \boldsymbol{\omega}\times(\boldsymbol{\omega}\times\textbf{r})\\
&= \textbf{a}_r + 2\boldsymbol{\omega}\times\textbf{v}_r + \boldsymbol{\omega}\times(\boldsymbol{\omega}\times\textbf{r})
\end{align}
Now we care about how Newton's laws look in the rotating frame, and rearranging tells us that
\begin{align}
\textbf{a}_r = \textbf{a}_s - 2\boldsymbol{\omega}\times\textbf{v}_r - \boldsymbol{\omega}\times(\boldsymbol{\omega}\times\textbf{r})
\end{align}
So we have the normal acceleration that would be created from Newton's second law in a non-rotating frame, then two extra terms which are caused by the rotation of the frame itself. The first term is the Coriolis acceleration, and the second is centrifugal acceleration.

\subsection{Moment of Inertia}
To find the moment of inertia of a simple object positioned in a difficult way, first find the moment of inertia of the body in it's center of mass frame such that the tensor is diagonal such that

$$ I_{CM} =
\left(
{\begin{array}{ccc}
I_{xx}&0&0\\
0&I_{yy}&0\\
0&0&I_{zz}\\
\end{array}}
\right)$$

With this you can then rotate the tensor to find what it would be if the object is spun on a more difficult axis. with

$$I_{Rot} = R(\theta_x)R(\theta_y)R(\theta_z)~I_{CM}~R(\theta_z)^{-1}R(\theta_y)^{-1}R(\theta_x)^{-1}$$

If the axis is still not where you want it to be, just apply the parallel axis theorem to again shift it with

$$I_{F} = I_{Rot} + Md^2$$

\section{Fluid Mechanics}
Fluid Mechanics is right on the border of being classical mechanics and statistical mechanics. It has to do with how a large number of particles move together. Looking at the mass density $\rho$, because we cannot create or destroy mass classically, we have
\begin{equation}\label{masscon}
\frac{\partial\rho}{\partial t} = -\nabla\cdot (\rho\textbf{v})
\end{equation}
Which is just the continuity equation, and says that the rate at which the mass density is shrinking is equal to how much mass is leaving each surface at a given time. We also define the momentum of a system by adding up each infinitesimal mass and multiplying it by its respective velocity. This is the same thing as
\begin{align}
    \textbf{p}(V,t) = \int_V dx^3 \rho(\textbf{x},t)\textbf{v}(\textbf{x},t)
\end{align}
An important thing to note is that the velocity $\textbf{v}$ in the integral is not specifically the velocity of any one particle, but called a \emph{velocity field} since it is defined over the entire volume, and the particles are too small for us to be concerned about any of them individually. Newton's third law tells us that $\textbf{F} = \dot{\textbf{p}}$, so we first define the \emph{force field}
\begin{align}
    \textbf{F}(V,t) = \int_V dx^3 \textbf{f}(\textbf{x},t)
\end{align}
Let's match Newton's third law and find
\begin{align}
    \int_V dx^3 \textbf{f}(\textbf{x},t) &= \frac{d}{dt}\int_V dx^3 \rho(\textbf{x},t)\textbf{v}(\textbf{x},t)
\end{align}
Conservation of momentum (also called Euler's equations) gives us
\begin{equation}\label{momcon}
\rho\left({\frac{\partial\textbf{v}}{\partial t} + (\textbf{v}\cdot\nabla)\textbf{v}}\right) = \textbf{f}
\end{equation}

%TODO Some more trivia
%
%\begin{itemize}
%\item Ideal Fluids
%\begin{itemize}
%\item Force field given by $\textbf{f} = -\nabla p$
%\item Isentropic Flow
%\begin{itemize}
%\item Kelvin's Theorem $\frac{d}{dt}\oint \delta\textbf{x}\cdot\textbf{v} = 0$
%\end{itemize}
%\end{itemize}
%\item Incompressible Fluids -  ($\rho=$ const, $\nabla\cdot \textbf{v} = 0$)
%\item Steady Flow -  $d\textbf{v}/dt = 0$
%\item Potential Flow $\textbf{v} = \nabla\phi$
%\end{itemize}
%If any coordinate goes to infinity ($\textbf{v}\cdot\nabla)\textbf{v} = 0$
%

%\section{TODO}

%\begin{itemize}

%\item Classical HW6 Problem 1, coupled oscillators
%\end{itemize}


\subsection{ABS} --- r1 \leftarrow $ |r2| $
\subsection{ADD} --- r1 \leftarrow $ r2 + r3 $
\subsection{AND} --- r1 \leftarrow $ r2 and r3 $ ; input and output are truncated and handled as if they were 32-bit integer.
\subsection{CALL} \emph{peripheral}\: Byte, \emph{arg}\: Int --- call command number \emph{arg} from \emph{peripheral}. BIOS is always mapped to \emph{peripheral} 255.
\subsection{CBRT} --- r1 \leftarrow $ r2 ^ 3 $


\documentclass{article}
\usepackage{latexsym}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{amsthm}

\newtheorem{theorem}{Theorem}[section]
\newtheorem*{problem}{Problem}

\begin{document}
\title{Problems with primes}
\author{Dave Neary}

\section{When is $1+p+p^2+p^3+p^4$ prime for prime $p$?}

\begin{problem}
	Given a prime number $p$, when is the sum of all of the positive factors of $p^4$
	a perfect square?
\end{problem}

\begin{proof}
	Since $p$ is a prime number, the only factors of $p^4$ are of the form
	$p^i, i \in \{0,1,2,3,4\}$. The sum of the factors is thus:
	\[ 1+p+p^2+p^3+p^4 = \frac{p^5-1}{p-1} \]

	Let's call this sum of powers of $p$ $f(p)$ for convenience. We begin our search
	with some exploration. When $n=2, 3, 5, 7, 11$ we obtain the following values:
	\begin{center}
		\begin{tabular}{ |c|c|c| }
			\hline
			$p$ & $f(p)$ & round($\sqrt{f(p)}$)$^2$ \\
			\hline
		2 & 31 & $6^2=36$ \\
		3 & 121 & $11^2=121$ \\
		5 & 781 & $28^2=784$ \\
		7 & 2801 & $53^2=2809$ \\
		11 & 16105 & $127^2=16129$ \\
		\hline
		\end{tabular}
	\end{center}

	3 is the only prime that produces a perfect square so far, and it seems like there
	is always a square close above the other odd primes. It's also interesting to note
	that the square close to $f(p)$ is a little more than the square of the square of our
	prime (not surprising given the $p^4$ term which will dominate as $p$ grows larger):
	$28 = 5^2 + 3, 53 = 7^2 + 4, 127=11^2 + 6$.

	Let's see if we can get close to $f(p)$ with the square of a quadratic expression.
	Clearly such a quadratic will be of the form:
	\[ (p^2 + ap + b)^2 = p^4 + 2ap^3 + (a^2+2b)p^2 + 2abp + b^2\]

	It makes sense to let $a=\frac{1}{2}$, then:
	\[(p^2 + \frac{p}{2} + b)^2 = p^4 + p^3 + (\frac{1}{4}+2b)p^2 + bp + b^2 \]

	Given that $p$ is an odd prime, we can turn this into an integer expression by
	setting $b=\frac{1}{2}$:
	\[ (p^2 + \frac{p+1}{2})^2 = p^4 + p^3 + \frac{5p^2}{4}p^2 + \frac{p}{2} + \frac{1}{4} \]
	\[ = \sum_{i=0}^4 p^i + \frac{1}{4}p^2 - \frac{p}{2} - \frac{3}{4} \]

	So we can write:
	\[ (p^2 + \frac{p+1}{2})^2 = \sum_{i=0}^4 p^i + \frac{1}{4}(p+1)(p-3) \]
	or
	\[ (p^2 + \frac{p+1}{2})^2 = \sum_{i=0}^4 p^i + \frac{1}{4}((p-1)^2-4) \]

	So this is bigger than $\sum_{i=0}^4 p^i$ for all $p>3$ (and, as we saw earlier, is
	equal for $p=3$). If we reduce the square by 1, can we prove that this is always
	smaller than $\sum_{i=0}^4 p^i$?

	\begin{align*}
		(p^2 + \frac{p-1}{2})^2 &= p^4 + p^3 - \frac{3p^2}{4} - \frac{p}{2} + \frac{1}{4}\\
		&= \sum_{i=0}^4 p^i -\frac{7}{4}p^2 - \frac{3}{2}p - \frac{3}{4} \\
		&< \sum_{i=0}^4 p^i
	\end{align*}
	since $p>0$.

	So we have shown that:
	\[(p^2 + \frac{p-1}{2})^2 < \sum_{i=0}^4 p^i \leq (p^2 + \frac{p+1}{2})^2 \]
	with equality if and only if $\frac{1}{4}(p+1)(p-3) = 0$, or when $p=3$

\end{proof}

\section{When is $p^2 + q^2 + 2017$ a perfect square?}

\begin{problem}
        How many prime numbers $p, q$ make $p^2 + q^2 + 2017$ a perfect square?
\end{problem}

\begin{proof}
	Consider the numbers $p^2,q^2,2017 \pmod{4}$.
	\[2017 \equiv 1 \pmod{4} \]
	If $p$ is odd, $p^2 \equiv 1 \pmod{4}$, and if $p$ is even, $p^2 \equiv 0 \pmod{4}$.

	Then:
	\[ 2017 + p^2 + q^2 \pmod{4} \in \{1,2,3\} \]
	with the value 1 when both $p,q$ are event, 2 if one of them is odd, and 3 if both
	are odd.

	For any integer $a$, $a^2 \equiv 0 \text{ or } 1 \pmod{4}$ - so both $p,q$ must be
	even. The only even prime number is 2, so the only number we need to check is
	\[ 2017 + 2^2 + 2^2 = 2025 = 45^2 \]

	So the only answer is $(p,q) = (2,2)$.
\end{proof}

\end{document}