\documentclass[draft]{article}

\usepackage{amsfonts}
\usepackage{amsmath}
\usepackage{amsthm}
\usepackage{booktabs}
\usepackage[T1]{fontenc}
\usepackage[final=true,backref=page,colorlinks=true]{hyperref}[2016/05/21]
\usepackage{ifdraft}
\usepackage[utf8]{inputenc}
\usepackage[final]{listings}
\usepackage[final]{microtype}
\usepackage[numbers]{natbib}
\usepackage{xcolor}

\input{palette.def}

\title{\Daence/:
  \Salsa20/ and \ChaCha/ in Deterministic Authenticated Encryption \\
  with no noNCEnse}
\author{Taylor `Riastradh' Campbell
  \email{campbell+daence@mumble.net}}

\bibliographystyle{plainnat}
\renewcommand*{\backrefalt}[4]{%
  \ifcase#1% no citations
  \or% one citation
    Cited on p.~#2.%
  \else% multiple citations
    Cited on pp.~#2.%
  \fi%
}
\DeclareUrlCommand\doi{%
  \def\UrlLeft##1\UrlRight{DOI~\href{https://doi.org/##1}{##1}}%
  \urlstyle{rm}}
\DeclareUrlCommand\url{%
  \def\UrlLeft##1\UrlRight{\href{##1}{##1}}%
  \urlstyle{tt}}
\DeclareUrlCommand\email{%
  \def\UrlLeft##1\UrlRight{\langle\href{mailto:##1}{##1}\rangle}%
  \urlstyle{tt}}

\newtheorem{definition}{Definition}
\newtheorem{lemma}{Lemma}
\newtheorem{theorem}{Theorem}

\newcommand{\lemmaautorefname}{Lemma}

\newcommand{\term}[1]{\textbf{#1}}

% Kludge for bold italic numerals.  Numerals turn out to be in the same
% place in OML encoding as they are in T1 encoding, so even though T1
% is not normally fit for math, it happens to work out here.
\DeclareMathAlphabet{\mathbfit}{T1}{lmr}{bx}{it}

\newcommand{\warning}[1]{%
  \ifdraft{\textbf{\textcolor{red}{\textsc{Warning}: #1}}}
          {}}

\newcommand{\margintodo}[1]{\ifdraft{%
  \leavevmode\marginpar{\leavevmode%
    \parskip=4pt plus 2pt minus 1pt\relax%
    \raggedright%
    \color{red}\bfseries%
    TODO: #1%
  }%
}{}}

\DeclareRobustCommand{\operatorsc}[1]{{%
  \ifmmode\let\next=\operatorname\else\let\next=\relax\fi\next{\textsc{#1}}}}
\def\Salsa#1/{\operatorsc{Salsa#1}}
\def\ChaCha#1/{\operatorsc{ChaCha#1}}
\def\HChaCha#1/{\operatorsc{HChaCha#1}}
\def\HSalsa#1/{\operatorsc{HSalsa#1}}
\def\XChaCha#1/{\operatorsc{XChaCha#1}}
\def\HXChaCha#1/{\operatorsc{HXChaCha#1}}
\def\XSalsa#1/{\operatorsc{XSalsa#1}}
\def\HXSalsa#1/{\operatorsc{HXSalsa#1}}
\def\Poly#1/{\operatorsc{Poly#1}}
\def\Auth#1/{\operatorsc{Auth#1}}
\def\Daence/{\operatorsc{Daence}}
\def\Deuce/{\operatorsc{Deuce}}
\def\NH/{NH}

\def\CAESAR/{\textsc{Caesar}}
\def\eSTREAM/{eSTREAM}
\def\OCB/{OCB}
\def\NaCl/{NaCl}
\def\TweetNaCl/{TweetNaCl}
\def\IETF/{IETF}
\def\NIST/{NIST}
\def\TLS/{TLS}
\def\IV/{\textsc{iv}}
\def\CPU/{\textsc{cpu}}
\def\SUPERCOP/{\textsc{supercop}}
\def\Tarsnap/{Tarsnap}
\def\GHASH/{\textsc{ghash}}
\def\POLYVAL/{\textsc{polyval}}
\def\GCM/{\textsc{gcm}}
\def\GCMSIV/{\textsc{gcm\nobreakdash-siv}}
\def\AES/{AES}
\def\AESCTR/{AES\nobreakdash-CTR}
\def\AESSIV/{AES\nobreakdash-CTR}
\def\AESCMAC/{AES\nobreakdash-CMAC}
\def\AESPMAC/{AES\nobreakdash-PMAC}
\def\AESSIV/{AES\nobreakdash-SIV}
\def\AESGCM/{AES\nobreakdash-GCM}
\def\AESGCMSIV/{AES\nobreakdash-GCM\nobreakdash-SIV}
\def\AESPMACSIV/{AES\nobreakdash-PMAC\nobreakdash-SIV}
\def\naclsecretbox/{crypto\_secretbox\_xsalsa20poly1305}
\def\naclonetimeauth/{crypto\_onetimeauth\_poly1305}
\def\libsodium/{libsodium}
\def\sodiumaead/{crypto\_aead}
\def\OpenSSL/{OpenSSL}
\def\BearSSL/{BearSSL}
\def\libgcrypt/{libgcrypt}
\def\Nettle/{Nettle}
\def\Rust/{Rust}
\def\Go/{Go}
\def\Python/{Python}

\makeatletter
\def\newlatinabbr#1#2{\def#1{\protect\@latinabbr{#2}}}
\def\@latinabbr#1{\@ifnextchar.{\@latinabbrfinal{#1}}{\@latinabbrmedial{#1}}}
\def\@latinabbrfinal#1{\latin{#1}\@}
\def\@latinabbrmedial#1{\latin{#1.}}
\makeatother
\newlatinabbr\eg{e.g}
\newlatinabbr\etc{etc}
\newlatinabbr\etseq{et seq}
\newlatinabbr\ie{i.e}
\newlatinabbr\vs{vs}
\def\latin#1{\emph{#1}}

\def\newmathcronym#1#2{%
  \DeclareRobustCommand#1{%
    \ifmmode\def\next{\operatorname{#2}}%
      \else\def\next/{\textsc{\lowercase{#2}}}%
    \fi\next}}

\newmathcronym{\DAE}{DAE}
\newmathcronym{\INDCPA}{IND-CPA}
\newmathcronym{\INTRUP}{INT-RUP}
\newmathcronym{\PRF}{PRF}
\newmathcronym{\PRP}{PRP}
\newmathcronym{\SIV}{SIV}

\DeclareMathOperator{\Adv}{Adv}
\DeclareMathOperator{\DaenceDecrypt}{\textsc{Daence-Decrypt}}
\DeclareMathOperator{\DaenceEncrypt}{\textsc{Daence-Encrypt}}
\DeclareMathOperator{\muDAE}{mu-DAE}
\DeclareMathOperator{\muPRF}{mu-PRF}
\DeclareMathOperator{\trunc}{trunc}

\newcommand{\Z}{\mathbb Z}

\newcommand{\concat}{\mathbin\|}
\newcommand{\given}{\mathrel|}

\newcommand{\maxlength}{\ell}
\newcommand{\collisionbound}{\varepsilon}

\begin{document}

\maketitle

\begin{abstract}
  We present \Daence/, a deterministic authenticated cipher based on a
   pseudorandom function family and a universal hash family, similar
   to \SIV/~\cite{rogaway-shrimpton2006keywrap}.
  We recommend instances with
   \Salsa20/~\cite{bernstein2007salsa20} or
   \ChaCha/~\cite{bernstein2008chacha}, and
   \Poly1305/~\cite{bernstein2005poly1305},
   for high performance, high security, and easy deployment.

  \warning{The definition and analysis are works in progress.}
\end{abstract}

\section{Introduction}

The nonce-based authenticated cipher
 crypto\_secretbox\_xsalsa20poly1305 in
 \NaCl/~\cite{bernstein2009naclcrypto}, and the variant
 \ChaCha//\Poly1305/ defined by the \IETF/~\cite{rfc7539} for
 \TLS/~\cite{rfc7905}, are widely available in fast software
 implementations resistant to timing side channels.
The nonce-based authenticated cipher \AESGCM/~\cite{nist-sp800-38d} is
 popular, though only with hardware support is it fast and resistant
 to timing side channels.

These nonce-based ciphers fail catastrophically in the face of nonce
 reuse.
They are best suited to protocols that are designed to support
 sequential message numbers, such as the record number in \TLS/.
Some applications are unable to keep the state needed to maintain a
 sequential message number, and although they could use an extended
 nonce like \XSalsa20/~\cite{bernstein2011xsalsa} chosen randomly,
 some environments may not have a reliable entropy source.
The \emph{nonce-misuse-resistant} authenticated cipher
 \AESGCMSIV/~\cite{rfc8452} was developed to address these use cases,
 but it carries with it the performance and side channel costs of
 \AESGCM/---and amplifies the performance cost by deriving fresh keys
 for each distinct nonce, yet has very narrow security margins.

We propose a deterministic authenticated cipher \Daence/ built out of
 the \Salsa20/ or \ChaCha/ pseudorandom function family and the
 \Poly1305/ universal hash family.
The design is based on the \SIV/ construction of Rogaway and
 Shrimpton~\cite{rogaway-shrimpton2006keywrap}, with a
 variable-input-\PRF/ made by composing a universal hash family with a
 fixed-input \PRF/~%
  \cite[\S1.5]{bellare-canetti-krawczyk1996cascade}%
  \cite[\S9, Theorem~9.2]{bernstein1999hash127}.
\Daence/ is easily implemented in terms of the primitives available in
 \NaCl/ and \libsodium/.

\section{Security contract}

\Daence/ is a deterministic authenticated cipher.
This means it consists of two functions:
%
\begin{description}
  \item[\normalfont $t \concat c = \DaenceEncrypt(k, a, m)$] takes
     a key $k$ (96-byte in \Salsa20/-\Daence/, 64-byte in
      \ChaCha/-\Daence/),
     a string $a$ of at most $2^{38}$ bytes of associated data, and
     a message $m$ of at most $2^{38}$ bytes ($256\,\mathrm{GB}$).

    $\DaenceEncrypt$ returns an authenticated ciphertext $t \concat c$
     which is 24 bytes longer than $m$.

  \item[\normalfont $m = \DaenceDecrypt(k, a, t \concat c)$] takes
     a key $k$, a string $a$ of at most $2^{38}$ bytes of associated
     data, and an alleged authenticated ciphertext $t \concat c$ of
     at most $24 + 2^{38}$ bytes.

    \begin{itemize}
      \item If $t \concat c = \DaenceEncrypt(k, a, m)$,
         $\DaenceDecrypt$ returns $m$.
      \item Otherwise, $\DaenceDecrypt$ reports a forgery with high
         probability.
        In the sequel we denote this by the symbol `$\bot$'; in
         practice, a \texttt{crypto\_dae\_salsa20daence\_open}
         function in the style of \NaCl/ may return an error code or
         throw an exception.
    \end{itemize}
\end{description}

\paragraph*{Responsibilities of the user.}

\begin{enumerate}
  \item You must choose a secret key $k$ uniformly at random and
     independently of everything else in your application.
    (You may safely derive the 96-byte key $k$ from a 32-byte key $k'$
     by a key derivation function---\eg,
     $k = \operatorname{HKDF-SHA256}_{k'}(\mathit{salt}, \text{`foo'},
      96)$.)

  \item If $\DaenceDecrypt$ reports a forgery, you must decline to act
     on the alleged message content except by immediately dropping it
     on the floor.

  \item You must encrypt at most $2^{52}$ messages with each key.

    Applications limited to smaller \emph{messages} can safely process
     a larger \emph{number} of messages: if every message is at most
     $L < 2^{38}$ bytes long (including associated data), then you may
     process up to $2^{90}\!/L$ messages.
\end{enumerate}

\paragraph*{Security guarantee.}

Under any key $k$ independently:

\begin{enumerate}
  \item If you choose a distinct associated data string for every
     message, then an adversary has no hope of distinguishing the
     ciphertexts of your messages from uniform random byte strings of
     the same length, or of distingushing the tags from uniform random
     24-byte strings.

  \item If you repeat an associated data string, then an adversary has
     no hope of distinguishing the ciphertexts of \emph{distinct}
     messages from uniform random byte strings of the same length, but
     can tell when messages are repeated.

  \item
    \margintodo{Triple-check bounds!}%
    The adversary's probability of succeeding at forgery---even
     after flooding your system with up to $2^{100}$ forgery
     attempts---is less than $1/2^{32}$.
