\chapter{Schnorr's applications}
\label{chpr:application}
In this chapter we will present some of the applications that Schnorr would make deployable in Bitcoin: we will study improved multi and threshold signature schemes and we will see the construction called adaptor signature, that allows the development of the so called \textit{scriptless scripts}, affecting considerably privacy and efficiency in cross-chain atomic swaps and in the Lightning Network.
\\
In case the reader is not familiar with Bitcoin's inner working, we recommend the reading of Appendix \ref{app:A}.

\bigskip

\section{Multi-signature: MuSig ($\mu \Sigma$)}
\label{musig}
Usually Schnorr is presented with an implicit multi-signature scheme: given $n$ users that want to sign a single message $m$, they can sign it on their own, the final signature being the sum of the so called partial signatures. This signature can then be verified against the sum of the public keys.
\\
Let's study this scheme through an example: Alice and Bob have key pairs $\{q_A, Q_A\}$ and $\{q_B, Q_B\}$, respectively. If both participants are honest, they will proceed as follows: they exchange their public keys, computing the aggregated one $Q = Q_A + Q_B$. Then each one of them calculate as usual the public nonces $K_A$ and $K_B$, defining the joint nonce as $K = K_A + K_B$. The signature would then be $(x_K, s)$, with $s = s_A + s_B = k_A + \text{hash}(x_K \ || \ Q \ || \ m)q_A + k_B + \text{hash}(x_K \ || \ Q \ || \ m)q_B \ (\text{mod} \ n)= (k_A + k_B) + \text{hash}(x_K \ || \ Q \ || \ m)(q_A + q_B) \ (\text{mod} \ n)$. Looking exactly as a single user signature, the verification procedure would follow Algorithm \ref{alg:schnorr_ver}.
\\
This sounds great, except for the fact that it is a completely insecure scheme: we assumed that both the participants were honest, a deadly hypothesis for every cryptosystem. Imagine that it is Bob that wants to cheat. He could simply says that his public key is $Q_B' = Q_B - Q_A$. Then, if someone sends money to the address associated to $Q = Q_A + Q_B' = Q_A + Q_B - Q_A = Q_B$, clearly Bob can control the funds by himself, being in possess of the associated private key.
\\
This kind of attack is called rogue key attack and is a serious concern for multi-signature schemes: given $n$ participants, a subset of $1 \leq t < n$ dishonest signers use public keys that are functions of the public keys of honest signers, allowing them to forge a signature without the aid of the honest signers for the whole set of public keys. There are certain ways to prevent such an attack: for example by ensuring that the participants own the private keys associated with the alleged public keys (now it is not possible for Bob to cheat, since it would imply breaking the ECDLP), a setting that takes the name of KOSK (knowledge of secret key).

\bigskip
\noindent
In this section we will present a provably secure multi-signature scheme of the type $n$-of-$n$. But before delving into its technicalities, it could be better to stop and talk a little about how changes are introduced in Bitcoin: deploying innovations in Bitcoin is a long procedure, due to its decentralized consensus protocol. Since it could require years to take a new feature to it, we should think about properties that would enhance Bitcoin in the long term. Today Bitcoin is missing some important properties in order to be a good method of payment: it is missing both fungibility and privacy. It is missing fungibility due to the fact that it is missing privacy: Bitcoin is pseudonymous, not anonymous, in the sense that an address is not directly linked to a physical person, but every single transaction is on the public  ledger open to (possibly) every node in the network. Low privacy means that bitcoins, not being interchangeable, could be treated differently: think about the bitcoins possessed by the creator of Bitcoin, Satoshi Nakamoto, and not moved since the creation of Bitcoin. Obviously they have not the same appeal of newly minted coins.
\\
Fortunately enough, the lack of some properties is not everlasting: for such a reason, when introducing a new feature in Bitcoin we should try to fix these problems. So, we will give now a look to some properties that, in a long term view, a new multi-signature scheme should possess:
\begin{enumerate}
	\item Accountability: this property refers to $m$-of-$n$ multi-signature schemes (also referred to as threshold schemes) and deals with the fact that for the participants of the scheme should be possible to know who signed and to show to others that they have not;
	\item Usability: the ease of use is important. If an interactive scheme requires a huge number of rounds, it won't be used by anyone;
	\item Privacy: third parties should learn as little about the policy of the scheme as possible (particular kind of policies could identify your transactions, leading to various problems, like censorship by miners).
\end{enumerate}

\bigskip
\noindent
After this brief digression, we are ready to present the MuSig scheme \cite{RefWork:11}. MuSig is an interactive (meaning that the scheme comprehends different rounds of communication between the participants) multi-signature scheme, based on the Schnorr signature. MuSig has some very attractive properties, namely:
\begin{itemize}
	\item The size of the signature is equal to the single user case;
	\item It is provably secure in the plain public key model\footnote{The signers are only required to have a public key: they do not have to prove ownership of it, i.e. knowledge of the associated private key.}.
\end{itemize}
These properties, although being appealing, are not original: MuSig shares them with other schemes, in particular with the Bellare-Neven (BN) scheme \cite{RefWork:10}. The novelty introduced by the authors is that they recovered key aggregation, meaning that to the scheme can be associated a unique joint public key, leading to a verification algorithm that is equal to the single user case: the multi-signature can be verified with respect to a single aggregated public key, leading to greater privacy since for third parties the multi-signature policy is completely hidden.
\\
The Bellare-Neven scheme prevents rogue key attacks relying on a particular algorithm to compute the partial signatures, avoiding a trusted setup: each participant $i \in \{1, ..., n\}$ with key pair $\{q_i, Q_i\}$ computes $s_i = k_i + c_iq_i, \ c_i = \text{hash}(\langle L \rangle\ || \ K \ || \ Q_i \ || \ m)$, where $K = \sum_{i = 1}^{n}K_i$ is the aggregated public nonce, $m$ is the message to be signed and $\langle L \rangle$ is a unique encoding of the multiset of public keys $L = \{Q_1, Q_2, ..., Q_n\}$, e.g. ordered lexicographically. The signature is $(K, s)$, where $s = \sum_{i = 1}^{n}s_i$, and the verification equation is: $sG = K + \sum_{i = 1}^{n}c_iQ_i$. We can notice that a validator needs the whole set of public keys in order to check the signature.
\\
MuSig can be thought as a variant of BN that recovers key aggregation. The setting in which the two schemes are defined is the same: both can be proven to be secure in the plain public key model under the discrete logarithm assumption\footnote{The discrete logarithm assumption requires the DL to be hard on the selected group. This means that if the DL is hard, then the scheme is secure.}, modelling the hash functions involved as a public random oracle.
\\
Security is to be intended in the sense that it is infeasible for an adversary to forge multi-signatures involving at least an honest participant, that is: the adversary is not able to produce on its own a signature valid for the set of public keys containing the one of the honest signer.
\\
We stress the fact that, from the applicative point of view, key aggregation is a fundamental property: if the scheme is usable (few interaction rounds), then we get for free privacy and accountability (MuSig is an $n$-of-$n$ scheme, so that it is possible to generate a valid signature only if all the participants agree). Indeed, thanks to key aggregation, verifiers will only see an aggregated public key: they would not even know that it is indeed aggregate, since it is indistinguishable from a normal public key. This is also important from the point of view of efficiency: in Bitcoin every single node has the possibility to validate each transaction, meaning that verification efficiency and signature size are very important, more than the timing of the signing algorithm. This is why, although there are multi-signature schemes with fewer interaction rounds, we present here MuSig: the benefits of key aggregation are improved bandwidth (no need for communication of multiple public keys), privacy (aggregated public key indistinguishable from a normal one) and validation efficiency (as efficient as a normal Schnorr's verification).
\\
Moreover if the aggregated public key is not given to the verifier, it is still possible to recover it just from the set of public keys of the participant, without interaction with the signers.

\bigskip
\noindent
The plain public key setting plays a crucial role when trying to enable multi-signatures across multiple inputs of a Bitcoin transaction, resulting in a unique signature per transaction.  In case the transaction spends inputs from different owners, they will obviously need to collaborate to produce the multi-signature. Such a construction would reduce further the traffic on-chain, resulting in a benefit for all the network participants. Such a change would require the introduction of new opcodes in the Bitcoin scripting language, but this can be done via a soft fork (i.e. in a backward compatible way). To see why security in the plain public key model is fundamental to enable cross-input multi-signature, think about an attacker that identifies some outputs he wants to steal, corresponding to a set $\{Q_1, Q_2, ..., Q_{n - t}\}$ of public keys. He could try to identify another set of keys $\{Q_{n - t + 1}, ..., Q_n\}$ such that he can sign for the aggregated public key. He would be able to steal the coins just by sending a small amount of his own money to outputs corresponding to the keys he found and finally creating a transaction referencing the outputs he wants to steal and the newly created outputs in his possession: by construction he is able to forge a signature on his own for this transaction. But the plain public key model defends exactly against such a situation, since the game is won by the adversary if he is able to forge a signature over a set of keys that includes at least one key not in possession of the attacker.
\\
In the setting of signature aggregation on a transaction basis, it is possible to resort to signature schemes different from MuSig (in particular the older and more reviewed BN scheme), since all the public keys involved are public.
\\
Up to now we have talked about cross-input aggregation, that would reduce the number of signatures to one per transaction. Is it possible to go further? For example, is it possible to obtain a single signature on a block basis? Unfortunately it is not possible through MuSig, since the scheme is interactive: this obviously prevents aggregation on a block level. However the discussion would not be fair if we would not point out that changing signature scheme would allow aggregation on a block basis: for example the BLS signature scheme (\cite{RefWork:15}, \cite{RefWork:16}) is non interactive when it comes to aggregation. This would enable a single signature per block. However, although there is interest around BLS signatures, it is underpinned by different cryptographic hypothesis than ECDSA and Schnorr. For this reason the Bitcoin community is working towards the implementation of Schnorr.

\bigskip
\noindent
Now we can finally look at the inner working of the scheme: it is parameterized by the cyclic group $\mathbb{G}$ (a subgroup of $E(\mathbb{F}_p)$), its order $n$, a generator of the group $G$ and three hash functions $\text{hash}_{com}, \ \text{hash}_{agg}$ and $\text{hash}_{sign}$: $\{0, 1\}^* \to \{0, 1\}^{L_n}$. The bit length of the order $n$ is denoted by $L_n$ and assumed to be a security parameter. The key generation algorithm is not presented: we assume each participant $i \in \{1, ..., m\}$ is in possession of a proper key pair $\{q_i, Q_i\}$. The signing algorithm is presented by Algorithm \ref{alg:musig_sig}. In the following $\langle L \rangle$ denotes a unique encoding of the multiset of public keys and the indices used in the signing algorithm are local references to the other cosigners. The algorithm is split in interactive rounds according to the \textbf{send} and \textbf{upon reception of} commands. Verification occurs following the single signature Schnorr verification Algorithm \ref{alg:schnorr_ver}.

\bigskip

\begin{algorithm}
	\caption{MuSig: signing algorithm}
	\label{alg:musig_sig}
	\begin{algorithmic}[1]
		\Procedure{MuSig\_sig}{$M, q_1, \{Q_2, ..., Q_m\}$}
		\State $m \gets \text{hash}(M)$
		\State $\langle L \rangle \gets \{q_1G, Q_2, ..., Q_m\}$
		\For {$i \gets 1, m$}
		\State $a_i \gets \text{int}(\text{hash}_{agg}(\langle L \rangle \ || \ \text{bytes}(Q_i)))$
		\EndFor
		\State $Q \gets \sum_{i = 1}^{m}a_iQ_i$
		\State $k_1 \xleftarrow{\text{\$}} \{1, ..., n - 1\}$
		\State $K_1 \gets k_1G, \ t_1 \gets \text{hash}_{comm}(\text{bytes}(K_1))$
		\State \textbf{send} $t_1$
		\State \textbf{upon reception of} $t_2, ..., t_m$ \textbf{send} $K_1$
		\State \textbf{upon reception of} $K_2, ..., K_m$ \textbf{do}
		\State $\ \ \ \ \ $ \textbf{for} $i \gets 2, m$ \textbf{do}
		\State $\ \ \ \ \ \ \ \ \ \ $ \textbf{if} $t_i \neq \text{hash}_{comm}(\text{bytes}(K_i))$ \textbf{do}
		\State $\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ $ \textbf{abort}
		\State $\ \ \ \ \ \ \ \ \ \ $ \textbf{end if}
		\State $\ \ \ \ \ $ \textbf{end for}
		\State $K \gets \sum_{i = 1}^{m}K_i$
		\If {$\text{jacobi}(y_K) \neq 1$}
		\State $k_1 \gets n - k_1$
		\EndIf
		\State $c \gets \text{int}(\text{hash}_{sig}(\text{bytes}(x_K) \ || \ \text{bytes}(Q) \ || \ m))$
		\State $s_1 \gets k_1\ + ca_1q_1 \ (\text{mod} \ n)$
		\State \textbf{send} $s_1$
		\State \textbf{upon reception of} $s_2, ..., s_m$ \textbf{do}
		\State $s \gets \sum_{i = 1}^{m}s_i \ (\text{mod} \ n)$
		\State \textbf{return} $(x_K, s)$
		\EndProcedure
	\end{algorithmic}
\end{algorithm}

\bigskip
\noindent
As usual, here follows the proof of the correctness.
\\
{\bf Proof}: Loosely speaking, we have to prove that $sG = K + cQ$.
\\
$$sG = \left(\sum_{i = 1}^{m} s_i\right)G = \left(\sum_{i = 1}^{m}(k_i + ca_iq_i)\right)G = \sum_{i = 1}^{m}(k_iG + ca_iq_iG) =$$
$$= \sum_{i = 1}^{m}k_iG + \sum_{i = 1}^{n} ca_iq_iG = \sum_{i = 1}^{m}K_i + c\sum_{i  = 1}^{m}a_iQ_i = K + cQ.$$
\ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ $\square$

\bigskip
\noindent
For the security proof of the scheme we refer to the original article \cite{RefWork:11}.
\\
Dealing with ECDSA and Schnorr in Chapter \ref{chpr:dss}, we have seen that in the single user setting there was the possibility to derandomize the signature algorithm without loss of security, by generating the random nonce $k$ through a deterministic function. This is done since pseudo random generation is one of the major sources of problems in cryptography. This is not anymore suggested in the multi-user setting: it is necessary to ensure to use different unpredictable values when the other signers change their $K$ values in repeated signing attempts, otherwise secret key recovery would be possible.
\\
Here follows an example taken directly from \cite{RefWork:11}: assume Alice and Bob have key pairs $\{q_A, Q_A\}$ and $\{q_B, Q_B\}$, respectively. They want to jointly produce a signature. Alice generates $k_A$ and sends $K_A = k_AG$ to Bob. In a first attempt, Bob responds with $K_B$. Alice then computes:
$$K = K_A + K_B,$$
$$c = \text{hash}_{sig}(x_K \ || \ Q \ || \ m),$$
$$s_A = k_A + ca_Aq_A \ (\text{mod} \ n),$$
and sends $s_A$ to Bob. Bob is trying to cheat on Alice, and decides not to produce a valid $s_B$, and thus the protocol fails. A new signing attempt takes place, and Alice again sends the same $K_A$. Bob responds with $K_B' \neq K_B$. Alice then computes $c' = \text{hash}_{sig}(x_{K_A + K_B'} \ || \ Q \ || \ m)$ and $s_A' = k_A + c'a_Aq_A \ (\text{mod} \ n)$ and sends $s_A'$ to Bob. Now Bob is able to derive Alice's private key:
$$s_A - s_A' = (c - c')a_Aq_A \ (\text{mod} \ n) \ \Longrightarrow \ q_A = (c - c')^{-1}a_A^{-1}(s_A - s_A') \ (\text{mod} \ n).$$
To avoid this problem, each signer must ensure that whenever any $K$ value sent by other cosigners or the message $m$ changes, his $k_i$ changes as well.

\bigskip

\bigskip

\section{Threshold signature}
\label{threshold}
With the name threshold signatures we refer to policies of the kind $m$-of-$n$, where it is necessary that at least $m$ participants of the scheme decide to collaborate to produce a valid signature. This kind of policy is very popular in Bitcoin, since it is flexible and has many applications: for example, a single user could use such a policy to improve security, storing the keys on different machines, at the same time defeating the risk of loss of some keys.
\\
In this section we will study a provably secure Schnorr based threshold scheme. For the security proof we refer to \cite{RefWork:14}. The scheme is constructed on top of the Pedersen Verifiable Secret Sharing Scheme (VSS scheme) and Pedersen's multi-party protocol to generate a random shared secret, hence we start presenting these two schemes.

\bigskip

\subsection{Verifiable secret sharing scheme}
\label{subsec:1}
Hereinafter, we will refer to threshold signature schemes as $t$-of-$m$ schemes in order to avoid confusion in the notation.
\\
Typically, in a $t$-of-$m$ secret sharing scheme, a trusted dealer distributes a secret $s$ to $m$ players $P_1, ..., P_m$ in such a way that any subgroup of at least $t$ members can recover the secret, while any subgroup of cardinality strictly less than $t$ learns nothing about it. A verifiable secret sharing scheme moreover prevents the dealer from cheating, since each participant can verify that his share of the secret is consistent with the others. The novelty introduced by Pedersen is that his scheme is non-interactive in the verification and does not require trust between the parties involved. Still there is a central dealer, a figure we would like to get rid of: this will be done through the second protocol that will be presented in Section \ref{subsec:2}. Here follows the VSS scheme proposed by Pedersen.

\bigskip
\noindent
Fix an elliptic curve over a prime finite field $E(\mathbb{F}_p)$, characterized by the EC domain parameters $T = (a, b, p, G, n, h)$ and fix another generator $H$ of the same cyclic group generated by $G$. We require that these two generators are \textit{nothing up my sleeves} (NUMS), meaning that we do not know the discrete logarithm of one with respect to the other, and vice versa.
\\
Assume that the dealer has a secret value $s \in \mathbb{Z}_n$ and a number $s' \in \mathbb{Z}_n$ generated at random. He commits\footnote{A commitment scheme is a cryptographic primitive used to commit to some secret data without revealing anything about it. Commitment schemes are designed so that it is unfeasible to change the secret: when revealed in a second moment, we have probabilistic assurance that it is the real committed value. A typical example of commitment scheme is a collision resistant hash function, e.g. SHA-256.} to the couple $(s, s')$ through the so called Pedersen commitment $C_0 = sG + s'H$. The NUMS property is needed to prevent the person who commits from lying about the values he committed to. Assume indeed that the dealer knows the discrete logarithm of $H$ with respect to $G$: $H = r_HG$. In this case he could write: $C_0 = sG + s'H = (s + s'r_H)G = (s \pm ar_H + s'r_H)G = (s - ar_H)G + (s'r_H + ar_H)G = (s - ar_H)G + (s' + a)H, \ \forall a \in \mathbb{Z}_n$.  As the calculations clearly show, knowing the DL the dealer could commit so the couple $(s, s')$ but later reveal $(s - ar_H, s' + a)$.
\\
After having broadcast the commitment, the secret $s$ can be shared among $P_1, ..., P_m$ through the following protocol:

\bigskip
\noindent
{\bf The dealer}:
\begin{enumerate}
	\item Chooses a couple of random polynomials of degree $t - 1$:
	$$f(u) = s + f_1u + ... + f_{t - 1}u^{t - 1} \ (\text{mod} \ n),$$
	$$f'(u) = s' + f'_1u + ... + f'_{t - 1}u^{t - 1} \ (\text{mod} \ n),$$
	where $s \ \text{and} \ s'$ are the committed values, while $f_i, f'_i \in \mathbb{Z}_n$ are randomly chosen for every $i \in \{1, ..., t - 1\}$;
	\item Computes $(s_i, s'_i) = (f(i), f'(i))$ for $i \in \{1, ..., m\}$;
	\item Sends secretly $(s_i, s'_i)$ to $P_i, \forall i \in \{1, ..., m\}$;
	\item Broadcasts the values $C_j = f_jG + f'_jH, \ \forall j \in \{1, ..., t - 1\}$.
\end{enumerate}

\bigskip

\noindent
{\bf Each participant $P_i$}:
\begin{enumerate}
	\item Verifies the consistency of its share of the secret as:
	$$s_iG + s'_iH = \sum_{j = 0}^{t - 1}i^jC_j.$$
	If this check fails, she broadcasts a compliant against the dealer;
	\item For each compliant from a player $i$, the dealer defends himself by broadcasting the values $(s_i, s'_i) = (f(i), f'(i))$ that satisfy the checking equation at point 1;
	\item Aborts the protocol if:
	\begin{itemize}
		\item The dealer received more than $t$ compliants;
		\item He answered to a compliant with values that violate again the checking equation.
	\end{itemize}
\end{enumerate}
Pedersen proved that any coalition of less than $t$ players cannot get any information about the shared secret, provided that the discrete logarithm in $E(\mathbb{F}_p)$ is hard\footnote{This is important since we are not adding cryptographic assumptions.}. For the proof we refer to the original paper \cite{RefWork:13}. Although we do not look at the proof, it may still be of interest to check why the verification procedure at step 1 should succeed:
$$s_iG+ s'_iH = f(i)G + f'(i)H = \sum_{j = 0}^{t- 1}f_ji^jG + \sum_{j = 0}^{t - 1}f'_ji^jH =$$
$$= \sum_{j = 0}^{t - 1}i^j(f_jG + f'_jH)= \sum_{j = 0}^{t - 1}i^jC_j.$$
We used the convention that $f_0 = s$ and $f'_0 = s'$. Remembering that $C_0$ commits to the secret and that the other $C_j$ commits to the polynomials, we have the assurance that the dealer is not cheating. Indeed there is one and only one polynomial over $\mathbb{Z}_n$ of degree at most $t - 1$ satisfying $f(i) = s_i$, respectively $f'(i) = s'_i$, for $t$ values of $i$.
\\
This is also the key property that allows the reconstruction of the secret value from any group $\mathcal{P}$ of $t$ participants. Indeed the members in $\mathcal{P}$ can recover the polynomial $f$ through the Lagrange's interpolation formula, that given a set of $t$ points $(i, s_i = f(i))$ returns the lowest degree polynomial (in this case a $t - 1$ degree polynomial) interpolating the given points:
$$f(u) = \sum_{i \in \mathcal{P}}f(i)\omega_i(u) \ (\text{mod} \ n), \ \text{where} \ \omega_i(u) = \prod_{j \in \mathcal{P}, \ j \neq i}\frac{u - j}{i - j} \ (\text{mod} \ n).$$
Since it holds that $s = f(0)$ by definition, the group $\mathcal{P}$ can directly reconstruct the secret as:
$$s = f(0) = \sum_{i \in \mathcal{P}}f(i)\omega_i \ (\text{mod} \ n),  \ \text{where} \ \omega_i = \omega_i(0) = \prod_{j \in \mathcal{P}, \ j \neq i}\frac{j}{j - i} \ (\text{mod} \ n).$$

\bigskip

\subsection{Protocol for the generation of a random shared secret}
\label{subsec:2}
As we pointed out before, we would like to get rid of the figure of the dealer, so that it is possible to generate a key pair between distrustful parties without his intervention. The key generation phase of the signature scheme generates a random shared secret key in a distributed way according to the following protocol:
\\
\\
{\bf Each participant $P_i$}:
\begin{enumerate}
	\item Chooses $r_i, r'_i \in \mathbb{Z}_n$ at random and verifiably shares $(r_i, r'_i)$ acting as the dealer according to the Pedersen's VSS scheme described above. Let the sharing polynomials of participant $i$ be $f_i(u) = \sum_{j = 0}^{t - 1}a_{ij}u^j \ (\text{mod} \ n)$, $f'_i(u) = \sum_{j= 0}^{t - 1}a'_{ij}u^j \ (\text{mod} \ n)$, where $a_{i0} = r_i$ and $a'_{i0} = r'_i$. The public commitments are $C_{ik} = a_{ik}G + a'_{ik}H$ for $k \in \{0, ..., t - 1\}$;
	\item Sets $H_0 = \{P_j \ | \ P_j \ \text{is not detected to be cheating at step 1}\}$. The distributed secret value $r$ is equal to $\sum_{i \in H_0}r_i \ (\text{mod} \ n)$ (but nobody can compute it on its own). Each participant $P_i$ sets his share of the secret at $s_i= \sum_{j \in H_0}f_j(i) \ (\text{mod} \ n)$ and sets the value $s'_i = \sum_{j \in H_0}f'_j(i) \ (\text{mod} \ n)$ (the share of the secret is simply equal to the sum of the partial shares received from honest participants);
	\item Each player in $H_0$ broadcasts $R_i = r_iG$ via Feldman's VSS scheme:
	\begin{enumerate}
		\item Each player $P_i$ in $H_0$ broadcasts $A_{ik} = a_{ik}G$ for $k \in \{0, ..., t - 1\}$;
		\item Each player $P_j$ verifies the values broadcast by the other players in $H_0$, i.e. for each $P_i \in H_0$, $P_j$ checks that:
		$$f_i(j)G = \sum_{k = 0}^{t - 1} j^kA_{ik}.$$
		If the check fails for an index $i$, $P_j$ complaints against $P_i$ broadcasting the values $(f_i(j), f'_i(j))$ that satisfy the checking equation of the Pedersen's VSS scheme  but not the one at point (b);
		\item For players $P_i$ who received at least one valid complaint, the other players run the reconstruction phase of Pedersen's VSS scheme to compute $r_i$, $f_i(u)$ and $A_{ik}$ for $k \in \{0, ..., t - 1\}$. All participants in $H_0$ set $R_i = r_iG$.
	\end{enumerate}
\end{enumerate}
After the execution of the protocol the following equations hold:
$$R = \sum_{i \in H_0} R_i = \sum_{i \in H_0}r_iG = \sum_{i \in H_0}A_{i0} = rG,$$
$$f(u) = \sum_{i \in H_0} f_i(u) = r + a_1u + ... + a_{t - 1}u^{t - 1} \ (\text{mod} \ n), \ \text{where} \ a_i = \sum_{j \in H_0}a_{ji} \ (\text{mod} \ n),$$
$$f(i) = s_i.$$
We introduce the following notation:
$$(s_1, ..., s_n) \xleftrightarrow{\text{(t, m)}} (r|R, a_iG, H_0), \ i \in \{0, ..., t - 1\}.$$
It means that $s_j$ is the share of secret key $r$ belonging to $P_j$ for $j \in H_0$. The values $a_iG$
are the public commitments of the sharing polynomial and $\{r, R\}$ is the key pair that can be reconstructed by any subgroup of $H_0$ composed of at least $t$ participants: this can be done via Lagrange's interpolation formula, as described in Section \ref{subsec:1}.
\\
Before we pass to analyse the actual signature scheme, let's give a look at the checking equation at point (b) in the protocol and verify why it should work:
$$f_i(j)G = \sum_{k = 0}^{t - 1}a_{ik}j^kG = \sum_{k = 0}^{t - 1}j^kA_{ik}.$$

\bigskip

\subsection{Threshold signature scheme}
Now that we have defined the primitives on which it is built, we can finally discuss the protocol that implements the $t$-of-$m$ threshold signature scheme. It is important to understand that the participants do not simply recover the private key: this would allow anyone possessing it to sign on the behalf of every other participant in the scheme, even those that did not take part in the reconstruction procedure. Instead, as we will see, the approach consists in the generation of a partial signature through the share of secret key in possession of each user.

\bigskip
\noindent
{\bf Key generation}: All $m$ participants have to cooperate to generate a public key $Q$ and a share of the secret key for each participant $P_j$. This can be done relying on the protocol presented in Section \ref{subsec:2}. The output of the protocol is:
$$(\alpha_1, ..., \alpha_m) \xleftrightarrow{\text{(t, m)}} (q|Q, b_iG, H_0), \ i \in \{0, ..., t - 1\}.$$
The $\alpha$ values denote the secret key share belonging to $P_j$. They will be used to generate a partial signature for the key pair $\{q, Q\}$.
\\
\\
{\bf Signing algorithm}: Let $msg$ denote the message to be signed. Suppose that a subset $H_1 \subseteq H_0$ wants to issue a signature. The members of $H_1$ proceed as follows:
\begin{enumerate}
	\item If $|H_1| < t$, abort. Otherwise, the subset $H_1$ generates a random shared secret following again the protocol presented in Section \ref{subsec:2}. We denote the output as:
	$$(\beta_1, ..., \beta_m) \xleftrightarrow{\text{(t, m)}} (k|K, c_iG, H_2), \ i \in \{0, ..., t - 1\};$$
	\item If $\text{jacobi}(y_K) \neq 1$, then each player $i$ sets $\beta_i = n - \beta_i$;
	\item If $|H_2| < t$, aborts. Otherwise, each $P_i \in H_2$ reveals
	$$\gamma_i = \beta_i + e\alpha_i \ (\text{mod} \ n),$$
	where $e = \text{int}(\text{hash}(\text{bytes}(x_K) \ || \ \text{bytes}(Q) \ || \ msg))$.
	\item Each $P_i \in H_2$ verifies $\forall P_l \in H_2$:
	$$\gamma_lG = \begin{cases} K + \sum_{j = 1}^{t - 1} c_jl^jG + e\left(Q + \sum_{j = 1}^{t - 1}b_jl^jG\right), & \mbox{if } \text{jacobi}(y_K) = 1 \\ - K -\sum_{j = 1}^{t - 1} c_jl^jG + e\left(Q + \sum_{j = 1}^{t - 1}b_jl^jG\right), & \mbox{if } \text{jacobi}(y_K) \neq 1 \end{cases}$$
	Let $H_3 = \{P_j \ | \ P_j \ \text{not detected to be cheating at step 4}\}$.
	\item If $|H_3| < t$, abort. Otherwise each $P_i \in H_3$ selects an arbitrary subset $H_4 \subseteq H_3$ with $|H_4| = t$ and computes $\sigma$ satisfying $\sigma = k + eq \ (\text{mod} \ n)$, where:
	$$\sigma = \sum_{j \in H_4}\gamma_j\omega_j \ (\text{mod} \ n), \ \text{where} \ \omega_j = \prod_{h \in H_4, \ h \neq j}\frac{h}{h - j} \ (\text{mod} \ n).$$
	The signature is $(x_K, \sigma)$; it is verified as a simple Schnorr signature.
\end{enumerate}
This concludes the presentation of the protocol. Nonetheless there are some formulas that deserve greater attention.
\begin{itemize}
	\item Checking formula at point 4\footnote{The formula is checked in case $\text{jacobi}(y_K) = 1$; the other case is proved in a similar way.}:
	$$\gamma_lG = (\beta_l + e\alpha_l)G = \beta_lG + e\alpha_lG = $$
	$$= \left(k + \sum_{j = 1}^{t - 1}c_jl^j\right)G + e\left(q + \sum_{j = 1}^{t - 1}b_jl^j\right)G =$$
	$$= K + \sum_{j = 1}^{t - 1}c_jl^jG + e\left(Q + \sum_{j = 1}^{t - 1}b_jl^jG\right).$$
	\item Formula used to compute $\sigma$: we defined $\gamma_i = \beta_i + e\alpha_i \ (\text{mod} \ n), \ \forall i \in H_2$. In particular the equation holds for every $i \in H_4$, with $|H_4| = t$. The $\alpha$ and $\beta$ values are defined to be the pointwise evaluation of the sharing polynomials created during the two iterations of the Pedersen protocol for the generation of a random shared secret, that we denote by $F_1(u)$ and $F_2(u)$. These polynomials have degree $t - 1$, so that we can define another polynomial of degree $t - 1$ as:
	$$F_3(u) = F_2(u) + eF_1(u) \ \Longrightarrow $$
	$$\Longrightarrow \ F_3(0) = F_2(0) + eF_1(0) \Longrightarrow $$
	$$\Longrightarrow \sigma := F_3(0) = k + eq \ (\text{mod} \ n).$$
	At this point we can apply the Lagrange's interpolation formula, since we know that $F_3(u)$ satisfies by construction $F_3(i) = \gamma_i$:
	$$F_3(u) = \sum_{j \in H_4}\gamma_j\omega_j(u) \ (\text{mod} \ n), \ \text{where} \ \omega_j(u) = \prod_{h \in H_4, \ h \neq j}\frac{u - h}{j -h} \ (\text{mod} \ n).$$
	Thus, $\sigma$ can be directly computed as:
	$$\sigma = F_3(0) = \sum_{j \in H_4}\gamma_j\omega_j \ (\text{mod} \ n), \ \text{where} \ \omega_j = \prod_{h \in H_4, \ h \neq j}\frac{h}{h - j} \ (\text{mod} \ n).$$
\end{itemize}
Notice that the scheme is robust, meaning that a corrupt signer who does not follow the protocol will be detected. The validity of the partial signatures computed at step 3 is immediately tested at step 4.

\bigskip

\bigskip
\noindent
The scheme presented is complex and cumbersome, but all the computations and interactions burden the participants who freely decided to rely on it. The Bitcoin blockchain would see a standard transaction with a single signature, indistinguishable from others. Nobody could tell that it required a threshold signature. This means that the protocol is highly private, but it comes with the downside of not being accountable, since the participants that do not sign cannot learn who instead did it. As usual, it is a matter of trade-offs: if accountability is desired, the naive ECDSA approach should be preferred (and will be available), otherwise users aiming at better privacy could rely on the presented Schnorr threshold scheme.

\bigskip

\bigskip

\section{Adaptor signature}
\label{adaptor}
Adaptor signatures are the building block for the so called \textit{scriptless script}, an innovative idea by Andrew Poelstra: the major aim is to introduce much more flexibility in systems lacking a scripting language (e.g. the Mimblewimble protocol discussed in \cite{MW1} and \cite{MW2}). However, it turns out that these kind of signatures have a couple of interesting applications also in Bitcoin, that we are going to explore.
\\
Adaptor signatures are based on Schnorr and leverage its linearity property. Therefore, introducing Schnorr in Bitcoin would allow the deployment of adaptor signatures for free. As we will see in the next two sections, this tool could affect significantly cross-chain atomic swaps and payment channels, where transactions can be made atomic through signatures and not through Bitcoin scipts. This traduces again in transactions that on-chain look the same as ordinary single signer transactions, improving greatly privacy and efficiency: smaller transactions result in lower fees, lower blockchain size and lower CPU requirement (since the UTXO set, i.e. the set saved in the RAM of the unspent transaction outputs, shrinks), while a unique aggregate signature hides completely the participants involved.

\bigskip
\noindent
Adaptor signatures come from the addition of the public nonce $K$ generated during Algorithm \ref{alg:schnorr_sig} with a random EC point $T = tG$: however, the secret nonce $k$ is not updated, in the sense that it is still considered $k$ as secret nonce instead of $k + t$. This results obviously in an invalid signature. But thanks to this construction, learning the secret integer $t$ is equivalent to learning a valid signature for the same message and public key used for the adaptor signature.
\\
To clarify how adaptor signatures work, let's look at an example. Consider two participants, Alice and Bob. To produce an adaptor signature Bob proceeds as shown in Algorithm \ref{alg:adaptor} on input a message $M$ and his private key $q_B$.

\begin{algorithm}
	\caption{Adaptor signature}
	\label{alg:adaptor}
	\begin{algorithmic}[1]
		\Procedure{adaptor\_sig}{$M, q$}
		\State $m \gets \text{hash}(M)$
		\State $k \gets \text{int}(\text{hash}(\text{bytes}(q) \ || \ m)) \ (\text{mod} \ n)$
		\State $t \xleftarrow{\text{\$}} \{1, ..., n - 1\}$
		\State $K \gets kG, \ T \gets tG$
		\If {$\text{jacobi}(y_{K + T}) \neq 1$}
		\State $k \gets n - k, \ t \gets n - t$
		\EndIf
		\State $e \gets \text{int}(\text{hash}(\text{bytes}(x_{K + T}) \ || \ \text{bytes}(qG) \ || \ m)) \ (\text{mod} \ n)$
		\State $s' \gets k + eq \ (\text{mod} \ n)$
		\State \textbf{return} $(\text{bytes}(x_T), \text{bytes}(x_{K + T}), \text{bytes}(s'))$
		\EndProcedure
	\end{algorithmic}
\end{algorithm}

\bigskip
\noindent
As we have already pointed out, the signature $(r', s') = (x_{K + T}, s')$ is not valid. Indeed, following the verification algorithm \ref{alg:schnorr_ver} Alice would compute:
$$e = \text{int}(\text{hash}(\text{bytes}(r') \ || \ \text{bytes}(Q_B) \ || \ m)) \ (\text{mod} \ n) \ \Longrightarrow$$
$$\Longrightarrow \ s'G - eQ_B = (k + eq_B)G - eQ_B = kG = K.$$
Then the algorithm would check whether or not $x_K$ is equal to $r' = x_{K + T}$, failing. This is because the secret nonce $k$ has not been offset by $t$.
\\
Although the adaptor signature is invalid, Alice can check that it is a valid adaptor signature, meaning that it is consistent. Consistency is to be intended in the sense that learning a valid signature is equivalent to learning $t$ and vice versa. This is done checking that:
$$s'G = K + eQ_B.$$
She can do this verification because she has $s'$ and $Q_B$, while from the given $x$ coordinates she is able to reconstruct both $T$ and $K + T$, from which she gets $K$. However, thanks to the difficulty of the ECDLP, she cannot find $t$.
\\
Assume now that Bob gives Alice a valid signature $(r', s' + t)$. It is valid by construction, indeed after the usual checks the verification algorithm would compute:
$$e = \text{int}(\text{hash}(\text{bytes}(r') \ || \ \text{bytes}(Q_B) \ || \ m)) \ (\text{mod} \ n) \ \Longrightarrow$$
$$\Longrightarrow \ (s' + t)G - eQ_B = (k + eq_B + t)G - eQ_B = (k + t)G = K + T.$$
This time, the check $x_{K + T} = r'$ would succeed.
\\
From this valid signature and the previously received adaptor signature, Alice can immediately recover $t$ simply by taking the difference: $s' + t - s' = t$.
\\
Obviously also the vice versa holds true: given the adaptor signature $(r, r', s') = (x_T, x_{K + T}, s')$ and $t$ Alice can immediately compute a valid signature as $(r', s' + t)$.

\bigskip
\noindent
Adaptor signatures can be used jointly with the multi-signature scheme described in Section \ref{musig}. Assuming again that it is Bob that wants to generate an adaptor signature, he would modify slightly Algorithm \ref{alg:musig_sig}, while Alice would follow it closely: when computing $K_B$ at step 9, he generates at random $t$ and computes $T = tG$. Then, he commits to $K_B + T$ and, at point 11, sends it to Alice. The final modification occurs at step 24: with $s_B$ he sends Alice also $T$, so that she can verify the adaptor signature. Nothing else changes.
\\
The final joint signature is:
$$(x_{K_A + K_B + T}, s),$$
where
$$s = s_A + s_B = $$
$$= k_A + \text{hash}(\text{bytes}(x_{K_A + K_B + T}) \ || \ \text{bytes}(Q) \ || \ m)\text{hash}(\langle L \rangle \ || \ \text{bytes}(Q_A))q_A + $$
$$+ k_B + \text{hash}(\text{bytes}(x_{K_A + K_B + T}) \ || \ \text{bytes}(Q) \ || \ m)\text{hash}(\langle L \rangle \ || \ \text{bytes}(Q_B))q_B$$
and
$$Q =  \text{hash}(\langle L \rangle \ || \ \text{bytes}(Q_A))Q_A + \text{hash}(\langle L \rangle \ || \ \text{bytes}(Q_B))Q_B.$$
As before this signature is not valid for $Q$, since Bob did not offset $s_B$ by $t$. Again, learning $t$ is equivalent to learning a valid signature.
\\
This is the key idea behind the applications we will study in the following sections.

\bigskip
\noindent
Adaptor signatures may not seem a big deal, but it is worth noticing that if $t$ is some necessary data for a separate protocol, arbitrary steps of arbitrary protocols can be made equivalent to signature production. In such a case it could be useful to attach auxiliary data to the signature to ensure that the role of $t$ is the one claimed. In particular, using the same $T$ in multiple subsequent adaptor signatures, it is possible to make arbitrary sets of signatures atomic: once a valid signature is produced, $t$ is revealed making all the signatures valid. Last thing worth of being pointed out is that adaptor signatures are deniable: for every signature on the blockchain one can come up with some $t$ and construct a linked adaptor signature.

\bigskip

\subsection{Atomic swap}
\label{atomic}
In this section we look at one application of adaptor signatures, starting from the easier concept of cross-chain atomic swap. Notice that the Schnorr's applications discussed in Sections \ref{musig} and \ref{threshold} can be extended outside the Bitcoin ecosystem. Atomic swaps instead are a concept strictly related to the crypto-currency world; for this reason we suggest to stop for a moment and give a look to Appendix \ref{app:A}: in there we give an overview of the role that signatures play in Bitcoin and a brief introduction to Bitcoin scripting language.

\bigskip
\noindent
A cross-chain atomic swap is the exchange of different crypto-currencies among two users in an atomic way, meaning that the swap is successful or the balances of the participants remain unchanged, in such a way that it is not possible to cheat, stealing coins from the other party. Following Bitcoin's spirit this is done in a decentralized way, without the need of resorting on a trusted third party. Atomic swaps' functionalities are important, since usually to convert a crypto-currency into another it is necessary to resort on exchanges, that charges high fees and constitutes a single point of failure.
\\
Let's start discussing how atomic swaps are implemented nowadays: to avoid recourse on exchanges and frauds from other users, the atomicity of the swap is enforced through the so called HTLC (Hashed TimeLock Contract). It is a special kind of locking script used to lock the funds on both blockchains. It is constructed in such a way that when one party claims the funds on one chain, the other party can retrieve the coins locked in the other transaction. If something goes wrong or if too much time elapses, it is possible for both parties to get back their coins.
\\
Considering as usual the two parties to be Alice and Bob, we imagine that they want to trade A-coins for B-coins. An HTLC constructed for this situation could have a structure similar to the following one:

\bigskip

\begin{lstlisting}[frame=single]
OP_IF
	OP_HASH256 <digest> OP_EQUALVERIFY OP_DUP OP_HASH160 <Bob address>
OP_ELSE
	<num> OP_CHECKSEQUENCEVERIFY OP_DROP OP_DUP OP_HASH160 <Alice addres>
OP_ENDIF
OP_EQUALVERIFY OP_CHECKSIG
\end{lstlisting}

\bigskip
\noindent
This HTLC would lock the funds on Alice's blockchain. The two branches of the if operator enforce two possibilities: the first one is linked to Bob, that providing the preimage of the digest\footnote{Typically one party generates a secret and gives its hashed value (digest) to the counterparty: it is the secret value that enforces the atomicity, while the hash value acts as a commitment.} and a signature valid for his public key could claim the funds. This can be done through an unlocking script of the following form, where the 1 at the end is needed to force the execution of the correct if branch:

\bigskip

\begin{lstlisting}[frame=single]
<Bob sig> <Bob pubkey> <preimage> 1
\end{lstlisting}

\bigskip
\noindent
The second path corresponds to Alice's lock time refund possibility: after enough time has elapsed\footnote{The exact amount depending on $<$num$>$ OP\_CHECKSEQUENCEVERIFY. This is not the unique possibility to fix a time lock: the OP\_CHECKSEQUENCEVERIFY operator can be substituted by OP\_CHECKLOCKTIMEVERIFY.} she can claim the funds through an unlocking script that would look something like this, where again the 0 at the end enforces the execution of the else path:

\bigskip

\begin{lstlisting}[frame=single]
<Alice sig> <Alice pubkey> 0
\end{lstlisting}

\bigskip
\noindent
A similar contract, where the roles of Alice and Bob are exchanged, would lock Bob's fund on the B-coin chain. Assuming it is Bob that generates the secret preimage, he would need to send its hash (the digest) to Alice, in order to construct the transaction. The atomicity of the swap is ensured by the fact that when Bob spends the output locked by the HTLC he publishes on-chain the preimage: Alice, that needs to monitor the blockchain, could now use the same preimage to take the B-coins.
\\
Caution has to be used when setting the time locks, in order to avoid fund loss: if Bob chooses the preimage, the time locked refund of B-coins should be greater than the one locking the A-coins. Otherwise Bob would be able to wait until his lock time expires and get his B-coins back. However Alice's lock time, being greater, would still prevents the creation of a refund transaction: Bob could publish the preimage and take all the money.

\bigskip
\noindent
As we have just seen, Alice and Bob have to agree on some aspects of the protocol before they can proceed:
\begin{itemize}
	\item The number of A-coins and B-coins to be exchanged (i.e. the exchange rate between the two currencies);
	\item The addresses where they want to receive funds: each party needs an address for A-coins and one for B-coins (in case of success and failure of the atomic swap)\footnote{Addresses here have to be intended in general: there are blockchain based protocols that do not have addresses at all, e.g. Mimblewimble.};
	\item The hash of the locking secret: Bob generates the secret and sends the hash of it to Alice;
	\item The expiry time of the exchange. As we have told, Alice needs enough time to redeem her funds, otherwise Bob would be able to grab them all.
\end{itemize}

\bigskip
\noindent
Now we analyse the possibilities offered by the introduction of adaptor signatures: first of all, they would allow to bring atomic swaps also on chains which do not support a scripting language to enforce an HTLC.
\\
For the sake of simplicity, but without loss of generality, we assume a unitary exchange rate between A-coins and B-coins. Here follows the detailed protocol to be enforced\footnote{We present the protocol in the case both chains support Schnorr signature; actually this is not strictly required.}:
\begin{enumerate}
	\item Alice and Bob agree on a pair of locking scripts which are secured by an aggregated public key. Let's name these outputs $O_1$ and $O_2$: they are locked respectively by the pairs of keys $(Q_1^A, Q_1^B)$ and $(Q_2^A, Q_2^B)$, aggregated through the MuSig protocol described in Section \ref{musig}. In particular:
	\begin{enumerate}
		\item Alice prepares a transaction TX$_1$ paying one A-coin into $O_1$, but does not sign it. Then she gives it to Bob and asks for a refund transaction that pays back the funds to Alice from TX$_1$, but has lock time L$_1$ (the two cooperates in the signature procedure). Upon reception of the refund transaction Alice can sign TX$_1$. If Bob broadcasts it, he can do nothing since he has not Alice's partial signature; Alice can just wait until the lock time expires and broadcast the refund transaction;
		\item Bob mirrors Alice's behaviour: he prepares TX$_2$ paying one B-coin to $O_2$ but does not sign it; he shares TX$_2$ and requires a signed refund transaction from Alice: it pays from TX$_2$ to Bob with lock time L$_2 > L_1$. Upon reception of the refund transaction (the two must interact to sign it), Bob can sign TX$_2$.
	\end{enumerate}
	\item At this point Alice and Bob can broadcast TX$_1$ and TX$_2$ and both wait for confirmation on the two blockchains. If there are problems at this step, refund transactions can be used to regain control of the money after having waited for the lock times to expire;
	\item Alice and Bob engage the MuSig protocol to spend from TX$_1$ and TX$_2$. Bob generates in parallel adaptor signatures for both $O_1$ and $O_2$ with the same $t$ value and sends them to Alice. She verifies them\footnote{In particular she verifies that both are valid adaptor signatures and that the offset value used is the same.}: if they are valid, she can provide her partial signature to spend TX$_1$,while if there are problems she aborts the protocol broadcasting the refund transaction;
	\item When Bob spends the output of TX$_1$ thanks to Alice's signature, she learns the secret offset $t$ (monitoring the blockchain) and becomes capable of spending from TX$_2$. At this point Bob cannot cheat: being L$_2$ greater than L$_1$ Alice has time to take the B-coins.
\end{enumerate}
In the cooperative case (no refund transaction broadcast) the unlocking scripts of TX$_1$ and of TX$_2$ look exactly the same as an ordinary single user payment: moreover, since only Alice had the adaptor signatures allowing her to extract $t$, nobody but Alice and Bob can link the transactions between the two chains.
\\
Notice that the efficiency achievement is impressive: we were able to condensate the verbose script semantics required by HTLC in a fixed size signature: this would result, once again, in greater privacy and efficiency, leading to an improvement also in fungibility.

\bigskip

\subsection{Lightning Network}
\label{ln}
The Lightning Network is an example of the broader concept of payment channel, an idea originally proposed by Joseph Poon and Thaddeus Dryja in \cite{RefWork:18}: the aim of this construction is to improve the well known scalability problem of Bitcoin through the so called layer 2 solutions. The name comes from the fact that they do not scale on chain\footnote{It is nearly impossible for Bitcoin to reach the transaction volume of centralized circuits like Visa: Bitcoin processes about ten transactions per second (tps), while Visa has been able to handle a peak of 47000 tps. It means that Visa is around 5000 times better than Bitcoin in this regard: an on-chain scale would result in a bloat of the blockchain size.}, but rather suggest the implementation of other protocols to handle off-chain transactions. The blockchain is seen as a court to which it is necessary to resort only in controversial situations or to close the channel. Although other implementations have been suggested (e.g. the eltoo protocol\footnote{The Lightning Network enforces an honest behaviour under a threat; eltoo avoids this punitive logic enforcing the possibility to update the broadcast of an old transaction, but needs the deployment of the SIGHASH\_NOINPUT soft fork proposed in \cite{BIP5}. Moreover three transactions have to be committed to the blockchain to open and close any channel.} described in \cite{RefWork:19}), nowadays layer 2 solutions leverage the HTLC presented in Section \ref{atomic}. The idea is to create bidirectional channels between the participants that transact frequently: the Lightning Network can be seen as a routed path composed by these channels, in such a way that it is not necessary to open a new channel anytime two parties want to transact.
We start presenting the basic working of the Lightning Network, that could be of interest on its own. Since its inner working is sort of an extension of the one presented when dealing with atomic swaps (being the atomicity the core property to be preserved), we will give only a low level overview.
\\
First we consider the example of a single channel between Alice and Bob, then we will look at how different channels can be connected to create a multi-hop payment channel.
\\
Alice and Bob open a channel committing some funds in 2-of-2 multi-signature address through the so called funding transaction. To avoid fund loss, they require the other party to sign an asymmetric commitment transaction before the funding transaction is broadcast to the Bitcoin network. These transactions spend the output of the funding transaction and lock the funds in two outputs: the first spending immediately what is owed to the other party, the second paying the party holding the transaction after a time lock. For example, the outputs of Bob's commitment transaction would look something like this:
\begin{itemize}
\item Output 0:
	\begin{lstlisting}[frame=single]
	OP_HASH160 <Alice's address> OP_EQUALVERIFY OP_CHECKSIG\end{lstlisting}

\item Output 1:
	\begin{lstlisting}[frame=single]
	OP_IF
		OP_HASH160 <revocation address>
	OP_ELSE
		<num> OP_CHECKSEQUENCEVERIFY OP_DROP OP_HASH160 <Bob's address>
	OP_ENDIF
	OP_EQUALVERIFY OP_CHECKSIG\end{lstlisting}
\end{itemize}
In Alice's transaction the roles of the two parties are exchanged. These transactions are signed by the other party, so that at any time the holder can also sign and broadcast: the revocation address is required to update the state of the channel, since its presence prevents the broadcast of an old state that is economically more appealing. This is a key problem for payment channels: any signed commitment transaction could be broadcast and the blockchain is not amendable, thus it is fundamental to prevent old commitment transactions from being broadcast (there is an economic incentive for the party that spent some money in the payment channel to broadcast an older version where he has more money). The revocation address is linked to a combination of Alice's public key and a revocation public key (revocation address = RIPEMD160(SHA-256($Q_A + Q_{rev}$))): through this mechanism, when Bob gives Alice the secret revocation key $q_{rev}$, by adding it to its private key only she is able to retrieve the funds locked in Output 1 before the lock time has elapsed. In this way, if Bob broadcast an old state Alice has some time to take action and punish Bob retrieving all the funds: this is the threat enforcing an honest behaviour we were mentioning before. Old transactions are toxic, since an erroneous broadcast would result in the funds being lost: it is better to delete intermediate states. However, revocation is not automatic: Alice has to monitor the blockchain and the same holds true for Bob.
\\
Anytime they want to update the balance, they exchange the revocation keys and signatures for the new commitment transactions, that spends always from the original funding transaction.
\\
The closure of a channel could happen cooperatively, so that the two parties cooperate creating a transaction with the correct balance but without any time lock, or not, meaning that one of the parties broadcast a commitment transaction for which the other party has not the revocation key: the drawback in this case is that he will need to wait for the lock time to expire.

\bigskip
\noindent
Now that we have seen the basic idea behind bidirectional channels, we can study their routing. Such a construction creates multi-hop payment channels, for which HTLC are needed: this contract ensures the atomicity of all the payments along the path.
\\
Consider the situation in which Alice wants to pay Carol 1 BTC. There is not an open channel between them: they could open one committing to the blockchain and consequently paying the associated fees, but a better idea is to rely on the Lightning Network. It automatically finds a path going from Alice to Carol taking advantage of already opened channels. In our example we consider the channels Alice-Bob and Bob-Carol.
\\
Alice's Lightning Network node (LN node, not to be confused with the Bitcoin node) needs to find a proper path connecting her and Carol. Notice that she is the only one knowing this path: every other participant knows only the previous and the following nodes\footnote{Such a situation is achieved through the so called onion routing.}. Obviously Carol knows that Alice has to pay her: for this reason she generates a secret $r$ and sends its hash $H_r = \text{hash}(r)$ to Alice. The atomicity of all the transactions is ensured by this hash value. At this point Alice constructs an HTLC paying to the hash $H_r$: the output of the transaction has to be slightly greater than 1 BTC (e.g. 1.001 BTC), so that the participants in the channel are rewarded with a small fee for the participation. Alice gives the HTLC to Bob, that updates the balance in the channel: Alice's balance decreases but Bob's does not increase; this is due to the fact that Alice's funds are committed in the HTLC and Bob can redeem them only knowing $r$. The HTLC provides a lock time refund logic, so that Bob has a limited amount of time to learn the secret. For this reason he constructs another HTLC updating the state of his channel with Carol, the logic being the same as above: he locks 1 BTC (he takes for himself 0.001 BTC as a fee) contingent to the revelation of the $H_r$'s preimage, with a smaller time lock with respect to the previous contract. The smaller time lock gives Bob enough time to take the coins from Alice's HTLC in case $r$ is revealed by Carol. At this point Carol has secret $r$ and can redeem the funds: she could either send the HTLC on-chain revealing $r$ and closing the channel with Bob, or she can simply reveal the secret to Bob and update the balance of the channel. The same holds true for Bob, that has incentives to reveal $r$ to Alice (remember that he earned a small fee). The secret acts as a sort of receipt for Alice, telling her that the payment has been successful.

\bigskip
\noindent
In the non cooperative case, these transactions go on-chain and are easily identifiable for blockchain observers, leading to a non negligible lack of privacy. This issue can be avoided through adaptor signatures\footnote{A much thorough discussion can be found in \cite{RefWork:17}.}. Instead of using $H_r$, Alice would require public keys $T_B$ and $T_C$ both from Bob and Carol (a unique offset could be used, but relying on one for participant allows reblinding of the offset). The funds of her transaction would be locked requiring a 2-of-2 Schnorr multi-signature: during the signature procedure she requires from Bob an adaptor signature with public offset $T_B + T_C$, so that Bob cannot provide a valid signature not knowing $t_C$. Similarly, Bob sends coins to Carol demanding for an adaptor signature with $T_C$ as offset. At this point,
Carol can produce a valid signature knowing $t_C$: she would grab the funds, revealing $t_C$ (either by publishing on-chain or by telling directly to Bob) and thus allowing Bob to do the same with Alice's transaction. Notice that for this construction to work it is necessary to include a lock time refund logic.
\\
Beyond the usual efficiency and privacy benefits,we have seen that the secret values used as offset can be reblinded between hops, allowing long chains of transactions to be made atomic while even the participants cannot identify which transactions are part of the chain. This is in sharp contrast with the HTLC based channels: although Alice does not reveal the path, all the members have the same hash and can collude to find out the nodes contributing to the channel.


\chapter{Approximate string matching}

\section{Edit (Levensthein) distance}

\begin{equation*}
  \qquad\operatorname{d}_{t,p}(i,j) =
  \begin{cases}
    \max(i,j) & \text{ if } \min(i,j)=0, \\
    \min
      \begin{cases}
        \operatorname{d}_{t,p}(i-1,j) + 1 \\
        \operatorname{d}_{t,p}(i,j-1) + 1 \\
        \operatorname{d}_{t,p}(i-1,j-1) + 1_{(t_i \neq p_j)}
      \end{cases} & \text{ otherwise.}
  \end{cases}
\end{equation*}

\begin{table}
  \begin{center}
    \begin{tabular}{c|ccccccc}
                  &\texttt{-}		&\texttt{a}		&\texttt{g}		&\texttt{t}		&\texttt{c}		&\texttt{a}		&\texttt{g}\\
      \hline
      \texttt{-}	&\tm{l10}0\tm{r10}  &\tm{l11}1\tm{r11}	&\tm{l12}2\tm{r12}  &\tm{l13}3\tm{r13}  &\tm{l14}4\tm{r14}	&\tm{l15}5\tm{r15}	&\tm{l16}6\tm{r16}\\[2px]
      \texttt{g}	&\tm{l20}1\tm{r20}	&\tm{l21}1\tm{r21}	&\tm{l22}1\tm{r22}	&\tm{l23}2\tm{r23}	&\tm{l24}3\tm{r24}	&\tm{l25}4\tm{r25}	&\tm{l26}5\tm{r26}\\[2px]
      \texttt{a}	&\tm{l30}2\tm{r30}	&\tm{l31}1\tm{r31}	&\tm{l32}2\tm{r32}	&\tm{l33}2\tm{r33}	&\tm{l34}3\tm{r34}	&\tm{l35}3\tm{r35}	&\tm{l36}4\tm{r36}\\[2px]
      \texttt{t}	&\tm{l40}3\tm{r40}	&\tm{l41}2\tm{r41}	&\tm{l42}2\tm{r42}	&\tm{l43}2\tm{r43}	&\tm{l44}3\tm{r44}	&\tm{l45}4\tm{r45}	&\tm{l46}4\tm{r46}\\[2px]
      \texttt{c}	&\tm{l50}4\tm{r50}	&\tm{l51}3\tm{r51}	&\tm{l52}3\tm{r52}	&\tm{l53}3\tm{r53}	&\tm{l54}2\tm{r54}	&\tm{l55}3\tm{r55}	&\tm{l56}4\tm{r56}\\[2px]
      \texttt{a}	&\tm{l60}5\tm{r60}  &\tm{l61}4\tm{r61}	&\tm{l62}4\tm{r62}	&\tm{l63}4\tm{r63}	&\tm{l64}3\tm{r64}	&\tm{l65}2\tm{r65}	&\tm{l66}3\tm{r66}\\[2px]
    \end{tabular}
%    \begin{tikzpicture}
%      [
%        remember picture,
%        overlay,
%        -latex,
%        shorten >=2pt,
%        shorten <=2pt
%      ]
%      \draw[green] ([yshift=0.5ex]{pic cs:l11}) -- ([yshift=0.5ex]{pic cs:r10});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l12}) -- ([yshift=0.5ex]{pic cs:r11});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l13}) -- ([yshift=0.5ex]{pic cs:r12});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l14}) -- ([yshift=0.5ex]{pic cs:r13});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l15}) -- ([yshift=0.5ex]{pic cs:r14});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l16}) -- ([yshift=0.5ex]{pic cs:r15});
%
%      \draw[green] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r20}) -- ([xshift=-0.5ex]{pic cs:r10});
%      \draw[blue] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r30}) -- ([xshift=-0.5ex]{pic cs:r20});
%      \draw[blue] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r40}) -- ([xshift=-0.5ex]{pic cs:r30});
%      \draw[blue] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r50}) -- ([xshift=-0.5ex]{pic cs:r40});
%      \draw[blue] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r60}) -- ([xshift=-0.5ex]{pic cs:r50});
%
%      \draw[green] ([yshift=1.0ex]{pic cs:l21}) -- ([yshift=0.0ex]{pic cs:r10});
%      \draw[green] ([yshift=1.0ex]{pic cs:l22}) -- ([yshift=0.0ex]{pic cs:r11});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l23}) -- ([yshift=0.5ex]{pic cs:r22});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l24}) -- ([yshift=0.5ex]{pic cs:r23});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l25}) -- ([yshift=0.5ex]{pic cs:r24});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l26}) -- ([yshift=0.0ex]{pic cs:r15});
%
%      \draw[green] ([yshift=1.0ex]{pic cs:l31}) -- ([yshift=0.0ex]{pic cs:r20});
%      \draw[green] ([yshift=1.0ex]{pic cs:l32}) -- ([yshift=0.0ex]{pic cs:r21});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l33}) -- ([yshift=0.0ex]{pic cs:r22});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l34}) -- ([yshift=0.0ex]{pic cs:r23});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l35}) -- ([yshift=0.0ex]{pic cs:r24});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l36}) -- ([yshift=0.5ex]{pic cs:r35});
%
%      \draw[blue] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r41}) -- ([xshift=-0.5ex]{pic cs:r31});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l42}) -- ([yshift=0.0ex]{pic cs:r31});
%      \draw[green] ([yshift=1.0ex]{pic cs:l43}) -- ([yshift=0.0ex]{pic cs:r32});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l44}) -- ([yshift=0.0ex]{pic cs:r33});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l45}) -- ([yshift=0.0ex]{pic cs:r34});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l46}) -- ([yshift=0.0ex]{pic cs:r35});
%
%      \draw[blue] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r51}) -- ([xshift=-0.5ex]{pic cs:r41});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l52}) -- ([yshift=0.0ex]{pic cs:r41});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l53}) -- ([yshift=0.0ex]{pic cs:r42});
%      \draw[green] ([yshift=1.0ex]{pic cs:l54}) -- ([yshift=0.0ex]{pic cs:r43});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l55}) -- ([yshift=0.5ex]{pic cs:r54});
%      \draw[blue] ([yshift=0.5ex]{pic cs:l56}) -- ([yshift=0.5ex]{pic cs:r55});
%
%      \draw[blue] ([yshift=1.0ex]{pic cs:l61}) -- ([yshift=0.0ex]{pic cs:r50});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l62}) -- ([yshift=0.0ex]{pic cs:r51});
%      \draw[blue] ([yshift=1.0ex]{pic cs:l63}) -- ([yshift=0.0ex]{pic cs:r52});
%      \draw[blue] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r64}) -- ([xshift=-0.5ex]{pic cs:r54});
%      \draw[green] ([yshift=1.0ex]{pic cs:l65}) -- ([yshift=0.0ex]{pic cs:r54});
%      \draw[green] ([yshift=0.5ex]{pic cs:l66}) -- ([yshift=0.5ex]{pic cs:r65});
%
%      \draw[green] ([yshift=1.0ex,xshift=-0.5ex]{pic cs:r32}) -- ([xshift=-0.5ex]{pic cs:r22});
%      \draw[green] ([yshift=0.5ex]{pic cs:l32}) -- ([yshift=0.5ex]{pic cs:r31});
%    \end{tikzpicture}
  \end{center}
  \caption{Edit distance between $t=\texttt{agtcag}$ a $p=\texttt{gatca}$.}
\end{table}

\clearpage
\section{Weighted edit distance}

\begin{equation*}
  \qquad\operatorname{d}_{t,p}(i,j) =
  \begin{cases}
    0 & \text{ if } i=0 \land j = 0,\\
    {d}_{t,p}(i-1,0) + D(t_i) & \text{ if } j=0 \land i > 0, \\
    {d}_{t,p}(0,j-1) + I(p_j) & \text{ if } i=0 \land j > 0, \\
    \min
      \begin{cases}
        \operatorname{d}_{t,p}(i-1,j) + D(t_i) \\
        \operatorname{d}_{t,p}(i,j-1) + I(p_j) \\
        \operatorname{d}_{t,p}(i-1,j-1) + R(p_j,t_i)_{(t_i \neq p_j)}
      \end{cases} & \text{ otherwise.}
  \end{cases}
\end{equation*}

\begin{table}
  \begin{center}
    \begin{tabular}{cc}
      \begin{tabular}[t]{c|cccc}
        R   &\texttt{a} &\texttt{g} &\texttt{c} &\texttt{t}\\\hline
        \texttt{a}  &-   &2   &3   &4\\
        \texttt{g}  &2   &-   &6   &2\\
        \texttt{c}  &2   &5   &-   &1\\
        \texttt{t}  &5   &2   &1   &-\\\hline
        I   &5 &2 &4 &3\\
        D   &2 &5 &3 &4\\
      \end{tabular}
      \quad
      \begin{tabular}[t]{c|ccccccc}
        DP          &\texttt{-}		&\texttt{a}		&\texttt{g}		&\texttt{t}		&\texttt{c}		&\texttt{a}		&\texttt{g}\\
        \hline
        \texttt{-}	&\tm{l10} 0\tm{r10}  &\tm{l11} 2\tm{r11}	&\tm{l12} 7\tm{r12} &\tm{l13}11\tm{r13} &\tm{l14}14\tm{r14}	&\tm{l15}16\tm{r15}	&\tm{l16}21\tm{r16}\\[2px]
        \texttt{g}	&\tm{l20} 2\tm{r20}	 &\tm{l21} 2\tm{r21}	&\tm{l22} 2\tm{r22}	&\tm{l23} 6\tm{r23}	&\tm{l24} 9\tm{r24}	&\tm{l25}11\tm{r25}	&\tm{l26}16\tm{r26}\\[2px]
        \texttt{a}	&\tm{l30} 7\tm{r30}	 &\tm{l31} 2\tm{r31}	&\tm{l32} 4\tm{r32}	&\tm{l33} 6\tm{r33}	&\tm{l34} 9\tm{r34}	&\tm{l35} 9\tm{r35}	&\tm{l36}13\tm{r36}\\[2px]
        \texttt{t}	&\tm{l40}10\tm{r40}	 &\tm{l41} 5\tm{r41}	&\tm{l42} 4\tm{r42}	&\tm{l43} 4\tm{r43}	&\tm{l44} 7\tm{r44}	&\tm{l45} 9\tm{r45}	&\tm{l46}11\tm{r46}\\[2px]
        \texttt{c}	&\tm{l50}14\tm{r50}	 &\tm{l51}9\tm{r51}	&\tm{l52} 8\tm{r52}	&\tm{l53} 5\tm{r53}	&\tm{l54} 4\tm{r54}	&\tm{l55} 6\tm{r55}	&\tm{l56}11\tm{r56}\\[2px]
        \texttt{a}	&\tm{l60}19\tm{r60}  &\tm{l61}14\tm{r61}	&\tm{l62}11\tm{r62}	&\tm{l63} 10\tm{r63}	&\tm{l64} 8\tm{r64}	&\tm{l65} 4\tm{r65}	&\tm{l66}8\tm{r66}\\[2px]
      \end{tabular}
    \end{tabular}
  \end{center}
  \caption{Weighted edit distance between $t=\texttt{agtcag}$ a $p=\texttt{gatca}$.}