\end{enumerate}

\subsection{Safe usage limits}

We recommend that each key be used to encrypt no more than $2^{52}$
 messages if an application may attain the maximum length of $2^{38}$
 bytes in the associated data and $2^{38}$ bytes in the message.
Such applications can withstand well over $2^{100}$ forgery attempts
 before the adversary's advantage exceeds $1/2^{32}$.

For better security, we recommend that each application set
 application-specific limits on the sum $\ell_a + \ell_m$ of the
 associated data and message length.
This limit should be chosen according to how much memory the
 application is willing to let a forger waste in a denial of service
 attack before detection.
For example:
\begin{itemize}
  \item an IP packet (on a path with the standard ethernet MTU)
     is at most $1500$ bytes;
  \item a TLS record is at most $2^{14}$ bytes;
  \item a file system block is typically at most $2^{15}$ or $2^{16}$ bytes;
  \item a Tarsnap file chunk can be up to around $2^{18}$ bytes.
\end{itemize}
Applications limited to smaller \emph{messages} can safely process a
 larger \emph{number} of messages per key---\eg, applications limited
 to $2^{30}$ bytes per message can safely process $2^{60}$ messages and
 withstand $2^{120}$ forgery attempts, and applications limited to 1500
 bytes per message can safely process $2^{79}$ messages and withstand
 $2^{158}$ forgery attempts, before the adversary's advantage exceeds
 $1/2^{32}$.
In general, a single \Daence/ key is safe for up to
 $2^{90}\!/(\ell_a + \ell_m)$
 messages, or $2^{80}$ messages, whichever is smaller.

\subsection{Comparison to alternative ciphers}

In \autoref{tab-security}, we compare the adversary's advantage against
 \Daence/ to several obvious alternatives, for various maximum message
 sizes and numbers of messages:

\begin{description}
  \item[\AESSIV/] (`\SIV/')
     a deterministic authenticated cipher in the \SIV/ construction,
     built out of \AESCTR/ and \AESCMAC/.
    (A variant, \AESPMACSIV/~\cite{arcieri2018aespmacsiv}, uses
     \AESPMAC/~\cite{black-rogaway2002pmac-eurocrypt} instead of
     \AESCMAC/ for better parallelism and essentially the same
     security.)

    Security~%
     \cite[\S4, Theorem~2]{rogaway-shrimpton2006keywrap}%
     \cite[\S5, Theorem~3, with $p=1$]{rogaway-shrimpton2006keywrap}%
     \cite[\S2, Theorem~2.2]{bernstein2005permutations}
     is dominated by the birthday bound on the 128-bit block size of
     \AES/.
    \Daence/ avoids this bottleneck by using a native \PRF/---\Salsa20/
     or \ChaCha/---instead of approximating one by a \PRP/ like \AES/.

  \item[\AESGCMSIV/] (`\GCMSIV/')
     a nonce-misuse-resistant authenticated cipher built out of
     \AESCTR/ and the polynomial evaluation hash \POLYVAL/ related to
     \AESGCM/'s \GHASH/.

    We consider both \AESGCMSIV/'s \emph{deterministic} security with a
     fixed nonce~%
     \cite[\S4, Theorem~3, with 256-bit \AES/ keys and $Q=1$ distinct
       nonces]{iwata-seurin2017gcmsivsecurity}
     as well as its \emph{randomized} security~%
     \cite[\S3.3, Corollary~1, with 256-bit \AES/ keys and random
       nonces]{iwata-seurin2017gcmsivsecurity}.

    Obviously \AESGCMSIV/'s randomized security, with no misuse, is
     better; we consider both because the cipher is advertised as
     `misuse-resistant'---if misused to the point that the same nonce
     is used for every message, whether because of entropy
     failure~%
     \cite{debian-dsa-1571-1-openssl}%
     \cite{hdwh2012miningpsqs}
     or virtual machine
     rollbacks or coding errors, \AESGCMSIV/ gives the deterministic
     security.
    The margin of this paper is too small to fit a neat visual
     representation of all the dimensions in which nonce reuse might
     occur---maximum reuses per nonce, average reuses per nonce, \etc.
    \begin{itemize}
      \item For \emph{deterministic security}, \AESGCMSIV/ is dominated
         by the birthday bound on the 128-bit block size of \AES/---and
         the birthday bound on the 128-bit tag size \emph{multiplied}
         by the maximum message length, because of \POLYVAL/ collision
         probability.

        \Daence/ avoids these bottlenecks by using a native \PRF/ and
         by using a much larger universal hash family to derive a
         192-bit tag.

      \item For \emph{randomized security with no misuse}, \AESGCMSIV/
         avoids the birthday bound on the block and tag size by
         deriving a fresh \AES/ key for each message---at high cost
         (whether or not it is misused) to performance and side channel
         security in implementations that cannot rely on hardware \AES/
         acceleration.
    \end{itemize}
    The deterministic security bound could be made tighter by
     judiciously incorporating the better \PRF//\PRP/ switching lemma
     of~\cite[\S2, Theorem~2.2]{bernstein2005permutations}
     into~\cite[Appendix~A, Lemma~2]{iwata-seurin2017gcmsivsecurity},
     but it would remain slightly worse than \AESSIV/ because
     \POLYVAL/'s collision probability contributes a factor of the
     maximum message length.

  \item[\AESGCM/] (`\GCM/')
     a nonce-based authenticated cipher built out of \AESCTR/ and the
     polynomial evaluation hash \GHASH/.

    Security~%
     \cite[Appendix~C, Eq.~(22)]{iwata-ohashi-minematsu2012gcmsecurity}
     is dominated by the birthday bound on the 128-bit block size of
     \AES/.
    No misuse-resistance---repeating a nonce is fatal.

  \item[\ChaCha//\Poly1305/] (`\textsc{c/p}')
     a nonce-based authenticated cipher built out of \ChaCha/ and
     \Poly1305/.

    Security~%
     \cite[\S9, Security notes]{bernstein2009naclcrypto}
     is \emph{not} affected by any birthday bound, but the \Poly1305/
     forgery advantage denominator, $2^{103}$, is smaller than for
     \GHASH/, $2^{128}$, which is why advantage against
     \ChaCha//\Poly1305/ starts higher but rises slower than \AESGCM/.
    No misuse-resistance---repeating a nonce is fatal.

    Unlike \ChaCha//\Poly1305/, \Daence/ \emph{is} subject to the
     birthday bound (on the \SIV/ tag size) because it has no
     nonce---but it drives the denominator up to $2^{206}$ by running
     two independent \Poly1305/ instances in parallel, which still
     leaves room to truncate the tag to 192 bits.
\end{description}

\begin{table}
  \caption{Comparison of adversary's advantage for various
     authenticated ciphers.}
  \label{tab-security}

  We suppose for the sake of presentation on two-dimensional paper that
   the adversary can attempt about a million times as many forgeries
   ($2^{20}$) as there are legitimate messages encrypted by the user;
   users for whom this is not accurate can use the theorems below to
   compute safe usage limits.

  Advantage bounds above $2^{-32}$ are
   \textcolor{Vermillion}{\textbf{\textit{highlighted}}};
   this somewhat arbitrary cutoff is derived from \NIST/ guidance on
   \AESGCM/~\cite[\S8, p.~18]{nist-sp800-38d}.

  \begin{center}
  \begin{minipage}{\textwidth}
  \renewcommand{\footnoterule}{}
  \newcommand{\bad}[1]{\textcolor{Vermillion}{\mathbfit{#1}}}
  \centerline{%
  \begin{tabular}{rccccccc}
    \multicolumn{2}{c}{}
    & \multicolumn{3}{c}{deterministic}
    & \multicolumn{1}{c}{randomized}
    & \multicolumn{2}{c}{nonce-based}
    \\
    max bytes per msg
    & msgs
    % deterministic
    & \Daence/
    & \SIV/
    & \GCMSIV/
    % randomized
    & \GCMSIV/
    % nonce-based
    & \GCM/
    & \textsc{c/p}
    \\
    \cmidrule(lr){1-2} \cmidrule(lr){3-5} \cmidrule(lr){6-6} \cmidrule(lr){7-8}
    \input{adv}
  \end{tabular}%
  }
  \end{minipage}
  \end{center}
\end{table}

\section{Definition}

\paragraph*{$\Poly1305/^2$.}
For 16-byte strings $k_1, \dotsc, k_4$, and a byte string $m$, define
\[
  \Poly1305/^2_{k_1,k_2}(m)
  := \Poly1305/_{k_1}(m) \concat \Poly1305/_{k_2}(m),
\]
 a 32-byte string.
For byte strings $a$ and $m$, define
\[
  \Poly1305/^2_{k_1,k_2,k_3,k_4}(a, m)
  := \Poly1305/^2_{k_3,k_4}(h_a \concat h_m),
\]
 where
 $h_a = \Poly1305/^2_{k_1,k_2}(a)$
 and
 $h_m = \Poly1305/^2_{k_1,k_2}(m)$.

\paragraph*{\HXSalsa20/.}
For 32-byte key $k_0$ and 16-byte inputs $i$ and $j$, define
\[
  \HXSalsa20/_{k_0}(i \concat j) := \HSalsa20/_{\HSalsa20/_{k_0}(i)}(j),
\]
 a 32-byte string.
Note there is a public function $G$ such that
 $\HXSalsa20/_{k_0}(i \concat j) = G(\XSalsa20/_{k_0}(i \concat j), j)$,
 just as \HSalsa20/ can be defined in terms of
 \Salsa20/~\cite{bernstein2011xsalsa} by
 $\HSalsa20/_{k_0}(i) = G(\Salsa20/_{k_0}(i), i)$.

\paragraph*{\Salsa20/-\Daence/.}
To \term{encrypt}, given
 a 96-byte key $k$,
 associated data $a$ of at most $2^{38}$ bytes, and
 a message $m$ of at most $2^{38}$ bytes,
 compute:
%
\begin{enumerate}
  \item $k_0 \concat k_1 \concat k_2 \concat k_3 \concat k_4 := k$
    \hfill (32-byte $k_0$; 16-byte $k_1, \dotsc, k_4$)
  \item $t := \trunc_{192}\bigl(
      \HXSalsa20/_{k_0}(\Poly1305/^2_{k_1,k_2,k_3,k_4}(a, m))
    \bigr)$
    \hfill (24-byte $t$)
  \item $c := m \oplus \bigl(\XSalsa20/_{k_0}(t \concat 0) \concat
      \XSalsa20/_{k_0}(t \concat 1) \concat \dotsb\bigr)$
\end{enumerate}
%
The authenticated ciphertext is $t \concat c$.

To \term{decrypt}, given
 a 96-byte key $k$,
 associated data $a$ of at most $2^{38}$ bytes, and
 an alleged authenticated ciphertext $t \concat c$ of $24$
 to $24 + 2^{38}$ bytes, compute:
%
\begin{enumerate}
  \item $k_0 \concat k_1 \concat k_2 \concat k_3 \concat k_4 := k$
    \hfill (32-byte $k_0$; 16-byte $k_1, \dotsc, k_4$)
  \item $m := c \oplus \bigl(\XSalsa20/_{k_0}(t \concat 0) \concat
      \XSalsa20/_{k_0}(t \concat 1) \concat \dotsb\bigr)$
  \item $t' := \trunc_{192}\bigl(
      \HXSalsa20/_{k_0}(\Poly1305/^2_{k_1,k_2,k_3,k_4}(a, m))
    \bigr)$
    \hfill (24-byte $t'$)
\end{enumerate}
%
If $t' \stackrel?= t$, return $m$; otherwise erase $m$ and report a
 forgery.

\paragraph*{\ChaCha/-\Daence/.}
\ChaCha/-\Daence/ has a 64-byte key, replaces \Salsa20/ by \ChaCha/
 (extended \XChaCha/~\cite{irtf-cfrg-xchacha-03}), and tweaks the
 encoding to match \ChaCha//\Poly1305/~\cite{rfc7539} by zero-padding
 the associated data and message to multiples 16 bytes as
 $\underline a$ and $\underline m$ and appending 8-byte little-endian
 lengths:
%
\begin{enumerate}
  \item $k_0 \concat k_1 \concat k_2 := k$
    \hfill (32-byte $k_0$, 16-byte $k_1$, 16-byte $k_2$)
  \item $t := \trunc_{192}\bigl(
      \HXChaCha/_{k_0}(
        \Poly1305/^2_{k_1,k_2}(
          \underline a \concat \underline m
            \concat \lvert a\rvert_8 \concat \lvert m\rvert_8))
    \bigr)$
  \item $c := m \oplus \bigl(\XChaCha/_{k_0}(t, 0) \concat
      \XChaCha/_{k_0}(t, 1) \concat \dotsb\bigr)$
\end{enumerate}
%
The \XChaCha/ input $(t, n)$ is encoded as
 $t_0 \concat n \concat 0^4 \concat t_1$,
 where
 $t_0$ is the first 16 bytes of $t$,
 $n$ is a 4-byte little-endian block counter,
 $0^4$ is four zero bytes, and
 $t_1$ is the last 8 bytes of $t$.
Decryption is derived similarly.

\section{Security notions}

Let $A$ be a random decision algorithm with access to an oracle
 $\mathcal O$.
Write $\Pr[A(\mathcal O)]$ for the probability $A$ accepts after
 making various queries to $\mathcal O$:
%
\begin{description}
  \item[Encryption queries for a \emph{single} user]
    Given associated data $a$ and message $m$, return an authenticated
     ciphertext $t \concat c$.
  \item[Decryption queries for a \emph{single} user]
    Given associated data $a$ and alleged authenticated ciphertext
     $t \concat c$, return a message $m$, or $\bot$ if the alleged
     authenticated ciphertext is deemed a forgery.
  \item[Encryption queries for \emph{multiple} users]
    Given a user number $u$, associated data $a$, and message $m$,
     return an authenticated ciphertext $t \concat c$.
  \item[Decryption queries for \emph{multiple} users]
    Given a user number $u$, associated data $a$, and alleged
     authenticated ciphertext $t \concat c$, return a message $m$, or
     $\bot$ if the alleged ciphertext is deemed a forgery.
  \item[Function queries for \emph{multiple} users]
    Given a user number $u$ and an input $x$, return an output $y$.
\end{description}
%
The adversary $A$ is assumed not to repeat queries, nor to submit the
 answers from encryption queries as decryption queries.
We review standard notions of security
 (\eg,~%
  \cite[Definition~1]{rogaway-shrimpton2006keywrap}%
  \cite[\S3]{bellare-tackmann2016mu-ae-crypto}),
 loosely summarized as how well $A$ can tell users of a real
 cryptosystem---\Daence/, \XSalsa20/, \etc---from pranksters who just
 roll dice to answer every query.

\begin{definition}
  The \term{pathological deterministic authenticated cipher $U_1$}
   returns an independent uniform random authenticated ciphertext of
   the appropriate length for each encryption query, and returns
   $\bot$ for every decryption query.
  The notion extends naturally to the multi-user setting; call it
   $U$.
\end{definition}

\begin{definition}
  For a deterministic authenticated cipher $E_k$ with random key $k$,
   the
   \term{multi-user deterministic authenticated encryption advantage}
   of $A$ against $E$ is the statistical distance from $E_k$ to $U$
   measured by $A$, where by abuse of language $k$ is understood to
   mean a collection of keys chosen independently by many users and
   $E_k$ is understood to mean a collection of instances of $E$ for
   many users keyed by their respective keys:
  \[
    \Adv^{\muDAE}_E(A) := \lvert\Pr[A(E_k)] - \Pr[A(U)]\rvert.
  \]
  Here $A$ may submit encryption and decryption queries for
   \emph{multiple} users.
\end{definition}

The single-user $\Adv^{\DAE}_E(A)$ is defined similarly.

\begin{definition}
  For a function family $\phi_k$ with random key $k$, the
   \term{multi-user pseudorandom function advantage}
   of $A$ against $\phi$ is the statistical distance from $\phi_k$ to
   $f$ measured by $A$, where $f$ is a a uniform random function of
   the same domain and codomain (where `$\phi_k$' and `$f$' again
   mean many independent instances):
  \[
    \Adv^{\muPRF}_\phi(A) := \lvert\Pr[A(\phi_k)] - \Pr[A(f)]\rvert.
  \]
  Here $A$ may submit function queries for \emph{multiple} users.
\end{definition}

\section{Analysis}

\begin{theorem}[\Salsa20/-\Daence/]\label{thm-salsa20-daence}
  Let $A$ be a random decision algorithm with encryption and
   decryption oracles for a set of deterministic authenticated
   cipher users.
  Suppose $A$ submits $E(u)$ encryption queries and $D(u)$ decryption
   queries to the $u^{\mathit{th}}$ user of up to $\ell_a(u)$ bytes of
   associated data and $\ell_m(u)$-byte messages.
  Then there is an algorithm $A'$ making at most
   $\sum_u \bigl(1 + \lceil\ell_m(u)/64\rceil\bigr)
     \bigl(E(u) + D(u)\bigr)$
   oracle queries and having the cost of $A$ plus the cost of
   evaluating $\Poly1305/^2$ and $\oplus$ on
   $\sum_u E(u) + D(u)$
   different $(\ell_a(u), \ell_m(u))$-byte inputs,
   such that
%
  \begin{multline*}
    \Adv^{\muDAE}_{\Daence/}(A)
     \leq \Adv^{\muPRF}_{\XSalsa20/}(A') \\
            + \sum_u
                \frac{2 D(u) + E(u)^2 + \binom{E(u)}{2}}
                     {2^{192}} \\
                + \collisionbound(\ell_a(u), \ell_m(u))
                  \cdot
                  {\textstyle\bigl(D(u) + \binom{E(u)}{2}\bigr)},
  \end{multline*}
%
   where
  \[
    \collisionbound(\ell_a, \ell_m)
    := \frac{\max\{\lceil\ell_a/16\rceil^2, \lceil\ell_m/16\rceil^2\}
             + 16}
            {2^{206}}.
  \]
\end{theorem}

\begin{theorem}[\ChaCha/-\Daence/]\label{thm-chacha-daence}
  Let $A$ be a random decision algorithm with encryption and
   decryption oracles for a set of deterministic authenticated
   cipher users.
  Suppose $A$ submits $E(u)$ encryption queries and $D(u)$ decryption
   queries to the $u^{\mathit{th}}$ user of up to $\ell_a(u)$ bytes of
   associated data and $\ell_m(u)$-byte messages.
  Then there is an algorithm $A'$ making at most
   $\sum_u \bigl(1 + \lceil\ell_m(u)/64\rceil\bigr)
     \bigl(E(u) + D(u)\bigr)$
   oracle queries and having the cost of $A$ plus the cost of
   evaluating $\Poly1305/^2$ and $\oplus$ on
   $\sum_u E(u) + D(u)$
   different $(\ell_a(u), \ell_m(u))$-byte inputs,
   such that
%
  \begin{multline*}
    \Adv^{\muDAE}_{\Daence/}(A)
     \leq \Adv^{\muPRF}_{\XChaCha/}(A') \\
            + \sum_u
                \frac{2 D(u) + E(u)^2 + \binom{E(u)}{2}}
                     {2^{192}} \\
                + \frac{\lceil(\ell_a(u) + \ell_m(u) + 16)/16\rceil^2}{2^{206}}
                  \cdot
                  {\textstyle\bigl(D(u) + \binom{E(u)}{2}\bigr)}.
  \end{multline*}
\end{theorem}

\paragraph*{Outline of proof.}

\begin{enumerate}
  \item Set a bound on the collision probability of $\Poly1305/^2$.
  \item Set a bound on \DAE/ advantage against an idealized version of
     \Daence/.
  \item Extend the bound to the multi-user setting.
  \item Instantiate the idealization with the actual \PRF/, \XSalsa20/
     or \XChaCha/.
\end{enumerate}

\subsection{Collisions under double-hashing with associated data}

\begin{lemma}[Double-hashing]\label{lem-double-hash}
  Let $k_1, k_2$ be independent \Poly1305/ keys.
  For any distinct strings $m \ne m'$ of at most $\ell$ bytes,
  \[
    \Pr[\Poly1305/^2_{k_1,k_2}(m) = \Poly1305/^2_{k_1,k_2}(m')]
    \leq \collisionbound(\ell)
    := \frac{\lceil\ell/16\rceil^2}{2^{206}}.
  \]
\end{lemma}

\begin{proof}
  By~\cite[Theorem~3.3]{bernstein2005poly1305},
  \[
    \Pr[\Poly1305/_{k_1}(m) = \Poly1305/_{k_1}(m')]
    \leq \frac{8\lceil\ell/16\rceil}{2^{106}},
  \]
   and likewise for $k_2$.
  Since $k_1$ and $k_2$ are independent,
  \begin{align*}
    \Pr&[\Poly1305/^2_{k_1,k_2}(m) = \Poly1305/^2_{k_1,k_2}(m')] \\
    &= \Pr[\Poly1305/_{k_1}(m) = \Poly1305/_{k_1}(m'), \\
    &\qquad\quad\Poly1305/_{k_2}(m) = \Poly1305/_{k_2}(m')] \\
    &= \Pr[\Poly1305/_{k_1}(m) = \Poly1305/_{k_1}(m')] \\
    &\quad
       \cdot
       \Pr[\Poly1305/_{k_2}(m) = \Poly1305/_{k_2}(m')] \\
    &\leq \biggl(\frac{8\lceil\ell/16\rceil}{2^{106}}\biggr)^2
     = \frac{64\lceil\ell/16\rceil^2}{2^{212}}
     = \frac{\lceil\ell/16\rceil^2}{2^{206}}.
    \qedhere
  \end{align*}
\end{proof}

\begin{lemma}[Hashing tuples]\label{lem-hash-tuple}
  Let $k_1, \dotsc, k_4$ be independent \Poly1305/ keys.
  For strings $a, a'$ up to $\ell_a$ bytes and $m, m'$ up to $\ell_m$
   bytes, if $(a, m) \ne (a', m')$ then
%
  \begin{multline*}
    \Pr[\Poly1305/^2_{k_1,k_2,k_3,k_4}(a, m)
        = \Poly1305/^2_{k_1,k_2,k_3,k_4}(a', m')] \\
    \leq \collisionbound(\ell_a, \ell_m)
    := \frac{\max\{\lceil\ell_a/16\rceil^2, \lceil\ell_m/16\rceil^2\}
             + 16}
            {2^{206}}.
  \end{multline*}
\end{lemma}

\begin{proof}
  Write
   $H := \Poly1305/^2_{k_1,k_2}$ and
   $H^* := \Poly1305/^2_{k_3,k_4}$.
  Let $h_x := H(x)$.
  We must have either $a \ne a'$ or $m \ne m'$, or both.
  If $a \ne a'$, then by \autoref{lem-double-hash},
   $\Pr[(h_a, h_m) = (h_{a'}, h_{m'})]
    \leq \Pr[h_a = h_{a'}]
    \leq \collisionbound(\ell_a)$.
  Similarly, if $m \ne m'$, the probability is bounded by
   $\collisionbound(\ell_m)$,
   so in either case,
  \[
    \Pr[(h_a, h_m) = (h_{a'}, h_{m'})]
    \leq \max\{\collisionbound(\ell_a), \collisionbound(\ell_m)\}.
  \]
  Finally, since $H^*$ is independent of $H$ and thus of the $h_x$:
%
  \begin{align*}
    \Pr&[H^*(h_a \concat h_m) = H^*(h_{a'} \concat h_{m'})] \\
    &\leq \Pr[(h_a, h_m) = (h_{a'}, h_{m'})] \\
    &\qquad
          + \Pr[H^*(h_a \concat h_m) = H^*(h_{a'} \concat h_{m'})
                \given (h_a, h_m) \ne (h_{a'}, h_{m'})] \\
    &\leq \max\{\collisionbound(\ell_a), \collisionbound(\ell_m)\}
          + \collisionbound(64)
     = \frac{\max\{\lceil\ell_a/16\rceil^2, \lceil\ell_m/16\rceil^2\}
             + 4^2}
            {2^{206}}.
    \qedhere
  \end{align*}
\end{proof}

\newpage

\subsection{Idealizing the cipher}

Let $f\colon \{0,1\}^{256} \to \{0,1\}^{512}$ be a uniform random
 function, an idealization of $\XSalsa20/$ under a uniform random key.
Denote by
 $\hat f\colon \{0,1\}^{256} \to \{0,1\}^{256}$
 the function
 $\hat f(n_0 \concat n_1) := G(f(n_0 \concat n_1), n_1)$,
 for 16-byte $n_0$ and $n_1$,
 \ie, the corresponding idealization of $\HXSalsa20/$ under the
 \emph{same} key.
For 192-bit $t$, denote by $f_*(t)$ the concatenation
 $f(t \concat 0) \concat f(t \concat 1) \concat f(t \concat 2) \concat \dotsb$,
 with the 64-bit input counter $0, 1, 2, \dotsc$
 (limited below $2^{32}$)
 encoded in little-endian---this idealizes the \XSalsa20/ stream
 cipher, again under the \emph{same} key.
Note that $f$, $\hat f$, and $f_*$ are all uniformly distributed
 (but not independent of one another!).

Define \term{\Deuce/} to be as \Daence/, but with $f$ substituted for
 $\XSalsa20/_{k_0}$:
%
\begin{enumerate}
  \item $h := \Poly1305/^2_{k_1,k_2,k_3,k_4}(a, m)$
    \hfill (32-byte $h$)
  \item $t := \trunc_{192}(\hat f(h))$
    \hfill (24-byte $t$)
  \item $c := m \oplus f_*(t)$
  \item return $t \concat c$
\end{enumerate}
%
(Decryption is defined the obvious way.)

\begin{lemma}[Single-user idealized security]\label{lem-su-ideal}
  Let $A$ be a random decision algorithm with encryption and
   decryption oracles for a deterministic authenticated cipher.
  Suppose $A$ makes $E$ encryption queries and $D$ decryption queries
   of up to $\ell_a$ bytes of associated data and $\ell_m$-byte
   messages.
  Then
  \[
    \Adv^{\DAE}_{\Deuce/}(A)
    \leq \frac{2 D + E^2 + \binom{E}{2}}{2^{192}}
         + \collisionbound(\ell_a, \ell_m)
           \cdot
           {\textstyle\bigl(D + \binom{E}{2}\bigr)}.
  \]
\end{lemma}

\begin{proof}

Recall
 $\Adv^{\DAE}_{\Deuce/}(A) := \lvert\Pr[A(\Deuce/)] - \Pr[A(U_1)]$
 where $U_1$ is the pathological `DAE' whose encryption oracle always
 answers with independent uniform random bit strings and whose
 decryption oracle always answers with $\bot$.
We will show that queries to a \Deuce/ oracle likewise all return
 independent uniform random bit strings for encryption and $\bot$ for
 decryption, except in events of low probability.

Setting aside forgery attempts (decryption queries) for the moment,
 consider the following set of encryption queries to a \Deuce/ oracle
 and its responses:
\[
  (a_1, m_1) \mapsto t_1 \concat c_1, \quad
  (a_2, m_2) \mapsto t_2 \concat c_2, \quad
  \cdots, \quad
  (a_E, m_E) \mapsto t_E \concat c_E,
\]
 where
\[
\begin{aligned}
  h_i &= \Poly1305/^2_{k_1,k_2,k_3,k_4}(a_i, m_i), \\
  t_i &= \trunc_{192}(\hat f(h_i)) = \trunc_{192}(G(f(h_i), h_i)), \\
  c_i &= m_i \oplus f_*(t_i)
       = m_i \oplus \bigl(
           f(t_i \concat 0) \concat
           f(t_i \concat 1) \concat
         \dotsb\bigr).
\end{aligned}
\]
Note that for each $i$, both $t_i$ and $c_i$ are uniform random on
 their own.
Further, as long as all the \emph{inputs} to $f$, via $\hat f$ and
 $f_*$, are \emph{distinct}, all the \emph{outputs}---and thus all the
 $t_i \concat c_i$---are \emph{independent}.
Conditional on this event, the distribution on the encryption oracle
 query responses for \Deuce/ is exactly the same as the distribution on
 encryption oracle query responses for $U_1$---independent uniform
 random bit strings.
Conditional also on the event that there are no successful forgeries,
 \Deuce/ and $U_1$ have exactly the same distribution for \emph{all}
 queries.

Among the oracle queries, either a successful forgery must happen
 first, or a collision in the inputs to $f$ must happen first.
It will be convenient to study the probability of a collision between a
 hash value $h_i$ and a tag/counter input $t_j \concat n$, separately
 from the probability of tag collision $t_i = t_j$ for some $i \ne j$.
So we will break the `bad' events into:
%
\begin{enumerate}
  \item
    $C_{th} := \exists i, j, n.\; h_i = t_j \concat n$
    ---
     a collision between a hash $h_i$ and a tag/counter
     $t_j \concat n$,
     \emph{before} a successful forgery and
     \emph{before} a collision among the tags.
  \item
    $C_t := \exists i \ne j.\; t_i = t_j$
    ---
     a collision between two tag values $t_i = t_j$ for $i \ne j$,
     \emph{before} a hash and tag/counter collision and
     \emph{before} a successful forgery.
  \item
    $F$
    ---
     a successful forgery
     \emph{before} a collision in the inputs to $f$.
\end{enumerate}
%
If none of these happen---no collision in $f$ inputs, no
 forgery---\Deuce/ and $U_1$ have the same distribution, so
%
\begin{align*}
  \Pr[A(\Deuce/)]
  &\leq \Pr[A(\Deuce/) \given \lnot C_{th}, \lnot C_t, \lnot F]
     + \Pr[C_{th}] + \Pr[C_t] + \Pr[F] \\
  &= \Pr[A(U_1)] + \Pr[C_{th}] + \Pr[C_t] + \Pr[F],
\end{align*}
%
 and since $A$ was arbitrary and could be replaced by $\lnot A$, we
 have
\[
  \lvert\Pr[A(\Deuce/)] - \Pr[A(U_1)]\rvert
  \leq \Pr[C_{th}] + \Pr[C_t] + \Pr[F].
\]
We will next show that the events $C_{th}$, $C_t$, and $F$ occur only
 with low probability.

For upper bounds on $\Pr[C_{th}]$ and $\Pr[C_t]$, we can assume $A$
 makes no forgery attempts---if it attempted forgeries
 (decryption queries)
 interspersed with encryption queries, we could construct an adversary
 $A'$ that is identical except without the forgery attempts.
The probabilities $\Pr[C_{th}]$ and $\Pr[C_t]$ of collisions
 \emph{before} a successful forgery are at least as high for $A'$,
 which never even attempts a forgery and so can never be interrupted in
 its quest for collisions by a successful forgery, as for $A$, which
 may succeed at forgery before it has had the opportunity to submit all
 the encryption queries that $A'$ would have submitted.
(This follows the argument
 of~\cite[Theorem~1]{dodis-pietrzak2007randmac}.)

\paragraph*{Probability of hash and tag/counter collision.}
To set an \emph{upper} bound on the probability of
 $h_i = t_j \concat n$ for some $i,j,n$,
 it suffices to consider the event that the first 192 bits
 $\trunc_{192}(h_i)$
 of hash $h_i$ coincides with tag $t_j$
 (before a successful forgery),
 ignoring the counter $n$:
%
\begin{multline*}
  \Pr[C_{th}]
   = \Pr[\exists i,j,n.\; h_i = t_j \concat n]
   \leq \Pr[\exists i,j.\; \trunc_{192}(h_i) = t_j] \\
   \leq \sum_{i,j} \Pr[\trunc_{192}(h_i) = t_j]
   = \sum_{i,j} \frac{1}{2^{192}}
   = \frac{E^2}{2^{192}},
\end{multline*}
%
 where
 $\Pr[\trunc_{192}(h_i) = t_j] = 1/2^{192}$
 because $t_j = f(h_j)$ is a uniform random 192-bit string
 independent of $\trunc_{192}(h_i)$.
(This holds even if $i = j$, because $f$ is a uniform random
 function---its output on any input is independent of the input.)

\paragraph*{Probability of tag collision.}
The collision $t_i = t_j$ for $i \ne j$ in the event $C_t$ may arise
 either from the hashes
 $h_i = \Poly1305/^2_{k_1,k_2,k_3,k_4}(a_i, m_i)$,
 or from the tags
 $t_i = f(h_i)$
 in encryption queries.
Let $C_h$ be the event of a collision $h_i = h_j$ for $i \ne j$
 (before a successful forgery, and before a hash and tag/counter
 collision).
Since $\Poly1305/^2$ has collision probability bounded by
 $\collisionbound(\ell_a, \ell_m)$,
 we have
%
\begin{align*}
  \Pr[C_h]
    &= \Pr[\exists i<j\colon h_i = h_j]
     \leq \sum_{i<j} \Pr[h_i = h_j] \\
    &= \sum_{i<j}
         \Pr[\Poly1305/^2_{k_1,k_2,k_3,k_4}(a_i, m_i)
               = \Poly1305/^2_{k_1,k_2,k_3,k_4}(a_j, m_j)] \\
    &\leq \sum_{i<j} \collisionbound(\ell_a, \ell_m)
     = \binom{E}{2} \collisionbound(\ell_a, \ell_m).
\end{align*}
%
If the $h_i$ are all distinct, then the $t_i$ are uniform random bit
 strings independent of everything else involved---which means an
 adversary learns no new information from each query to adaptively act
 on in subsequent queries---so there is a collision among the $t_i$
 only with probability
%
\begin{multline*}
  \Pr[C_t \given \lnot C_h]
     = \Pr[\exists i<j\colon t_i = t_j \given \lnot C_h]
     \leq \sum_{i<j} \Pr[t_i = t_j \given \lnot C_h] \\
     = \sum_{i<j} \Pr[f(h_i) = f(h_j) \given h_i \ne h_j]
     \leq \sum_{i<j} \frac{1}{2^{192}}
     = \binom{E}{2} \frac{1}{2^{192}}.
\end{multline*}
%
Thus,
\[
  \Pr[C_t] \leq \Pr[C_h] + \Pr[C_t \given \lnot C_h]
    \leq \binom{E}{2} \biggl(
        \collisionbound(\ell_a, \ell_m)
        + \frac{1}{2^{192}}
      \biggr).
\]

\paragraph*{Forgery probability.}
To bound $\Pr[F]$, assume $A$ halts after the first forgery
 attempt---an adversary that makes $D>1$ forgery attempts can be broken
 into one that halts after the first forgery attempt, and another one
 that simulates forgery failure for the first attempt before making
 $D-1$ more attempts.
If the first succeeded with probability at most $\Pr[F_0]$, then by
 induction the second succeeds with probability at most
 $(D - 1) \cdot \Pr[F_0]$,
 so that the original succeeds with probability at most
 $\Pr[F_0] + (D - 1) \cdot \Pr[F_0] = D \cdot \Pr[F_0]$.

Let $(a', t' \concat c')$ be the single forgery attempt of $A$,
 with
 $t' \concat c' \ne t_i \concat c_i$
 for all $i$.
Let
 $m' = c' \oplus f_*(t')$
 and
 $h' = \Poly1305/^2_{k_1,k_2,k_3,k_4}(a', m')$.
The forgery succeeds if $t' = f(h')$.
Note that $(a', m') \ne (a_i, m_i)$, for if
 $(a', m') = (a_i, m_i)$,
 then we would have
 $t' \concat c' = t_i \concat c_i$, since---for fixed
 $f,k_1,\dotsc,k_4$ values---$t' \concat c'$ is a deterministic
 function of $(a', m')$.

Let $F_0^{\ne}$ be the event that the forgery is successful \emph{and}
 $t' \ne t_i$ for all $i$, and let $F_0^=$ be the event that the
 forgery is successful \emph{and} $t' = t_i$ for some $i$, so that
 $\Pr[F_0] = \Pr[F_0^{\ne}] + \Pr[F_0^=]$.
%
\begin{itemize}
  \item
    If $t' \ne t_i$ for all $i$, we must have $h' \ne h_i$ for all $i$,
     since $t' = f(h')$ and $t_i = f(h_i)$.
    Hence $f(h')$ is a uniform random 192-bit string independent of all
     the $t_i$ and $c_i$, so $t' = f(h')$ only with probability
     $1/2^{192}$ for this forgery attempt; that is,
    \[
      \Pr[F_0^{\ne}] = 1/2^{192}.
    \]
  \item
    If $t' = t_i$ for some $i$, then necessarily $m' \ne m_i$ for all
     $i$, and the forgery succeeds only when $h' = h_i$, which occurs
     with probability at most $\collisionbound(\ell_a, \ell_m)$; or, if
     $h' \ne h_i$, when $f(h') = f(h_i)$, which occurs with probability
     $1/2^{192}$.
    Thus,
    \[
      \Pr[F_0^=] \leq \collisionbound(\ell_a, \ell_m) + 1/2^{192}.
    \]
\end{itemize}
%
Combining these, we see the probability of a forgery (before any
 collisions) is bounded by
\[
  \Pr[F]
  \leq D \cdot \Pr[F_0]
  \leq D \cdot \Pr[F_0^{\ne}] + D \cdot \Pr[F_0^=]
  \leq \frac{2 D}{2^{192}} + D \cdot \collisionbound(\ell_a, \ell_m).
\]

\paragraph*{Summing it up.}

\begin{align*}
  \lvert\Pr&[A(\Deuce/)] - \Pr[A(U_1)]\rvert \\
  &\leq \Pr[C_{th}] + \Pr[C_t] + \Pr[F] \\
  &\leq \frac{E^2}{2^{192}}
     + \binom{E}{2} \biggl(
         \collisionbound(\ell_a, \ell_m)
         + \frac{1}{2^{192}}
       \biggr)
     + \frac{2 D}{2^{192}} + D \cdot \collisionbound(\ell_a, \ell_m) \\
  &\leq \frac{2 D + E^2 + \binom{E}{2}}{2^{192}}
     + \collisionbound(\ell_a, \ell_m)
       \cdot
       {\textstyle\bigl(D + \binom{E}{2}\bigr)}.
  \qedhere
\end{align*}

\end{proof}

\subsection{Multi-user security}

\begin{lemma}[Multi-user idealized security]\label{lem-mu-ideal}
  Let $A$ be a random decision algorithm with encryption and
   decryption oracles for a \emph{set} of deterministic authenticated
   cipher users.
  Suppose $A$ makes $E(u)$ encryption queries and $D(u)$ decryption
   queries to the $u^{\mathit{th}}$ user of up to $\ell_a(u)$ bytes of
   associated data and $\ell_m(u)$-byte messages.
  Then
%
  \begin{multline*}
    \Adv^{\muDAE}_{\Deuce/}(A)
    \leq \sum_u \frac{2 D(u) + E(u)^2 + \binom{E(u)}{2}}
                     {2^{192}} \\
           + \collisionbound(\ell_a(u), \ell_m(u))
             \cdot
             {\textstyle\bigl(D(u) + \binom{E(u)}{2}\bigr)}.
  \end{multline*}
\end{lemma}

\begin{proof}
  In the foregoing analysis of the idealized cipher \Deuce/ in the
   single-user setting (\autoref{lem-su-ideal}), the probabilities of
   the critical events---$C_{th}$, $C_t$, and $F$---can be
   straightforwardly seen to sum over the users.
  For example, let $C_t^u$ be the event of a tag collision for the
   $u^{\mathit{th}}$ user, and let $C_t^*$ be the event of a tag
   collision in \emph{any one} of the users; then
  \[\textstyle
    \Pr[C_t^*] = \Pr[\exists u.\; C_t^u] \leq \sum_u \Pr[C_t^u].
  \]
  Consequently, the multi-user \DAE/ advantage against \Deuce/---that
   is, the statistical distance under $A$ from \Deuce/ to a
   pathological `\DAE/' collection $U$---is at most the sum of the
   single-user \DAE/ advantages.
\end{proof}

\paragraph*{Discussion.}
The generic single-user-to-multi-user advantage bound lemma%
 ~\cite[Lemma~3.3]{bellare-canetti-krawczyk1996cascade}%
  \cite[Lemma~1]{bellare-bernstein-tessaro2016amac-mu}
 shows that if an adversary making a total of $q$ queries to \emph{one}
 user has advantage at most $\epsilon$, then an adversary making a
 total of $q$ queries distributed across $N$ users has advantage at
 most $N\cdot\epsilon$.
Here, with $q = \sum_u E(u) + D(u)$, we have shown a multi-user
 advantage bound much smaller than the generic lemma yields as
 a corollary.
Loosely, where the generic would be
 $N\cdot \bigl(\sum_u \cdots\bigr)^2\!/2^\lambda$,
 we show
 $\sum_u (\cdots)^2\!/2^\lambda$
 instead.
How does this work?

In \Deuce/, a query to a never-before-queried user gives a response
 independent of all prior query responses, and so queries to new users
 contribute only \emph{linearly} to the adversary's advantage.
But a query to a previously-queried user may lead to a collision
 involving that user's secret $f$ or $\Poly1305/^2_{k_1,\dotsc,k_4}$,
 and so by the birthday bound repeated queries to the same user
 contribute \emph{quadratically} to the adversary's advantage.
Thus, the best strategy at breaking the idealized cipher---recall this
 is before we have instantiated it with \XSalsa20/ so there is no batch
 key search advantage yet---is to focus on the user with the highest
 maximum message length or bandwidth, ignoring all other users.

\subsection{Instantiating the idealized cipher}

\begin{lemma}[Multi-user instantiation]\label{lem-mu-instance}
  Let $A$ be a random decision algorithm with encryption and
   decryption oracles for a \emph{set} of deterministic authenticated
   cipher users.
  Suppose $A$ makes $E(u)$ encryption queries and $D(u)$ decryption
   queries to the $u^{\mathit{th}}$ user of up to $\ell_a(u)$ bytes of
   associated data and $\ell_m(u)$-byte messages.
  Then there is an algorithm $A'$ making at most
   $\sum_u \bigl(1 + \lceil\ell_m(u)/64\rceil\bigr)
     \bigl(E(u) + D(u)\bigr)$
   oracle queries and having the cost of $A$ plus the cost of
   evaluating $\Poly1305/^2$ and $\oplus$ on
   $\sum_u E(u) + D(u)$
   different $(\ell_a(u), \ell_m(u))$-byte inputs,
   such that
  \[
    \lvert\Pr[A(\Daence/)] - \Pr[A(\Deuce/)]\rvert
    = \Adv^{\muPRF}_{\XSalsa20/}(A').
  \]
\end{lemma}

\begin{proof}
  \Deuce/ is simply \Daence/ with a uniform random function $f$
   substituted for $\XSalsa20/_{k_0}$, so if $A$ can distinguish a
   collection of \Daence/ users from a collection of \Deuce/ users then
   it can be used in an algorithm $A'$ to distinguish a collection of
   $\XSalsa20/_{k_0}$ users from a collection of $f$ users (recall
   $f\colon \{0,1\}^{256} \to \{0,1\}^{512}$ is a
   uniform random function).

  If $\mathcal O(u,x)$ is an oracle for a collection of function
   instances indexed by $u$, define $A'(\mathcal O)$ to run $A$ with
   oracles for the following \DAE/ under independent uniform random keys
   $k_1,\dotsc,k_4$ for the $u^{\mathit{th}}$ user, decryption being
   defined the obvious way:
%
  \begin{enumerate}
    \item $h := \Poly1305/^2_{k_1,k_2,k_3,k_4}(a, m)$
      \hfill (32-byte $h$)
    \item $t := \trunc_{192}(\hat{\mathcal O}(u, h))$
      \hfill (24-byte $t$)
    \item $c := m \oplus \mathcal O_*(u, t)$
    \item return $t \concat c$
  \end{enumerate}
%
  This invokes the oracle once for each message
   (via $\hat{\mathcal O}$)
   and once for each 64-byte block in each message
   (via $\mathcal O_*$).
  Then $A'(\XSalsa20/_{k_0}) = A(\Daence/)$ and $A'(f) = A(\Deuce/)$
   (with `$k_0$' and `$f$' understood to mean a collection of
   independent keys/functions), so
  %
  \begin{align*}
    \lvert\Pr[A(\Daence/)] - \Pr[A(\Deuce/)]\rvert
    &= \lvert\Pr[A'(\XSalsa20/_{k_0})] - \Pr[A'(f)]\rvert \\
    &= \Adv^{\muPRF}_{\XSalsa20/}(A').
    \qedhere
  \end{align*}
\end{proof}

\subsection{Tying the room together}

\begin{proof}[Proof of \autoref{thm-salsa20-daence}]
  By stringing all the inequalities together, we complete the proof:
%
  \begin{align*}
    \Adv^{\muDAE}_{\Daence/}(A)
    &= \lvert\Pr[A(\Daence/)] - \Pr[A(U)]\rvert \\
    &\leq \lvert\Pr[A(\Daence/)] - \Pr[A(\Deuce/)]\rvert \\
    &\qquad + \lvert\Pr[A(\Deuce/)] - \Pr[A(U)]\rvert \\
    &\leq \Adv^{\muPRF}_{\XSalsa20/}(A') \\
    &\qquad
       + \sum_u \frac{2 D(u) + E(u)^2 + \binom{E(u)}{2}}
                     {2^{192}} \\
    &\qquad\qquad\qquad
           + \collisionbound(\ell_a(u), \ell_m(u))
             \cdot
             {\textstyle\bigl(D(u) + \binom{E(u)}{2}\bigr)}.
    \qedhere
  \end{align*}
\end{proof}

\begin{proof}[Proof of \autoref{thm-chacha-daence}]
  The \ChaCha/ version of \Daence/ uses
  \[
    \Poly1305/^2_{k_1,k_2}(
      a \concat m \concat \lvert a\rvert_8 \concat \lvert m\rvert_8)
  \]
  instead of
  \[
    \Poly1305/^2_{k_1,k_2,k_3,k_4}(a, m).
  \]
  By \autoref{lem-double-hash}, the collision probability is bounded
   by $\collisionbound(\ell_a + \ell_m + 16)$ rather than by
   $\collisionbound(\ell_a, \ell_m)$; the rest of the analysis carries
   over identically, with \XChaCha/ in the place of \XSalsa20/.
\end{proof}

\section{Shaving IAQs---Infrequently Asked Questions}

\begin{description}
  \item[Why not just use the \CAESAR/ competition winner?]
    In our estimation, the \CAESAR/
     competition\footnote{\CAESAR/: Competition for Authenticated
        Encryption: Security, Applicability, and Robustness.
       \url{https://competitions.cr.yp.to/caesar.html}}
     was too broad and dragged on for too long, and in the
     end---although it produced a wealth of valuable research---it
     failed to gain the traction it needed for real-world deployment.
    While \NaCl/, \IETF/ \ChaCha//\Poly1305/, and \AESGCM/ are
     ubiquitous today, with a variety of high-quality implementations
     available in many programming languages, the benefits of the
     \CAESAR/ winners do not seem to justify the engineering effort to
     make the novel cryptographic primitives as ubiquitous.
    In contrast, \Daence/ requires negligible effort on top of \NaCl/
     or \libsodium/.

  \item[Why not just use \AESGCMSIV/?]
    \AESGCMSIV/ is optimized for applications that can
     \emph{guarantee} hardware support for the primitives---otherwise
     it may be subject to severe performance degradation and/or timing
     side channel attacks.
    This may be reasonable when the engineer can control everything
     about the hardware and software stack, and audit the software
     stack all the way down to the hardware to ensure safety, but it's
     less appealing for a general-purpose tool.

    The \AESGCMSIV/ security guarantee requires unusually detailed
     safe usage limits~\cite[\S9]{rfc8452}, and users are advised to
     choose nonces at random---which is exactly the opposite of the
     advice for nonce-based ciphers like \AESGCM/ and \NaCl/
     \naclsecretbox/.
    This limits \AESGCMSIV/'s value as a drop-in replacement for
     nonce-based ciphers with a safety net for \Tarsnap/-style
     accidental nonce reuse
     bugs~\cite{cperciva2011tarsnap-nonce-reuse} and virtual machine
     rollbacks, and makes applications \emph{more} vulnerable to
     broken entropy sources than \Daence/ would.

  \item[Why not a prior \ChaCha//\Poly1305/-based design?]
    There have been past designs for nonce-misuse-resistant
     ciphers built with \ChaCha/ and \Poly1305/, such as HS1-SIV in
     \CAESAR/~\cite{krovetz2015hs1siv}
     and \XChaCha20/-HMAC-SHA256-SIV proposed as a now-withdrawn
     internet-draft~\cite{madden-generalised-siv-00}.

    HS1-SIV relies on nonstandard security assumptions about \ChaCha/,
     requires a large key of 176 bytes at the low end or 368 bytes
     for security comparable to \Daence/, and by using polynomial
     evaluation modulo $2^{61} - 1$ can't take advantage of existing
     high-speed constant-time \Poly1305/ logic---it is not just a few
     lines of code to call out to \ChaCha/ and \Poly1305/.

    \XChaCha20/-HMAC-SHA256-SIV is a more conservative design, but it
     uses the expensive and overpowered HMAC-SHA256 rather than taking
     advantage of cheap \Poly1305/ code that is likely to be hanging
     out in the neighbourhood of \ChaCha/ code.

    Further, despite being flavours of \SIV/, both HS1-SIV and
     \XChaCha20/-HMAC-SHA256-SIV still require nonces, which we feel is
     an unnecessary complication, addressed below.

  \item[Why not a nonce-misuse-resistant authenticated cipher?]
    If you have a nonce---say a message sequence number---then you can
     use it in the associated data to conceal repeated messages like a
     nonce-based cipher does.
    So out of \Daence/ you can build your own nonce-misuse-resistant
     authenticated cipher: just prefix a fixed-size nonce to the
     associated data!
    You can also safely incorporate a \emph{secret}
     nonce~\cite{bellare-ng-tackmann2019nonces-revisited-crypto} into
     the encrypted payload.

    But there is a conceptual cost to \emph{requiring} a nonce
     parameter \emph{and} associated data---what are you supposed to
     put in the nonce and what are you supposed to put in the
     associated data?
    The terms `nonce' and `nonce-misuse-resistant authenticated
     cipher' are confusing to non-experts (not to mention the
     British).

    The security bounds could be better if we derived a fresh key for
     each distinct nonce like \AESGCMSIV/ does.
    But \AESGCMSIV/ has weaker security bounds to begin with.
    At the level of security that \Daence/ provides, there is little
     reason to pay the interface complexity cost.

  \item[Why bother with \Salsa20/?  Why not just \ChaCha/?]
    \NaCl/ and many of its derivatives support only \Salsa20/, not
     \ChaCha/, and for \Poly1305/ only have a one-shot
     \naclonetimeauth/ function that processes a whole message at
     once.
    It is easy to implement \Salsa20/-\Daence/ in terms of this
     interface, but not \ChaCha/-\Daence/.

    On the other hand, \ChaCha//\Poly1305/ is seeing wider use after
     \IETF/ standardization in \TLS/---and systems with
     \ChaCha//\Poly1305/ will generally have the parts needed to
     implement \ChaCha/-\Daence/ just as easily.

    There is a small security advantage to the hashing in
     \Salsa20/-\Daence/; there may be a small performance advantage to
     the hashing in \ChaCha/-\Daence/; but the primary advantage to
     defining both alternatives is to reduce the engineering costs to
     adopting either one in environments that already use \NaCl/ or
     already implement \ChaCha//\Poly1305/.

  \item[Why not \ChaCha12/?]
    The reduced-round variant \ChaCha12/ is faster than \ChaCha20/
     (\ie, \ChaCha/ with the default number of rounds, 20), and still
     has a comfortable security margin from the best attacks on
     reduced-round \ChaCha/ in the literature to date.
    This is why, for instance, Google selected \ChaCha12/ in Adiantum
     disk encryption~\cite{crowley-biggers2018adiantum}.

    However, \ChaCha20/ is much more widely available in
     libraries today---\eg,
     \libsodium/,
     \OpenSSL/,
     \BearSSL/,
     \Nettle/,
     the \Rust/ \texttt{crypto::chacha20} module,
     the \Go/ \texttt{golang.org/x/crypto/chacha20} package,
     and
     the \Python/ pyca cryptography.io library,
     none of which provide \ChaCha12/.

    Similarly, \Salsa{20/12}/ was selected over \Salsa{20/20}/ in the
     \eSTREAM/ portfolio for the same performance improvement with a
     comfortable security margin, but also seems to be much less widely
     deployed than \Salsa{20/20}/.

    So although in principle \ChaCha12/ or \Salsa{20/12}/ would improve
     performance over \ChaCha20/ or \Salsa{20/20}/ at negligible
     security cost, they appear to raise the engineering costs of
     deployment in practice.

  \item[Why not use \Auth256/?]
    The \Auth256/~\cite{bernstein-chou2014auth256} message
     authentication code is based on a universal hash family with
     collision probability bounded by $1/2^{255}$ using a key as long
     as the message.
    This bound obviously seems better than the
     ${\approx}\ell^2\!/2^{206}$ bound for $\Poly1305/^2$, so why not
     reach for it?

    \margintodo{Double-check bounds!}%
    With \Daence/, even if an application allowed messages up to the
     maximum length, $2^{39}$ ($2^{38}$ bytes of associated data and
     $2^{38}$ bytes of message), exposed quadrillions of legitimate
     messages ($2^{52}$) to the adversary, and the adversary attempted
     an unimaginable $2^{100}$ forgeries, the probability of \emph{one}
     forgery would stay below $1/2^{32}$.
    So there is little \emph{security} motivation to replace
     \Poly1305/ by a larger hash.

    What about performance?
    \Auth256/, even at its best on very long messages, is not faster
     than \Poly1305/ in software.
    Maybe \Auth256/ would improve on $\Poly1305/^2$---it's not clear,
     \latin{a priori}, and since \Auth256/ requires a message-length
     key the cost would have to figure in key generation.

    But most importantly, neither \Auth256/ nor any other
     ${\approx}256$-bit universal hash family, whether in a binary
     field or large prime field, is widely implemented and deployed
     the way \Poly1305/ is.
    So---even if there may be a slim performance
     improvement---switching from \Poly1305/ would substantially raise
     the engineering costs of adopting \Daence/.

  \item[How fast is it?]
    The main cost over \naclsecretbox/ is evaluating \Poly1305/ twice
     rather than once, and completing it before starting \XSalsa20/,
     so \Salsa20/-\Daence/ should cost about 1--2x what
     \naclsecretbox/ costs.
    If the analysis survives some scrutiny, we will submit \Daence/ to
     \SUPERCOP/\footnote{\url{https://bench.cr.yp.to/}} for reliable,
     fair measurements across a variety of machines.

    But if you must see rough numbers first, on our Intel
     Kaby~Lake~i7, \SUPERCOP/ measures
     ${\approx}2.5\,\mathrm{cpb}$ for \naclsecretbox/,
     ${\approx}1.9\,\mathrm{cpb}$ for hardware-accelerated \AESGCM/,
     and
     ${\approx}3.6\,\mathrm{cpb}$ for \Salsa20/-\Daence/.
    There is room for improvement: this naïve code makes no attempt to
     compute the two \Poly1305/'s in parallel, which may be faster
     than computing them serially---both for messages exceeding the
     \CPU/ cache, and for short messages for which setting up many
     powers of the evaluation point is not worthwhile.

  \item[Why a 96-byte key (or 64-byte for \ChaCha/-\Daence/)?]
    For \ChaCha/-\Daence/, in addition to \ChaCha/ we use two
     independent \Poly1305/ instances---each requiring 16-byte keys,
     for a total of $32 + 2\cdot16 = 64$ bytes of key material---in
     order to provide high security without nonces.

    For \Salsa20/-\Daence/, in addition to \Salsa20/ we use
     \emph{four} independent \Poly1305/ instances---each requiring
     16-byte keys, for a total of $32 + 4\cdot16 = 96$ bytes of key
     material---primarily to support incorporating associated data
     without relying an incremental-update API for \Poly1305/.
    This way, \Salsa20/-\Daence/ can take advantage of the existing
     deployed \NaCl/ library which can only compute \Poly1305/ on an
     entire message.

    We could start from a 32-byte master key and then derive subkeys
     from it.
    However, doing this with the obvious tool at hand---either
     \Salsa20/ or \ChaCha/---would add hundreds of cycles to the cost
     of processing each message.
    Since many applications already use trees of key derivation for
     various purposes, we feel that the cost of deriving another few
     dozen bytes of key material---which can be cached and reused by
     the application---is not worth the cost of hundreds of additional
     cycles per message.

  \item[Can \Daence/ do streaming or random access?]
    \hskip 0pt plus 1em
    If you want to handle large files, break them into bite-size
     pieces to be encrypted as separate messages.
    You should ensure the pieces are no larger than the amount of
     memory you are willing to let an adversary waste with a forgery in
     a denial of service attack.
    In the associated data or message (depending on whether you need to
     keep it secret), include:
    \begin{itemize}
      \item
         a unique file name, so the pieces can't be swapped around
         between multiple different files;
      \item
         a piece number or byte position within the file, so the pieces
         of a single file can't be reordered;
         and
      \item
         a flag indicating whether the piece is the last one in the
         file or not, so files can't be truncated without your
         noticing.
    \end{itemize}
    Alternatively, instead of an end-of-file flag in each piece, you
     might include a manifest at the beginning of the stream specifying
     the file's size, if it is available then.

    This provides `nOAE' security~\cite{hrrv2015online-ae-crypto} like
     the `STREAM' construction.
    Additionally incorporating the tag of the previous message
     (or, really, any tag-sized substring of the previous ciphertext)
     into the associated data of the next one provides `OAE2' security,
     like the `CHAIN' construction, which provides a weak defence
     against reusing a file name for two different files, at the cost
     of losing random access.

  \item[Does \Daence/ have \INTRUP/ security?]
    Yes.

    Loosely, \INTRUP/~\cite{ablmmy2014intrup} means that even if the
     legitimate user reveals unverified plaintext in decryption
     queries, the adversary can't forge a message that passes
     verification.

    In the analysis above, the hashes $h_i$ are distributed with
     maximum probability around $1/2^{200}$ and independent of the tags
     and ciphertexts, except in the low-probability event of one of the
     collisions discussed in the analysis, so the probability that a
     decryption query reveals a key stream
     $f(t \concat 0) \concat f(t \concat 1) \concat f(t \concat 2)
      \concat \dotsb$
     any of whose blocks are related to a valid message's tag is low,
     even when the adversary chooses $t$.
    (Filling out the quantitative details is left as an exercise for
     the reader.)

    Nevertheless, we recommend zeroing any forgery immediately so this
     doesn't come up.
    \Daence/ is \emph{not} `plaintext-aware'---releasing unverified
     plaintext to a decryption query may enable the adversary to
     decrypt other messages.

    The primary motivation for \INTRUP/ (and plaintext-awareness) is as
     a safety net for the temptation of `streaming' decryption
     \emph{before} verification.
    But if you just break large files into bite-size authenticated
     pieces as described above, you get the nOAE or OAE2 security you
     would have wanted for streaming without any temptation to skip
     verification.

  \item[Isn't \Daence/ kind of boring?]
    Yes.
    That's the point.
    \Daence/ does not provide asymmetric impermeability under
     semi-consensual-plaintext attack in the Delphic oracle model, or
     achieve any asymptotic lower bound that solves an open research
     question, or have eighteen different parameters and knobs and
     bells and whistles.
    \Daence/ is boring crypto built out of parts you probably have
     lying around that you can confidently use now to avoid nonce reuse
     catastrophe.

  \item[How is the `ae' in \Daence/ pronounced?]
    Like the `a' in `data'.
\end{description}

\noindent
We do not anticipate that \Daence/ will replace \ChaCha//\Poly1305/ in
 major protocols such as \TLS/ designed by world-class cryptographers,
 which can easily take advantage of a message number guaranteed not to
 repeat.
We do hope that \Daence/ will find its way into the repertoire of
 general-purpose application engineers who need to store messages safe
 from eavesdropping and forgery in diverse software
 environments---%
 \emph{without} auditing the software stack all the way down to
  machine instructions to ensure their use of \AESGCMSIV/ is safe from
  timing side channels,
 \emph{without} adopting unusual cryptographic primitives or an
  entirely new cryptography library, and
 \emph{without} teetering on the brink of catastrophe from nonce reuse
  in \naclsecretbox/ or \AESGCM/.

\bibliography{daence}

\newpage
\appendix

\section{Tweetable implementation}

\lstinputlisting[basicstyle=\small\ttfamily,tabsize=4]{tweetdaence.c}

\section{Reference implementation}

\lstinputlisting[basicstyle=\small\ttfamily,tabsize=4,formfeed=\newpage]
  {kat_salsa20daence.c}

\newpage
\section{Test vectors}

\lstinputlisting[basicstyle=\small\ttfamily]{kat_salsa20daence.out}

\end{document}

%%  LocalWords:  pseudorandom crypto secretbox xsalsa Rogaway dae SHA
%%  LocalWords:  Shrimpton ciphertext daence HKDF ciphertexts decrypt
%%  LocalWords:  endian cryptosystem codomain th IAQs cryptographic
%%  LocalWords:  nonces quintillion priori Kaby cpb subkeys Tweetable
%%  LocalWords:  naïve ae basicstyle tabsize tweetdaence formfeed kat


%\title{Building Perfect Brackets}

\documentclass[5p, preprint]{elsarticle}

\usepackage[cmex10]{amsmath}
\usepackage[parfill]{parskip}
\usepackage{url}
\usepackage{graphicx}
\usepackage{subfig}
\usepackage{caption}
\usepackage{hyperref}

% correct bad hyphenation here
\hyphenation{op-tical net-works semi-conduc-tor}

\begin{document}

\title{Building Perfect Tournament Brackets with Data Analytics}

\author[purdue_ChE]{Christopher D. Hagmann\corref{cor1}}
\ead{chagmann@purdue.edu}

\author[purdue_BME]{Nan Kong}
\ead{nkong@purdue.edu}

\cortext[cor1]{Corresponding author}

\address[purdue_ChE]{School of Chemical Engineering, Purdue University, 480 Stadium Mall Drive, West Lafayette, IN 47907, USA}
\address[purdue_BME]{Weldon School of Biomedical Engineering, Purdue University, West Lafayette, IN 47907, USA}

\begin{abstract}
The NCAA men's basketball tournament highlights data analytics to the everyday person as they look for help building their brackets. A k-Nearest Neighbors algorithm is proposed to compare new opponents to previously played teams. A distance between teams is calculated to determine the most similar teams and to weigh the value of each win or loss to the teams. The value of $k$ is determined from previous years and applied to 2014. Results are compared to other predictions for 2014.
\end{abstract}

% Note that keywords are not normally used for peerreview papers.
\begin{keyword}
k-Nearest Neighbors (kNN); March Madness; Tempo-free Statistics.
\end{keyword}

% The paper headers
\markboth{Working Paper}%
{Hagmann \MakeLowercase{\textit{et al.}}: Building Perfect Brackets}

\maketitle

\section{Introduction}

Every March in the United States, work productivity dramatically drops as everyone turns their attention to the National Collegiate Athletic Association (NCAA) Division 1 (D-I) men's basketball tournament, known colloquially as ``March Madness."  This single elimination, or knockout, tournament consists of 64 teams in four groups of 16, with each group being ranked (or ``seeded'') so that the highly favored teams do not have to compete until later in the tournament. A popular tradition that accompanies this event is tournament pools. In tournament pools, groups of people submit fill-in tournament brackets with their predictions of which team they think will win. As most pools have prizes for the winners, more and more people are turning to data analytics to help them build the perfect tournament bracket.

This has never been as true as it was in 2014 when Warren Buffet announced a \$1,000,000,000 (USD) prize for anyone who correctly predicted all 63 games' outcomes. Figure \ref{pic:distro} shows the distribution of correctly predicted games of all 9,223,372,036,854,775,808 possible brackets, assuming that each bracket is just as likely to occur as any other bracket. Figure \ref{pic:distro} also shows the real-life distributions based on the 2013 and 2014 ESPN Tournament Challenges. In this paper, a k-Nearest Neighbors algorithm is developed to attempt to better predict the perfect bracket.

\begin{figure*}[!t]
\centering
\includegraphics[width=6.5in]{distro2.png}
\caption{Distribution of the number of games correctly picked for all possible brackets along with the distributions of the 2013 and 2014 ESPN Tournament Challenges}
\label{pic:distro}
\end{figure*}

\vspace*{-.1in}

\subsection*{Tempo-Free Statistics}

Traditionally in basketball, team and player statistics are averaged on a ``per-game" (PG) basis. As such, when looking at a stats page on the NCAA D-1 men's basketball website, one will find the abbreviations PPG (points per game),  OPP PPG, (opponent's points per game), APG (assists per game), and RPG (rebounds per game).  In recent years, however, there has been a shift by some away from these statistics in exchange for statistics that are independent of a team's tempos.

The tempo of a basketball team is defined by the number of possessions a team has in a game. In NCAA D-1 men's basketball, each team has 35 seconds to shoot the ball and at least hit the rim; otherwise, the ball is turned over to the other team.  There are some teams that will pass the ball frequently looking for the best open shot and use nearly all of this time, but there are others that try to make the first available shot they have. As such, the number of possessions a team has in a single 40-minute game can vary dramatically.

There are many arguments for tempo-free statistic. First, basketball can be viewed as a turn-based game where every possession ends with points, a missed shot, or a turnover before possession is transferred to the other team. Consequently, the offense would like to convert possessions into as many points as possible while the defense would like to prevent the other team from doing so. Second, 40 minutes is not necessarily long enough to collect an adequate sample of possessions over which to average. Third,  the number of possessions in the game will differ. Therefore,  it is easier to compare teams on the per possession basis, or in other words, to use tempo-free statistics.

For example, suppose Team A and Team B are going to play each other. Looking over the team statistices both teams average 80 points per game. They seem like a very even match; however, their tempos are 60 and 80 possessions per game, respectively. This means that Team A is averaging 4 points every 3 possessions while Team B is only averaging 4 points every 4 possessions. When teams play each other they will have nearly the same amount of possessions, save for who starts and ends with the ball. As such, it is easy to see that if the team's average points per possession hold, that Team A will beat Team B as it is more effective at converting possessions to points than Team B.

This idea of making statistics that are independent of a team's tempo, or tempo-free statistics, has been championed by analysts like Ken Pomeroy, who runs a site that provides tabulated tempo-free statistics (\href{kenpom.com}{kenpom.com}). It is important to note that all of these statistics are defined as some sort of estimate against an average D-I team. In other words, assuming a D-I team  throughout the course of the season has faced a good sample of D-I opponents, then their per-possession statistics are a good approximation for how they would do against the average D-I team.

For example, the adjusted offensive efficiency($AdjOE$) is an estimate of the number of points scored a team would have against the average D-I defense per 100 possessions. The adjusted defensive efficiency($AdjDE$) is an estimate of the number of points allowed by a team against the average D-I offense per 100 possessions.

Finally, the Pythagorean expectation($Pyth$) combines the adjusted offensive and defensive efficiencies for a D-I team. It is considered an estimate of the team's expected winning percentage against average D-I teams. In general, a Pythagorean expectation is calculated using the following formula:

\[
Pyth = \frac{\mbox{points scored} ^ 2}{\mbox{points scored} ^ 2 + \mbox{points allowed} ^ 2}.
\]

It gets its name from its resemblance to the Pythagorean equation. As each sport keeps score in dramatically different ways, each uses different measures of offense and defense as well as different exponents. For the Pythagorean expectations tabulated on \href{kenpom.com}{kenpom.com}, the formula is

\[
Pyth = \frac{AdjOE^{11.5}}{AdjOE^{11.5} + AdjDE^{11.5}},
\]

where the exponent of 11.5 was fitted by Ken Pomeroy using the 2002 - 2013 seasons' data. As a percentage, Pythagorean expectations are bounded between 0 and 1.

To help give the reader some familiarization with these statistics, the highest and lowest values among the 2014 NCAA tournament teams are given for the discussed statistics. Creighton, a No. 3 seed, had the highest adjusted offensive efficiency at 125.7 points scored per 100 possessions, while Coastal Carolina, a No. 16 seed, had the lowest at 97.3 points scored per 100 possessions. Arizona, a No. 1 seed, had the best adjusted defensive efficiency of 86.9 points allowed per 100 possessions, while Eastern Kentucky, a No. 15 seed, had an adjusted defensive efficiency of only 108.3 points allowed per 100 possessions. Arizona had the highest Pythagorean expectation at .9540 whereas Coastal Carolina had the lowest value at .3552.

\vspace*{-.1in}

\section{Current Methods}

\vspace*{-.1in}

\subsection{``Chalk''}

There are many current methods that try to predict the results of the tournament. The first, and simplest, is the idea of ``picking chalk." This is a term in sports betting that has its origins back to the day that betting odds were written on chalkboards. As more people placed bets on the favorite-to-win, the odds would be erased and changed to  reflect the moving position. This frequently left the name of the favorite-to-win obscured in the resulting chalk dust. As such, ``chalk" refers to picking the favorite-to-win~\cite{Tracy2013}. In this case, by definition of the seeding process,  it means always choosing the higher seeded team to win for any head-to-head faceoff.  As the tournament bracket explicitly gives ranks to the teams, using this method will only yield one bracket called the ``chalk" bracket. While this is a very simple idea, it usually fares well in small bracket pools.

\vspace*{-.1in}

\subsection{Log5 Method}

The other method compared in this paper is the Log5 method, created by Bill James for use in baseball \cite{James1981}.  Log5 is a method of estimating the probability one team will beat another based on their true winning percentages. A true winning percentage is the percentage of games a team \emph{should} win if they were to play sufficiently many games as to average out any amount of luck. It is suspected that the name Log5 comes from the resemblance the formula has to the logit function and the fact that it uses the assumption that the average performance across the league, $p_L$, is $.500$. The below formulation would be an estimate for team A beating team B.

{\small
\[
Log5(p_a, p_b) = \frac{\frac{p_a}{1-p_a}}{\frac{p_a}{1-p_a} + \frac{p_b}{1-p_b} * \frac{p_L}{1-p_L}} = \frac{p_a (1 - p_b)}{p_a (1 - p_b) + p_b (1 - p_a)}.
\]
}

The Log5 method has some very useful properties~\cite{Miller2008, Hammond2014}.

\begin{itemize}
\item $ 0 \leq Log5(p_a, p_b) \leq 1$.
\item $Log5(p_a, p_a) = .500$.
\item $Log5(p_b, p_a) = 1 - Log5(p_a, p_b)$.
\item $Log5(1, p_b \neq 0) = 1$.
\item $Log5(0, p_b \neq 0) = 0$.
\item $Log5(p_a, .500) = p_a$.
\item $p_a > p_b \Rightarrow Log5(p_a, p_b) > .500$.
\end{itemize}

One thing that is of importance to note is that the Log5 method relies on knowing each team's ``true" winning percentage. Currently, this is being approximated in college basketball by the Pythagorean expectation. This paper seeks to calculate a more accurate alternative to Pythagorean expectation for use in the Log5 method in order to predict game outcomes.

\vspace*{-.1in}

\section{Methodology}

To calculate the probability that a bracket will occur, there are two approaches that can be taken. The first approach is to calculate the probability of a team advancing to the next round conditional on all possible games that could occur. While this is more mathematically sound, it is much more computationally intensive to model. It also has the potential to make some strange predictions. For example, it is possible for teams that have a less than 50\% chance of winning in one round to advance to the next round if their chances of winning (or losing) in the next round are extreme ($P \leq .05 \mbox{ or }  P \geq .95)$. In this case, intuition would state that picking a team to advance when it is predicted to lose the first game would be a poor choice. However, the likelihood of a bracket where this team does advance may be greater than that of a bracket where this team is not chosen to advance, thereby possibly predicting an upset. This method will be referred to as the conditional method.

The second approach is to calculate the probability based on the teams that are actually in the match, independent of what has happened or what will happen later. In other words, each individual game is predicted based on the game alone, and the  winners are advanced to play in another independent game. This has the benefit of always choosing the team with the higher probability of winning the game, but this also means that it is less likely to predict upsets. This method will be referred to as the independent method.

\vspace*{-.1in}

\subsection*{k-Nearest Neighbors}

The k-Nearest Neighbors method is a clustering analysis method used to determine the membership of each entity based on the attributes of this entity relative to those of its $k$ neighbors \cite{Dudani1976}. For the purpose of this paper, the entity to be determined is the outcome of a game against an opponent, with its neighbors being opponents that were faced during the regular season.  Let $\theta_{a,b}$ represent the outcome of a game where $\theta_{a,b}=1$ if Team A beats Team B and zero otherwise. Then two distance-weighted values are calculated by taking into account the win and loss outcomes from playing against $t=1,\ldots,k$ opponents in the regular season similar to Team B, i.e.  $W_{a,b} \equiv\sum_{t=1}^k{(1-d_{a,t}) \, \theta_{a,t}}$ and $L_{a,b} \equiv \sum_{t=1}^k{(1-d_{a,t}) \, (1 - \theta_{a,t})}$, where a similarity index, $d_{a,t}$, was determined by using the normalized Manhattan distance between each team's Pythagorean expectation. Similarly, the calculation is performed for the opposing team, i.e., team B. Below is the formula for the predicted winning percentage for team A against teams similar to team B, $p_{a,b}$, using the win and loss parameters mentioned above.

\[
p_{a,b} = \frac{W_{a,b} + L_{b,a}}{W_{a,b} + L_{b,a} + W_{b,a} + L_{a,b}}
\]

This $p_{a,b}$, and similarly calculated $p_{b,a}$ values can then be used in the Log5 method.

\vspace*{-.1in}

\subsection*{Example}

To help illustrate this procedure, the first-round game in the 2014 tournament between fifth seeded Cincinnati and twelfth seeded Harvard is used as an example.  Cincinnati finished the regular season with a win-loss record of 27-6 ($Pyth = .8701$) and Harvard finished with a record of 25-4 ($Pyth = .8402)$. With the Log5 method using the Pythagorean expectations, one would give Cincinnati a 56\% chance of beating Harvard. However, if the 10 most similar opponents in the regular season are examined for each team ($k=10$), then Cincinnati's record against the 10 teams that they have played and are most similar to Harvard is only 5-5. This is compared to Harvard's similarly modified record of 8-2. Using the method above, Cincinnati's expected winning percentage against teams similar to Harvard is calculated as $p_{c,h} = .3760$ while that same number for Harvard is $p_{h,c} = .6240$. Using these numbers in the Log5 method would give Harvard a 73\% chance of beating Cincinnati.  When the game was played, Harvard did in fact upset Cincinnati.

\vspace*{-.1in}

\subsection*{Backtesting}

In order to determine the appropriate value for $k$, backtesting was performed on the 2003 - 2013 tournaments. The data for these seasons were provided by Ken Pomeroy. For each tournament, $k$ values of between 3 and 30 were tested with both the conditional and independent methods. The goodness of the $k$ value was measured by the number of games correctly predicted using the $k$ value minus the number of games correctly predicted using Pythagorean expectations in the Log5 method. This measure was used as the goal of this research was to calculate a more accurate alternative to Pythagorean expectation.

\vspace*{-.1in}

\section{Results}

Upon backtesting, it was determined that a $k$ value of 25 performed the best for both the conditional and independent methods, with the conditional method doing slightly better over the span tested.

These results were then applied to 2014 tournament. In Table \ref{tab_2014}, the results for the experiment can be seen, as well as some prominent results for comparison. The National Bracket compiles brackets submitted to ESPN by using a team's selection to advance on an individual's bracket as a vote for that team to advance on the compiled bracket. For example, in a first-round match, 65\% of brackets submitted to ESPN predicted No. 9 seeded Oklahoma State to defeat No. 8 seeded Gonzaga. As such, the National Bracket picked Oklahoma State advance to the second round. Repeating this for all 63 games yields one unique bracket, the National Bracket.

It should be noted that $k=25$ was also the best value for 2014, upon running all other possible values for $k$ between 3 and 30.

\vspace*{-.1in}

\section{Conclusion}

 \begin{table}[!t]
  \caption{Results for the 2014 Tournament}
  \label{tab_2014}
  \centering
  \begin{tabular}{|c|c|}
   \hline
   Bracket & Games Correct\\
   \hline
   \hline
   Conditional kNN ($k$=25) & 42\\
   Independent kNN ($k$=25) & 40\\
   President Obama          & 40\\
   ``Chalk"                 & 39\\
   The National Bracket     & 39\\
   Conditional Log5         & 38\\
   Independent Log5         & 38\\
   \hline
  \end{tabular}
 \end{table}

As a large $k$ value in general appeared to be preferred over small $k$ values, an extension of this work using a pure distance-weighted nearest neighbors algorithm where all previous opponents are examined could be promising. The data of past seasons could then be used to do a regression of the distance formula.

\vspace*{-.2in}

\section*{Acknowledgment}

The authors would like to thank Ken Pomeroy for providing them with the data necessary for this research and Sara Hagmann for her help in proof-reading this paper.

\vspace*{-.2in}

\bibliographystyle{model5-names}
\bibliography{NCAA.bib}

\end{document}


% fit table into one page

\chapter{Notation}

\begin{tabularx}{\textwidth}{l X r}
	$\intset{\ \cdot\ ,\ \cdot\ }$ & inclusive integer space & \\
	$\incircbin{\neg}$ & Boolean tensor not operator & definition \ref{tensornot} \\
	$\incircbin{\land}$ & Boolean tensor and operator & definition \ref{tensorand} \\
	$\incircbin{\lor}$ & Boolean tensor or operator & definition \ref{tensoror} \\
	$\rightsquigarrow,\rightsquigarrow_k$ & attack relation & section \ref{aaf}\\
	$\rightsquigarrow_\alpha$ & interval schedule base feasibility & definition \ref{intervalalpha} \\
	$\rightsquigarrow_\beta$ & interval schedule sequential feasibility & definition \ref{intervalbeta} \\
	$\rightsquigarrow_\gamma$ & interval schedule start feasibility & definition \ref{intervalgamma} \\
	$\rightsquigarrow_\delta$ & interval schedule finish feasibility & definition \ref{intervaldelta} \\
	$\rightsquigarrow_\varepsilon$ & interval schedule negative decision feasibility & definition \ref{intervalepsilon} \\
	$\rightsquigarrow_\zeta$ & interval schedule positive decision feasibility & definition \ref{intervalzeta} \\
	$\rightsquigarrow_\eta$ & interval schedule positive decision feasibility & definition \ref{intervaleta} \\
	$\rightsquigarrow_D$ & makespan fixed decision attack relation & definition \ref{feasibilityframework} \\
	$\rightsquigarrow_F$ & makespan feasibility attack relation & definition \ref{efficiencyframework} \\
	$\rightsquigarrow_S$ & makespan efficiency attack relation & definition \ref{fixeddecisionframework} \\
	$\twoheadrightarrow$ & tensor implementation of $\rightsquigarrow$ & section \ref{frameworkconstruction} \\
	$\twoheadrightarrow_D$ & tensor implementation of $\rightsquigarrow_D$ & definition \ref{tensorfeasiblityframework} \\
	$\twoheadrightarrow_F$ & tensor implementation of $\rightsquigarrow_F$ & definition \ref{tensorefficiencyframework} \\
	$\twoheadrightarrow_S$ & tensor implementation of $\rightsquigarrow_S$ & definition \ref{tensorfixeddecisionframework} \\
	$\prec$ & lexicographical ordering on $Args$ & appendix \ref{stabilityproof} \\
	$Args$ & set of arguments & section \ref{aaf}\\
	$D$ & user fixed decisions & section \ref{fixeddecisions} \\
	$D^-$ & user negative fixed decisions & section \ref{fixeddecisions} \\
	$D^+$ & user positive fixed decisions & section \ref{fixeddecisions} \\
	$E$ & extension & section \ref{aaf} \\
	$\mathbf{f}$ & finishing times & section \ref{interval} \\
	$i,i',i_1,i_2$ & machine index & section \ref{interval} \\
	$j,j',j_1,j_2$ & job index & section \ref{makespan} \\
	$\mathcal{J}$ & set of jobs & section \ref{makespan} \\
	$m$ & number of machines & section \ref{makespan} \\
	$\mathcal{M}$ & set of machines & section \ref{makespan} \\
	$n$ & number of jobs & section \ref{makespan} \\
	$\mathbf{p}$ & processing times & section \ref{makespan} \\
	$P,P_0,P_k$ & schedule property & section \ref{unionframeworks} \\
	$Q_l$ & post-condition on line $l$ & appendix \ref{stabilityproof} \\
\end{tabularx}
\newpage
\begin{tabularx}{\textwidth}{l X r}
	$\mathbf{s}$ & starting times & section \ref{interval} \\
	$S$ & schedule & section \ref{makespan} \\
	$t,t',t_1,t_2$ & time index & section \ref{interval} \\
	$T$ & number of timeslots & section \ref{interval} \\
	$\mathcal{T}$ & set of time indices & section \ref{interval} \\
	$\mathbf{x}$ & assignment matrix & definition \ref{assignmentmatrix} \\
\end{tabularx}


\subsection{Noise and it's Cancellation by LIGO}

Any disturbance in the surrounding could potentially act as noise for LIGO which tends to interfere with the detector and could produce it's own signal instead of a gravitational wave.

\subsubsection{Seismic Noise}

A gravitational wave is measured by monitoring the relative distance between two test mass surfaces. Any force affecting the centre of mass would then result in an ambiguous and faulty measurement. A ground-based interferometer is mechanically coupled to the earth and the masses are prone to seismically driven vibrations. The dominant part of the seismic power spectrum is at low frequencies. A moderately quiet site will have a spectrum of roughly,

\begin{equation}
    x(f) = \frac{1}{f^2} \times 10^{-8}m(Hz)^{3/2}
\end{equation}

where $x(f)$ is Band-width of the noise as a function of frequency($f$).

\begin{enumerate}
    \item Passive technique of seismic noise reduction \\

    It utilizes the inertial response of a mass on a spring. Passive isolation takes advantage of the fact that above the resonant frequency, $f_0$, of the mass-spring system, the response of the mass to driving forces decreases by $(\frac{f_0}{f})^2$ . Systems with lower resonant frequencies give higher isolation at a given frequency. These passive systems can also be staged by suspending one isolation system from the isolated stage of a previous system. The total isolation then is the product of each mass-spring system, $(\frac{f_0}{f})^{2n}$, where `$n$' is the number of stages (assuming the same resonant frequency).

    \item Active technique of seismic noise reduction \\

    Active isolation techniques employ a bootstrapping method. A proof mass is placed on the platform being isolated. The proof mass is more inertial than the platform it sits on. Monitoring the relative displacement, velocity, or acceleration between the platform and the proof mass generates an error signal when the platform has suffered a disturbance to its state. Feedback control systems are used to correct the error signal, locking the position of the platform to the inertial reference of the proof mass. \\
    The level of isolation is proportional to the closed-loop gain of the system when the sensor noise is low enough. The limits to the closed-loop gain, the isolation are the sensor’s bandwidth and noise. An advantage to arranging the isolation system in stages is that loop gain in each stage can be more modest, which is sometimes forced by the available bandwidths and mechanical resonances of the structure. LIGO I uses a simple, multi-layer passive isolation system which places a “wall” in the seismic noise spectrum at roughly 40 $Hz$. The proposed LIGO II seismic isolation is largely active \cite{giaime2000active}. A quiet hydraulic system is used externally to the vacuum chambers which house the test masses. This external system has large dynamic range, and is used primarily to take-out long-time scale drifts and disturbances. A two-stage active isolation system inside the test mass chambers is supported by the external system through bellows. The active system isolates an optical table in all six 7 degrees of freedom, from which the test mass is hung as the lower mass of a quadruple pendulum. This design is expected to move the seismic wall to $ \sim 10 Hz$
\end{enumerate}

\subsubsection{Thermal Noise}

Another noise source is due to the fact that the masses are at finite non-zero temperature. Non-zero temperature dictates that the atoms which comprise the masses, as well as the wires which suspend the masses, vibrate, according to entropy. Vibrations of the test mass atoms cause the surfaces of the mirrors to vibrate, which generates a signal. Thermal noise affecting the surface of the test mass directly is called internal thermal noise while the thermal noise from the suspension wires is called pendulum thermal noise.

\subsubsection{Optical noise}

The last of the fundamental noise sources is a limitation of the measurement process itself. The measurement process involves the interaction of light with the test masses, and the subsequent counting of the signal photons by a photo-detector. This has traditionally been thought of in terms of two uncorrelated sources - the Poissonian statistics of the counting of photons, otherwise known as shot noise, and the Poissonian statistics of the force on the test masses from photons, known as radiation pressure noise. \cite{weiss1972electronically} , \cite{saulson1994fundamentals}\\
Shot and radiation pressure noise are manifestations of the two quadrature of the vacuum. The square-law photo-diode measures the product of the amplitudes of the vacuum and the coherent light from the laser. Increasing the laser power increases the shot noise sensitivity while the radiation pressure noise sensitivity decreases. In LIGO I, 6 watts of light are incident on the interferometer, and radiation pressure noise is negligible. In LIGO II, however, 120 watts of power are planned, making radiation pressure an important factor. The shot noise spectral density is flat, while the radiation pressure amplitude spectral density has a 1/f shape. At a given frequency, the quadrature sum of the shot and radiation pressure noise can be minimized by using the right amount of power. This defines the standard quantum limit. \cite{braginsky1995quantum}

\begin{equation}
    h_{SQL}(f) = \sqrt{\frac{8\hbar}{(2\pi f)^2 mL^2}}
\end{equation}
where the minimum level of quantum noise is defined as a function of frequency `$h_{SQL}(f)$', `$m$' is  the mass of the test mass, `$L$' is the length of the interferometer arms, `$\hbar$' is the reduced plank's constant. This is actually a locus of the optimum strain spectral density at frequency `$f$' assuming the optimized input power for that frequency,
\begin{equation}
    P_{SQL} = \frac{mL^2(2\pi f)^4}{4\omega_0}
\end{equation}
where $\omega_0$ is the angular frequency of the light. This limit makes the assumption that the shot noise and the radiation pressure noise are uncorrelated. Recent work has discovered that there are correlations in the radiation pressure noise in signal tuned interferometers. \cite{buonanno18optical},\cite{buonanno2001quantum}

\pagebreak

\pagebreak