\end{table}

\clearpage
\section{Needleman--Wunsch}

\begin{equation*}
  \qquad\operatorname{d}_{t,p}(i,j) =
  \begin{cases}
    0 & \text{ if } i=0 \land j = 0,\\
    i \cdot c & \text{ if } j=0 \land i > 0, \\
    j \cdot c & \text{ if } i=0 \land j > 0, \\
    \max
      \begin{cases}
        \operatorname{d}_{t,p}(i-1,j) + c \\
        \operatorname{d}_{t,p}(i,j-1) + c \\
        \operatorname{d}_{t,p}(i-1,j-1) + S(p_j,t_i)
      \end{cases} & \text{ otherwise.}
  \end{cases}
\end{equation*}

\begin{table}
  \begin{center}
    \begin{tabular}{cc}
      \begin{tabular}[t]{c|cccc}
        S   &\texttt{a} &\texttt{g} &\texttt{c} &\texttt{t}\\\hline
        \texttt{a}  &10   &-1   &-3   &-4\\
        \texttt{g}  &-1   &7    &-5   &-3\\
        \texttt{c}  &-3   &-5   &9    &0\\
        \texttt{t}  &-4   &-3   &0    &8\\\hline
        c  & -5 \\
      \end{tabular}
      \quad
      \begin{tabular}[t]{c|ccccccc}
        DP          &\texttt{-}		&\texttt{a}		&\texttt{g}		&\texttt{t}		&\texttt{c}		&\texttt{a}		&\texttt{g}\\
        \hline
        \texttt{-}	&\tm{l10}  0\tm{r10}  &\tm{l11} -5\tm{r11}	&\tm{l12}-10\tm{r12}    &\tm{l13}-15\tm{r13}    &\tm{l14}-20\tm{r14}	&\tm{l15}-25\tm{r15}	&\tm{l16}-30\tm{r16}\\[2px]
        \texttt{g}	&\tm{l20} -5\tm{r20}  &\tm{l21} -1\tm{r21}	&\tm{l22}  2\tm{r22}	&\tm{l23} -3\tm{r23}	&\tm{l24} -8\tm{r24}	&\tm{l25}-13\tm{r25}	&\tm{l26}-18\tm{r26}\\[2px]
        \texttt{a}	&\tm{l30}-10\tm{r30}  &\tm{l31}  5\tm{r31}	&\tm{l32}  0\tm{r32}	&\tm{l33} -2\tm{r33}	&\tm{l34} -6\tm{r34}	&\tm{l35}  2\tm{r35}	&\tm{l36} -3\tm{r36}\\[2px]
        \texttt{t}	&\tm{l40}-15\tm{r40}  &\tm{l41}  0\tm{r41}	&\tm{l42}  2\tm{r42}	&\tm{l43}  8\tm{r43}	&\tm{l44}  3\tm{r44}	&\tm{l45} -2\tm{r45}	&\tm{l46} -1\tm{r46}\\[2px]
        \texttt{c}	&\tm{l50}-20\tm{r50}  &\tm{l51} -5\tm{r51}	&\tm{l52} -3\tm{r52}	&\tm{l53}  3\tm{r53}	&\tm{l54}  17\tm{r54}	&\tm{l55} 12\tm{r55}	&\tm{l56} 7\tm{r56}\\[2px]
        \texttt{a}	&\tm{l60}-25\tm{r60}  &\tm{l61}-10\tm{r61}	&\tm{l62} -6\tm{r62}	&\tm{l63} -2\tm{r63}	&\tm{l64} 12\tm{r64}	&\tm{l65}  27\tm{r65}	&\tm{l66}  22\tm{r66}\\[2px]
      \end{tabular}
    \end{tabular}
  \end{center}
  \caption{Needleman--Wunsch price of alignment between $t=\texttt{agtcag}$ a $p=\texttt{gatca}$.}
\end{table}

\clearpage
\section{Algorithm implementations}
\cpplistings{tut6/levensthein}{Implementation of Levenshtein distance algorithm.}{{17-44}}
  \clistings{tut6/distance}{Implementation of Levenshein distance algorithm with backtracking.}{{23-61}}
\cpplistings{tut6/wed}{Implementation of Weighted edit distance algorithm.}{{89-134}}
\cpplistings{tut6/nw}{Implementation of Needleman--Wunsch algorithm.}{{73-106}}


%---------------------------------------------------------------------
\section{Probability Calculation}
\label{full}

\subsection{Differential Cross Section at the Parton Level}

The matrix element analysis technique reconstructs each event to the
final state four-vectors to evaluate the signal and background leading
order matrix element. The following sections derive the signal and
background probabilities starting from the final state at the parton
level and then relating these objects to the physical quantities
measured in the detector. The following also assumes a lepton,
neutrino, and two quarks in the final state.

The probability density for a process to occur at a hadron-hadron
collider is given as an integral of the hard-scatter differential
cross section over all possible ways of producing the process from the
quarks and gluons inside the hadron. This probability density, shown
below, is a convolution of the hard scatter differential cross section
with a parton distribution function for each of the two partons from
the hadrons with an integral over all possible momentum fractions
$x_{i}, x_{j}$ from each initial parton.
\begin{equation}
{\cal P}(\vec{y}) = \frac{1}{\sigma} \sum_{i,j}
\int f_{i}(q_{1}, Q^{2})dq_{1}
\times f_{j}(q_{2}, Q^{2})dq_{2}
\times d\sigma_{hs,ij}(\vec{y})
\end{equation}
\noindent where the normalization constant $\sigma$ is defined as
integral of the differential cross section over the initial- and
final-state phase spac:
\begin{equation}
\label{ds}
\sigma = \int  \sum_{i,j}
\int f_{i}(q_{1}, Q^{2})dq_{1}
\times f_{j}(q_{2}, Q^{2})dq_{2}
\times \pderiv{\sigma_{hs,ij}(\vec{y})}{\vec{y}} d\vec{y}
\end{equation}
\noindent and finally, the hard-scatter differential cross section is
defined as the product of the final state phase space factor, the
square of the matrix element amplitude and an overall flux factor:
\begin{equation}
d\sigma_{hs} = \frac{(2\pi)^4}{4}
\frac{{|\cal M|}^{2}}
{\sqrt{(q_{1}q_{2})^2 - m_{1}^2 m_{2}^2}}
\frac{d^{3}p_{1}}{(2\pi)^3 2E_{1}}
\frac{d^{3}p_{2}}{(2\pi)^3 2E_{2}}
\frac{d^{3}p_{\ell}}{(2\pi)^3 2E_{\ell}}
\frac{d^{3}p_{\nu}}{(2\pi)^3 2E_{\nu}}
\delta^{4}(q_{1}q_{2};p_{1},p_{2},p_{\ell},p_{\nu})
\end{equation}

\subsection{Evaluating the Hard Scatter Differential Cross Section}

The following section evaluates the differential cross section shown
in Eq.~\ref{ds} given a set of inital and final state four-vectors.

The first assumption made is that all collisions occur along the beam
axis with no net transverse momentum. This means the initial state
four vectors can be written as
\begin{equation}
q_{1} = ( E_{beam} x_{1}, 0, 0, E_{beam} x_{1} )
\end{equation}
\begin{equation}
q_{2} = ( E_{beam} x_{2}, 0, 0, -E_{beam} x_{2} )
\end{equation}
\noindent The next assumption is that all particle masses are known
and are negligible compared to their energies and thus can be ignored
for this calculation. The flux factor (shown below) in the hard
scatter cross section can now be written in terms in the two momentum
fractions of the incoming partons:
\begin{equation}
\frac{1}{\sqrt{(q_{1}q_{2})^2 - m_{1}^2m_{2}^2}} \rightarrow
\frac{1}{\sqrt{(q_{1}q_{2})^2}} \rightarrow
\frac{1}{2E_{beam}x_{1}x_{2}}
\end{equation}
\noindent For the remainder of the note, the following notation will
be used to distinquish quarks, leptons, and neutrinos: $p_{\ell}$ is
the momemtum of the lepton, $p_{1,2}$ is the momentum of the first and
second final state partons, and $p_{\nu}$ is the neutrino
momentum. Because the phase space is written in terms of rectangular
coordinates, the next step towards the final differential cross
section equation is to redefine the phase space factors in terms of
spherical coordiniates. This is done for all final state particles
except the neutrino for reasons that will be clear later in the
document.
\begin{eqnarray}
d\Phi_{4} =
\frac{d^{3}p_{1}}{(2\pi)^3 2E_{1}}
\frac{d^{3}p_{2}}{(2\pi)^3 2E_{2}}
\frac{d^{3}p_{\ell}}{(2\pi)^3 2E_{\ell}}
\frac{d^{3}p_{\nu}}{(2\pi)^3 2E_{\nu}} \delta^{4}
\rightarrow \\
\frac{1}{16(2\pi)^{12}}
\frac{|p_{1}|^{2}d|p_{1}|d\Omega_{1}}{E_{1}}
\frac{|p_{2}|^{2}d|p_{2}|d\Omega_{2}}{E_{2}}
\frac{|p_{\ell}|^{2}d|p_{\ell}|d\Omega_{\ell}}{E_{\ell}}
\frac{d^{x}_{\nu} d^{y}_{\nu} d^{z}_{\nu}}{E_{\nu}}\delta^{4}
%\frac{d^{3}p_{1}}{(2\pi)^3 2E_{1}} \frac{d^{3}p_{2}}{(2\pi)^32E_{2}} \frac{d^{3}p_{\ell}}{(2\pi)^3 2E_{\ell}}
%\frac{d^{3}p_{\nu}}{(2\pi)^3 2E_{\nu}} \delta^{4} \righarrow
%\frac{1}{16(2\pi)^{12}}
\end{eqnarray}
\noindent To summarize, the full hard scatter differential cross
section is now
\begin{equation}
\label{dhs}
d\sigma_{hs} = \frac{1}{128(2\pi)^{8}E_{beam}}
\frac{{|\cal M|}^{2}}{2x_{1}x_{2}}
\frac{|p_{1}|^{2}d|p_{1}|d\Omega_{1}}{E_{1}}
\frac{|p_{2}|^{2}d|p_{2}|d\Omega_{2}}{E_{2}}
\frac{|p_{\ell}|^{2}d|p_{\ell}|d\Omega_{\ell}}{E_{\ell}}
\frac{d^{x}_{\nu} d^{y}_{\nu} d^{z}_{\nu}}{E_{\nu}} \delta^{4}
\end{equation}

\subsection{Evaluating the Hadron-Hadron Differential Cross Section}

The next step to writing the full hadron-hadron differential cross
section is to rewrite Eq.~\ref{dhs} such that any integration over the
phase space will remove the four-dimensional delta function required
for energy and momentum conservation. The delta function is currently
written such that it will vanish only over integrations of total
$p_{x}, p_{y}, p_{z}$, and $E$. Because there was an original
assumption of no net transverse momentum in the collision, the total
$p_{x}$ and $p_{y}$ can be solved for the neutrino transverse
momentum.
\begin{eqnarray}
\sum_{i}P^{x}_{i} =
p^{x}_{1} + p^{x}_{2} + p^{x}_{\ell} + p^{x}_{\nu} = 0
\rightarrow p^{x}_{\nu} =
- p^{x}_{1} - p^{x}_{2} - p^{x}_{\ell} \\
\sum_{i}P^{y}_{i} =
p^{y}_{1} + p^{y}_{2} + p^{y}_{\ell} + p^{y}_{\nu} = 0
\rightarrow p^{y}_{\nu} =
- p^{y}_{1} - p^{y}_{2} - p^{y}_{\ell}
\end{eqnarray}
\noindent The total $p_{z}$ and requirement can be rewritten in terms
of the intial parton's momemtum fraction and the other final state
partons' $z$ momenta and thus solve for the neutrino $p_{z}$:
\begin{eqnarray}
\nonumber
\sum_{i}P^{z}_{i} =
p^{z}_{1} + p^{z}_{2} + p^{z}_{\ell} + p^{z}_{\nu} -
E_{beam}x_{1} + E_{beam}x_{2} = 0 \rightarrow \\
p^{z}_{\nu} =
- E_{beam}(x_{1} - x_{2}) - p^{z}_{1} - p^{z}_{2} - p^{z}_{\ell}
\end{eqnarray}
\noindent Finally, the total energy delta function implies the
following:
\begin{equation}
E_{beam}x_{1} + E_{beam}x_{2} = E_{1} + E_{2} + E_{\ell} + E_{\nu}
\end{equation}

At this point, is it useful to rewrite the full differential cross
section at the parton level:
\begin{eqnarray}
\nonumber
d\sigma(\vec{y}) = \sum_{i,j} \int f_{i}(x_{1}, Q^{2})dx_{1}
\times f_{j}(x_{2}, Q^{2})dx_{2}
\times \frac{1}{128(2\pi)^{8}E_{beam}}
\frac{{|\cal M|}^{2}}{2x_{1}x_{2}} \times \\
\nonumber
\frac{|p_{1}|^{2}d|p_{1}|d\Omega_{1}}{E_{1}}
\frac{|p_{2}|^{2}d|p_{2}|d\Omega_{2}}{E_{2}}
\frac{|p_{\ell}|^{2}d|p_{\ell}|d\Omega_{\ell}}{E_{\ell}}
\frac{d^{x}_{\nu} d^{y}_{\nu} d^{z}_{\nu}}{E_{\nu}} \times \\
\nonumber
\delta(p^{x}_{\nu} + p^{x}_{1} + p^{x}_{2} + p^{x}_{\ell}) \times \\
\nonumber
\delta(p^{y}_{\nu} + p^{y}_{1} + p^{y}_{2} + p^{y}_{\ell}) \times \\
\nonumber
\delta(p^{z}_{\nu} + E_{beam}(x_{1} - x_{2}) + p^{z}_{1}
+ p^{z}_{2} + p^{z}_{\ell}) \times \\
\delta(E_{beam}x_{1} + E_{beam}x_{2} - E_{1} - E_{2}
- E_{\ell} - E_{\nu})
\end{eqnarray}

The next step is to rewrite the integrational variables, $x_{1}$ and
$x_{2}$, in terms of the total energy and total $p_{z}$:
\begin{eqnarray}
\label{x1}
x_{1} = \frac{E_{tot} + p^{z}_{tot}}{2E_{beam}} \\
\label{x2}
x_{2} = \frac{E_{tot} - p^{z}_{tot}}{2E_{beam}}
\end{eqnarray}
\noindent Now, the integration over $x_{1}$ and $x_{2}$ can be
rewritten in terms of $E_{tot}$ and $p_{z}$:
\begin{eqnarray}
dx_{1}dx_{2} =
\frac{1}{J(x_{1},x_{2};E_{tot},p^{z}_{tot})}dE_{tot}dp^{z}_{tot} \\
J(x_{1},x_{2};E_{tot},p^{z}_{tot}) = 2E^{2}_{beam}
\end{eqnarray}
\noindent At this point the integration over the total energy and
$p_{z}$ will constrain the two incoming partons' momentum fractions
through Eq.~\ref{x1} and \ref{x2}.

The full differential cross section at the parton level can now be
written as
\begin{eqnarray}
\nonumber
d\sigma(\vec{y}) = \sum_{i,j} \int f_{i}(x_{1}, Q^{2})
\times
f_{j}(x_{2}, Q^{2}) \times \frac{1}{128(2\pi)^{8}E_{beam}}
\frac{{|\cal M|}^{2}}{2x_{1}x_{2}} \times \\
\nonumber
\frac{|p_{1}|^{2}d|p_{1}|d\Omega_{1}}{E_{1}}
\frac{|p_{2}|^{2}d|p_{2}|d\Omega_{2}}{E_{2}}
\frac{|p_{\ell}|^{2}d|p_{\ell}|d\Omega_{\ell}}{E_{\ell}}
\frac{d^{x}_{\nu} d^{y}_{\nu} d^{z}_{\nu}}{E_{\nu}} \times \\
\int \frac{1}{2E^{2}_{beam}} dp^{z}_{tot}
\end{eqnarray}
\noindent where the implicit integration over the four dimensional
delta function yields the following formulas for the neutrino four
vector and the incoming partons' momentum fraction in terms of the
remaining differential variables.
\begin{eqnarray}
p^{x}_{\nu} = - p^{x}_{1} - p^{x}_{2} - p^{x}_{\ell} \\
p^{y}_{\nu} = - p^{y}_{1} - p^{y}_{2} - p^{y}_{\ell} \\
p^{z}_{\nu} = - p^{z}_{tot} - p^{z}_{1} - p^{z}_{2} - p^{z}_{\ell} \\
x_{1} = \frac{E_{1} + E_{2} + E_{\ell} + E_{\nu} + p^{z}_{tot}}
{2E_{beam}} \\
x_{2} = \frac{E_{1} + E_{2} + E_{\ell} + E_{\nu} - p^{z}_{tot}}
{2E_{beam}}
\end{eqnarray}

\subsection{Relating Reconstructed Objects to Partons}

The previous sections have calculated the differential cross section
for a hadron-hadron collision producing a lepton, neutrino, and two
partons in the final state. These particles are not exactly what is
measured in the detector and thus it is necessary to relate
quantities. To do this, the differential cross section is convoluted
with a function, $W(\vec{x}, \vec{y})$, which is the probability of
producing a final state, $\vec{y}$, and observed state, $\vec{x}$, in
the detector. The resulting differential cross section is then
integrated over the final state phase space, $d\vec{y}$:
\begin{equation}
\pderiv{\sigma^{'}(\vec{x})}{\vec{x}} =
\int \pderiv{\sigma(\vec{y})}{\vec{y}} W(\vec{x}, \vec{y}) d\vec{y}
\end{equation}
\noindent where the function $W(\vec{x}, \vec{y})$ is assumed to be
factorizable for each measured object:
\begin{equation}
W(\vec{x}, \vec{y}) = \prod_{i} W_{i}(\vec{x_{i}}, \vec{y_{i}})
\end{equation}

\subsubsection{Jets}

The transfer function for jets measured in the calorimter is assumed
to only be a function of the relative energy difference between the
two objects and all angles are assumed to be well measured:
\begin{equation}
W_{jet}(\vec{x}_{jet}, \vec{y}_{parton}) = W(E_{jet} -
E_{parton}) \times \delta(\Omega_{jet} - \Omega_{parton})
\end{equation}
\noindent where $W(E_{jet} - E_{parton})$ is parametrized using the
following functional form:
\begin{equation}
W(E_{jet} - E_{parton}) = \frac{e^{-\frac{(E_{jet}
- E_{parton} - p_{1})^{2}}{2p^{2}_{2}}} + p_{3}e^{-\frac{(E_{jet}
- E_{parton} - p_{4})^{2}}{2p^{5}_{2}}}}{2\pi(p_{2} + p_{3}p_{5})}
\end{equation}
\noindent where $p_{i} = \alpha_{i} + \beta_{i} \times E_{parton}$.
The five $\alpha$ and five $\beta$ parameters are determined by
minimizing a likelihood formed by measuring the parton energy in Monte
Carlo and the matched jet energy also in Monte Carlo. The parameters
used for this analysis were determined in several regions of the
calorimeter to account for the resolution differences in the detector.

\subsubsection{Electrons}

The transfer function for electrons~\cite{ElectronTF} is assumed to be
solely a function of the reconstructed energy of the electron,
$E_{reco}$, the parton energy of the electron, $E_{parton}$, and
$\theta$, the production angle with respect to the beam axis:
\begin{equation}
W_{electron}(\vec{x}_{reco}, \vec{y}_{parton}) = W(E_{reco},
E_{parton}, \theta) \times \delta(\Omega_{reco} - \Omega_{parton})
\end{equation}
\noindent where $W(E_{reco}, E_{parton}, \theta)$ is parametrized
using the following functional form:
\begin{eqnarray}
W(E_{reco}, E_{parton}, \theta) & = &
\frac{1}{2\pi\sigma}\mathrm{exp}
[-\frac{(E_{reco} - E_{center})^{2}}{2\sigma^{2}}]\\
E_{center} & = &
1.0002 E_{parton} + 0.324\,{GeV}/c^2 \\
\sigma & = &
0.028 E_{center} \oplus \textrm{Sampling}(E_{center},
\eta) E_{center} \oplus 0.4 \\
\textrm{Sampling}(E, \theta) & = &
\left[\frac{0.164}{\sqrt{E}} + \frac{0.122}{E}\right]
\textrm{exp}\left[\frac{\textrm{p1}(E)}
{\textrm{sin}\theta}-\textrm{p1}(E)\right] \\
\textrm{p1}(E)& = & 1.35193 - \frac{2.09564}{E} - \frac{6.98578}{E^2}.
\end{eqnarray}

\subsubsection{Muons}

The transfer function for muons~\cite{MuonTF} is assumed to be a
function of
\begin{equation}
\Delta\left( \frac{q}{p_t}\right) =
\left( \frac{q}{p_t}\right)_{reco} -
\left( \frac{q}{p_t}\right)_{parton}
\end{equation}
\noindent and of $\eta_\mathrm{CFT}$,
\begin{equation}
W_{muon}(\vec{x}_{reco}, \vec{y}_{parton}) =
W\left(\Delta\left( \frac{q}{p_t}\right),
\eta_\mathrm{CFT}\right) \times
\delta(\Omega_{reco} - \Omega_{parton})
\end{equation}
\noindent where $W\left(\Delta\left( \frac{q}{p_t}\right),
\eta_\mathrm{CFT}\right)$ is parametrized using a single Gaussian:
\begin{equation}
W\left(\Delta\left( \frac{q}{p_t}\right), \eta_\mathrm{CFT}\right) =
\frac{1}{2\pi\sigma}\mathrm{exp}
\left\{-\frac{\left[\Delta
\left( \frac{q}{p_t} \right)\right]^2}
{2\sigma^2}\right\}
\end{equation}
\begin{equation}
\sigma  =  \left\{
\begin{array} {c@{\quad:\quad}l} \sigma_o &
|\eta_\mathrm{CFT}| \le \eta_o \\
\sqrt{\sigma^2_o + [c(|\eta_\mathrm{CFT}| - \eta_o)]^2} &
|\eta_\mathrm{CFT}| > \eta_o
\end{array} \right.
\end{equation}

\noindent There are three fitted parameters in the above equations:
$\sigma_o$, $c$, and $\eta_o$, each of which is actually fitted by two
sub-parameters:
\begin{equation}
par = par(0) + par(1) \cdot 1/p_t.
\end{equation}
\noindent Furthermore, these parameters are derived for four classes
of events: those that were from before or after the 2004 shutdown,
when the magnetic field strength changed, and in each run range, those
that have an SMT hit and those that do not.

As a simplification, we assume $q_{reco} = q_{parton}$, that is, we
do not consider charge misidentification

\subsection{Full Differential Cross Section and Normalization}

The full differential cross section at the detector object level can
now be written as
\begin{eqnarray}
\label{fullds}
\nonumber
\pderiv{\sigma^{'}(\vec{x})}{\vec{x}} =
\int dp^{z}_{tot}dq_{1}dq_{2}dp_{\ell} \sum_{i,j}
f_{i}(q_{1}, Q^{2}) \times f_{j}(q_{2}, Q^{2}) \\
\times \frac{1}{256(2\pi)^{8}E^{3}_{beam}}
\frac{{|\cal M|}^{2}}{2x_{1}x_{2}} \times
\frac{p_{1}^{2}}{E_{1}} \frac{p_{2}^{2}}{E_{2}}
\frac{p_{\ell}^{2}}{E_{\ell}} \frac{1}{E_{\nu}}
\times W_{Lepton}W_{Jet1}W_{Jet2}
\end{eqnarray}
\noindent The final step to evaluating the probability density is to
properly normalize the differential cross section in
Eq.~\ref{fullds}. This is done by integration of the differential
cross section over all possible states in the detector. Since the
event selection cuts will change the number events due to acceptance
losses, this must be accounted for in the overall normalization (cross
section) calculation. The total cross section is then written as
\begin{eqnarray}
\label{norm}
\nonumber
\sigma = \int \pderiv{\sigma^{'}(\vec{x})}{\vec{x}} d\vec{x} =
\int d\vec{x}dp^{z}_{tot}dq_{1}dq_{2}dp_{\ell} \sum_{i,j}
f_{i}(q_{1}, Q^{2}) \times f_{j}(q_{2}, Q^{2}) \\
\times \frac{1}{256(2\pi)^{8}E^{3}_{beam}}
\frac{{|\cal M|}^{2}}{2x_{1}x_{2}} \times
\frac{p_{1}^{2}}{E_{1}} \frac{p_{2}^{2}}{E_{2}}
\frac{p_{\ell}^{2}}{E_{\ell}} \frac{1}{E_{\nu}}
\times W_{Lepton}W_{Jet1}W_{Jet2} \times \Theta_{\rm{Cuts}}(\vec{x})
\end{eqnarray}


\chapter{Polyhedral Sets and Polyhedrally Constrained Languages}\label{chp:polyhedral}

In this chapter we introduce the family of \emph{polyhedrally constrained languages} which we use in the proof of \cref{thm:geodesic-growth}.
This family of languages is a generalisation of linearly constrained languages, as in \cref{defn:linearly-constrained-language}.
It is a result of \textcite{massazza1993} that the generating function of linearly constrained languages is holonomic (see~\cref{prop:lcl-is-holonomic}).
In \cref{prop:polyhedrally-constrained-is-holonomic}, we show that the family of polyhedrally constrained languages also have holonomic (multivariate) generating functions.

\Textcite{benson1983} introduced the concept of \emph{polyhedral sets} to compute the volume growth of virtually abelian groups, in particular, for each virtually abelian group \citeauthor{benson1983} constructed a polyhedral set whose (volume) generating function is the volume growth series of the group.
In \cref{sec:virtually-abelian-groups} we apply a similar argument to construct a \emph{polyhedrally constrained language} whose generating function is the geodesic growth series of a virtually abelian group.
We define and study the class of polyhedral sets in \cref{sec:polyhedral-sets}, and the family of polyhedrally constrained languages in \cref{sec:polyhedrally-constrained-languages}.

\section{Polyhedral Sets}\label{sec:polyhedral-sets}

A \emph{polyhedral set}, as we see in \cref{defn:polyhedral-set}, is a subset of $\mathbb{Z}^n$ that encodes the integer solutions to finitely many systems of linear equations, inequalities and congruences.
The class of polyhedral sets is closed under Boolean expressions, Cartesian products, and (inverse) mapping by integer affine transformation (see \cref{prop:affine-transforms-of-polyhedral-sets,prop:closure-properties-of-polyhedral-sets}).
The class of polyhedral sets and their closure properties are essential to our study of the language of geodesics for virtually abelian groups in \cref{sec:virtually-abelian-groups}.

\begin{definition}\label{defn:polyhedral-set}
A subset $\mathcal{E} \subseteq \mathbb{Z}^m$ is called an \emph{elementary region} if it can be expressed as
\[
	\left\{
		z \in \mathbb{Z}^m
	\, \middle\vert \,
		a\cdot z = b
	\right\},
	%
	\
	%
	\left\{
		z \in \mathbb{Z}^m
	\, \middle\vert \,
		a\cdot z > b
	\right\}
	%
	\text{ or }
	%
	\left\{
		z \in \mathbb{Z}^m
	\, \middle\vert \,
		a\cdot z \equiv b\ (\bmod\ c)
	\right\}
\]
for some $a \in \mathbb{Z}^m$ and $b,c\in \mathbb{Z}$ with $c > 0$.
A \emph{basic polyhedral set} is a finite intersection of elementary regions;
and a \emph{polyhedral set} is a finite disjoint union of basic polyhedral sets.
\end{definition}

From this definition we see that $\emptyset$ and $\mathbb{Z}^m$ are elementary regions, and that $\mathbb{N}^m$ is a basic polyhedral set.
In \cref{prop:closure-properties-of-polyhedral-sets} we see that the class of polyhedral sets is closed under Boolean expressions and Cartesian products.

\begin{proposition}[Proposition~13.1~and~Remark~13.2~in~\cite{benson1983}]\label{prop:closure-properties-of-polyhedral-sets}
	The class of polyhedral subsets of $\mathbb{Z}^m$ is{\tiny } closed under finite union, finite intersection and set difference.
	Moreover, the class of polyhedral sets is closed under Cartesian product.
\end{proposition}

A map $E \colon \mathbb{Z}^m \to \mathbb{Z}^n$ is an \emph{integer affine transform} if it can be written as $E(v) = vA + b$ where $A \in \mathbb{Z}^{m \times n}$ is a matrix and $b \in \mathbb{Z}^n$ is a vector.
In \cref{prop:affine-transforms-of-polyhedral-sets} we see that the class of polyhedral sets is closed under (inverse) mapping by integer affine transformations.

\begin{proposition}[Propositions~13.7~and~13.8~in~\cite{benson1983}]\label{prop:affine-transforms-of-polyhedral-sets}
	Suppose that $\mathcal{P} \subseteq \mathbb{Z}^m$ and $\mathcal{Q} \subseteq \mathbb{Z}^n$ are polyhedral sets, and $E\colon\mathbb{Z}^m\to\mathbb{Z}^n$ is an integer affine transform.
	Then, $E(\mathcal{P})$ and $E^{-1}(\mathcal{Q})$ are both polyhedral sets.
\end{proposition}

Notice that our definition of $n$-atoms and $n$-constraints in \cref{defn:n-constraints} is similar to that of elementary regions and polyhedral sets, respectively, without modular arithmetic.
From the closure properties in \cref{prop:closure-properties-of-polyhedral-sets} we see that $n$-constraints form a subclass of the polyhedral subsets of $\mathbb{Z}^n$.
It can be verified by the reader that, for each $n \geqslant 1$,
\[
	\{
		(x,0,0,\ldots,0) \in \mathbb{Z}^n
	\mid
		x \equiv 0\ (\bmod\ 2)
	\}
\]
is a polyhedral set but not an $n$-constraint, and thus the class of $n$-constraints form a proper subclass of the polyhedral subsets of $\mathbb{Z}^n$.
In the following section, we generalise the family of linearly constrained languages, defined in \cref{defn:linearly-constrained-language}, to the family of \emph{polyhedral constrained languages} which we use in the proof of \cref{thm:geodesic-growth}.

\section{Polyhedrally Constrained Languages}\label{sec:polyhedrally-constrained-languages}

In \cref{sec:constrained-languages}, we saw that a constrained language, $L(U,\mathcal{C})$, is the intersection of an unambiguous context-free language $U \subseteq \Sigma$ and the set of words whose Parikh images belong to a set $\mathcal{C} \subseteq \mathbb{Z}^{|\Sigma|}$.
Moreover, we defined the family of linearly constrained languages in \cref{defn:linearly-constrained-language} as the constrained languages where $\mathcal{C}$ is a $|\Sigma|$-constraint.
In this section we generalise this definition to the family of \emph{polyhedrally constrained languages} as follows.

\begin{definition}\label{defn:polyhedrally-constrained-language}
	A language is \emph{polyhedraly constrained} if it can be written as
	\[
		L(U,\mathcal{P})
		=
		\left\{
			w \in U \subseteq \Sigma^*
		\mid
			\Parikh_\Sigma(w) \in \mathcal{P}
		\right\}
	\]
	where $U$ is an unambiguous context-free language, and $\mathcal{P}$ is a polyhedral set.
\end{definition}

In \cref{sec:virtually-abelian-groups} we will not require the full power of polyhedrally constrained languages, in particular, we only require polyhedrally constrained languages $L(U,\mathcal{P})$ where $U$ is a regular language.
It can then be shown that such languages form a subfamily of the \emph{RCM languages} introduced by \textcite{castiglione2017}, moreover, they showed that the single-variable generating functions of these languages are holonomic.
In \cref{prop:polyhedrally-constrained-is-holonomic}, we show that the multivariate generating function of each polyhedrally constrained language is holonomic.
We make use of this characterisation in the proof of \cref{thm:geodesic-growth}.

\begin{proposition}\label{prop:polyhedrally-constrained-is-holonomic}
	The multivariate generating function of a polyhedrally constrained language is holonomic.
\end{proposition}

\begin{proof}
	Let $L(U,\mathcal{P}) \in \Sigma^*$ be a polyhedrally constrained language.
	From the definition of polyhedral sets, we may decompose $\mathcal{P} \subseteq \mathbb{Z}^{|\Sigma|}$ into a union of finitely many disjoint basic polyhedral sets
	$\mathcal{P} = \bigcup_{i=1}^L \mathcal{B}_i$.
	Moreover, each such basic polyhedral set $\mathcal{B}_i \subseteq \mathbb{Z}^{|\Sigma|}$ can be written as a finite intersection of elementary regions
	\begin{multline*}
		\mathcal{B}_i
		=
		\bigcap_{j = 1}^{K_{i,1}}
		\{
			v \in \mathbb{Z}^{|\Sigma|}
		\mid
			\alpha_{i,j} \cdot v = \beta_{i,j}
		\}
		\cap
		\bigcap_{j = 1}^{K_{i,2}}
		\{
			v \in \mathbb{Z}^{|\Sigma|}
		\mid
			\xi_{i,j} \cdot v > \lambda_{i,j}
		\}
		\\\cap
		\bigcap_{j = 1}^{K_{i,3}}
		\{
			v \in \mathbb{Z}^{|\Sigma|}
		\mid
			\zeta_{i,j} \cdot v \equiv \eta_{i,j}\ (\bmod\ \theta_{i,j})
		\}
	\end{multline*}
	where each $\alpha_{i,j},\xi_{i,j},\zeta_{i,j} \in \mathbb{Z}^{|\Sigma|}$, each $\beta_{i,j},\lambda_{i,j}, \eta_{i,j} \in \mathbb{Z}$, and $\theta_{i,j} \in \mathbb{N}_+$.

	From the definition of constrained language we see that $L(U,\mathcal{P})$ is the union of disjoint polyhedrally constrained languages $L(U,\mathcal{B}_i)$.
	We see that if each $L(U,\mathcal{B}_i)$ has a multivariate generating function of $f_i(x_1,x_2,\ldots,x_{|\Sigma|})$, then the multivariate generating function for $L(U,\mathcal{P})$ is given by
	\[
		f(x_1,x_2,\ldots,x_{|\Sigma|})
		=
		\sum_{i=1}^L f_i(x_1,x_2,\ldots,x_{|\Sigma|}).
	\]

	For each basic polyhedral set $\mathcal{B}_i$, we introduce a $|\Sigma|$-constraint
	\[
		\mathcal{C}_i
		=
		\bigcap_{j = 1}^{K_{i,1}}
		\{
			v \in \mathbb{Z}^{|\Sigma|}
		\mid
			\alpha_{i,j} \cdot v = \beta_{i,j}
		\}
		\cap
		\bigcap_{j = 1}^{K_{i,2}}
		\{
			v \in \mathbb{Z}^{|\Sigma|}
		\mid
			\xi_{i,j} \cdot v > \lambda_{i,j}
		\},
	\]
	and a monoid homomorphism $\varphi_i \colon \Sigma^* \to \prod_{j=1}^{K_{i,3}} (\mathbb{Z}/\theta_{i,j}\mathbb{Z})$ such that
	\[
		\varphi_i(w)
		=
		(
			\zeta_{i,1} \cdot \Parikh_\Sigma(w),\,
			\zeta_{i,2} \cdot \Parikh_\Sigma(w),\,
			\ldots,\,
			\zeta_{i,K_{i,3}} \cdot \Parikh_\Sigma(w)
		);
	\]
	moreover, we write $R_i \in \Sigma^*$ for the inverse image
	\[
		R_i =
		\varphi_i^{-1}(\{ (\eta_{i,1},\eta_{i,2},\ldots,\eta_{i,K_{i,3}}) \}).
	\]

	Each language $R_i \in \Sigma^*$ is expressed as the inverse image of a subset of a finite monoid.
	From \cite[Theorem~1]{rabin1959} we see that each $R_i$ is a regular language, in particular, for each $R_i$ we may construct a finite-state automaton with states given by the set $\prod_{j=1}^{K_{i,3}} (\mathbb{Z}/\theta_{i,j}\mathbb{Z})$, initial state given by $(0,\ldots,0)$, an accepting state of $(\eta_{i,1},\eta_{i,2},\ldots,\eta_{i,K_{i,3}})$, and a transition $v \to^\sigma v'$ for each state $v$ and letter $\sigma \in \Sigma$ where $v' = v + \varphi_i(\sigma)$.
	Moreover, since the class of unambiguous context-free grammar is closed under intersection with regular language (see Theorem~6.4.1 on p.~197 of \cite{harrison1978}), we see that each $L(U \cap R_i,\mathcal{C}_i) = L(U,\mathcal{B}_i)$ is linearly constrained as in \cref{defn:linearly-constrained-language}.
	From \cref{prop:lcl-is-holonomic}, we see that each $f_i(x_1,x_2,\ldots,x_{|\Sigma|})$ is holonomic.

	From \cref{lemma:holonomic-closure-properties}, holonomic functions are closed under addition, and thus the multivariate generating function of $L(U, \mathcal{P})$ is holonomic.
\end{proof}