\documentclass{article}
\RequirePackage{amsmath}
\RequirePackage{bytefield}
\RequirePackage{graphicx}
\RequirePackage{newtxmath}
\RequirePackage{mathtools}
\RequirePackage{xspace}
\RequirePackage{url}
\RequirePackage{changepage}
\RequirePackage[unicode,bookmarksnumbered,bookmarksopen,pdfview=Fit]{hyperref}
\RequirePackage{nameref}
\RequirePackage{enumitem}
\RequirePackage{tabularx}
\RequirePackage{hhline}
\RequirePackage{comment}

% Fonts
\RequirePackage{lmodern}
\RequirePackage{bold-extra}
\RequirePackage{quattrocento}
\RequirePackage{dsfont}

% Quattrocento is beautiful but doesn't have an italic face. So we scale
% New Century Schoolbook italic to fit in with slanted Quattrocento and
% match its x height.
\renewcommand{\emph}[1]{{\fontfamily{pnc}\selectfont\scalebox{1.045}[0.99]{\textit{#1}}}}

% While we're at it, let's match the tt x height to Quattrocento as well.
\let\oldtexttt\texttt
\let\oldmathtt\mathtt
\renewcommand{\texttt}[1]{\scalebox{1.02}[1.07]{\oldtexttt{#1}}}
\renewcommand{\mathtt}[1]{\scalebox{1.02}[1.07]{$\oldmathtt{#1}$}}

% bold but not extended
\newcommand{\textbnx}[1]{{\fontseries{b}\selectfont #1}}


\setlength{\oddsidemargin}{-0.25in}
\setlength{\textwidth}{7in}
\setlength{\topmargin}{-0.75in}
\setlength{\textheight}{9.2in}
\setlength{\parskip}{1.5ex}
\setlength{\parindent}{0ex}
\renewcommand{\arraystretch}{1.4}
\overfullrule=2cm

\setlist[itemize]{itemsep=0.5ex,topsep=0.2ex,after=\vspace{1.5ex}}

\newcommand{\docversion}{Version unavailable (check protocol.ver)}
\InputIfFileExists{protocol.ver}{}{}

\newcommand{\doctitle}{Zcash Protocol Specification}
\newcommand{\leadauthor}{Daira Hopwood}
\newcommand{\coauthors}{Sean Bowe | Taylor Hornby | Nathan Wilcox}

\hypersetup{
  pdfborderstyle={/S/U/W 0.7},
  pdfinfo={
    Title={\doctitle, \docversion},
    Author={\leadauthor\ | \coauthors}
  }
}

\renewcommand{\sectionautorefname}{\S\!}
\renewcommand{\subsectionautorefname}{\S\!}
\renewcommand{\subsubsectionautorefname}{\S\!}
\newcommand{\crossref}[1]{\autoref{#1}\, \emph{`\nameref*{#1}\kern -0.05em'} on p.\,\pageref*{#1}}

\newcommand{\nstrut}{\rule[-.2\baselineskip]{0pt}{\baselineskip}}
\newcommand{\nsection}[1]{\section{\texorpdfstring{#1\nstrut}{#1}}}
\newcommand{\nsubsection}[1]{\subsection{\texorpdfstring{#1\nstrut}{#1}}}
\newcommand{\nsubsubsection}[1]{\subsubsection{\texorpdfstring{#1\nstrut}{#1}}}

\mathchardef\mhyphen="2D

% http://tex.stackexchange.com/a/309445/78411
\DeclareFontFamily{U}{FdSymbolA}{}
\DeclareFontShape{U}{FdSymbolA}{m}{n}{
    <-> s*[.4] FdSymbolA-Regular
}{}
\DeclareSymbolFont{fdsymbol}{U}{FdSymbolA}{m}{n}
\DeclareMathSymbol{\smallcirc}{\mathord}{fdsymbol}{"60}

\makeatletter
\newcommand{\hollowcolon}{\mathpalette\hollow@colon\relax}
\newcommand{\hollow@colon}[2]{
  \mspace{1mu}
  \vbox{\hbox{$\m@th#1\smallcirc$}\nointerlineskip\kern.45ex \hbox{$\m@th#1\smallcirc$}\kern-.06ex}
  \mspace{1mu}
}
\makeatother
\newcommand{\typecolon}{\;\hollowcolon\;}

\RequirePackage[usenames,dvipsnames]{xcolor}
% https://en.wikibooks.org/wiki/LaTeX/Colors#The_68_standard_colors_known_to_dvips
\newcommand{\eli}[1]{{\color{JungleGreen}\sf{Eli: #1}}}
\newcommand{\sean}[1]{{\color{blue}\sf{Sean: #1}}}
\newcommand{\taylor}[1]{{\color{red}\sf{Taylor: #1}}}
\newcommand{\daira}[1]{{\color{RedOrange}\sf{Daira: #1}}}
\newcommand{\nathan}[1]{{\color{ForestGreen}\sf{Nathan: #1}}}
\newcommand{\todo}[1]{{\color{Sepia}\sf{TODO: #1}}}

\newcommand{\changedcolor}{magenta}
\newcommand{\setchanged}{\color{\changedcolor}}
\newcommand{\changed}[1]{\texorpdfstring{{\setchanged{#1}}}{#1}}

% terminology

\newcommand{\term}[1]{\textsl{#1}\kern 0.05em\xspace}
\newcommand{\titleterm}[1]{#1}
\newcommand{\termbf}[1]{\textbf{#1}\xspace}
\newcommand{\conformance}[1]{\textbnx{#1}\xspace}

\newcommand{\Zcash}{\termbf{Zcash}}
\newcommand{\Zerocash}{\termbf{Zerocash}}
\newcommand{\Bitcoin}{\termbf{Bitcoin}}
\newcommand{\ZEC}{\termbf{ZEC}}
\newcommand{\zatoshi}{\term{zatoshi}}

\newcommand{\MUST}{\conformance{MUST}}
\newcommand{\MUSTNOT}{\conformance{MUST NOT}}
\newcommand{\SHOULD}{\conformance{SHOULD}}
\newcommand{\SHOULDNOT}{\conformance{SHOULD NOT}}

\newcommand{\note}{\term{note}}
\newcommand{\notes}{\term{notes}}
\newcommand{\Note}{Note}
\newcommand{\Notes}{Notes}
\newcommand{\noteCommitment}{\term{note commitment}}
\newcommand{\noteCommitments}{\term{note commitments}}
\newcommand{\NoteCommitment}{\titleterm{Note Commitment}}
\newcommand{\NoteCommitments}{\titleterm{Note Commitments}}
\newcommand{\noteCommitmentTree}{\term{note commitment tree}}
\newcommand{\joinSplitDescription}{\term{JoinSplit description}}
\newcommand{\joinSplitDescriptions}{\term{JoinSplit descriptions}}
\newcommand{\sequenceOfJoinSplitDescriptions}{\changed{sequence of} \joinSplitDescription\changed{\term{s}}\xspace}
\newcommand{\joinSplitTransfer}{\term{JoinSplit operation}}
\newcommand{\joinSplitTransfers}{\term{JoinSplit operations}}
\newcommand{\JoinSplitTransfer}{\titleterm{JoinSplit Operation}}
\newcommand{\JoinSplitTransfers}{\titleterm{JoinSplit Operations}}
\newcommand{\joinSplitSignature}{\term{JoinSplit signature}}
\newcommand{\fullnode}{\term{full node}}
\newcommand{\fullnodes}{\term{full nodes}}
\newcommand{\anchor}{\term{anchor}}
\newcommand{\anchors}{\term{anchors}}
\newcommand{\block}{\term{block}}
\newcommand{\blocks}{\term{blocks}}
\newcommand{\transaction}{\term{transaction}}
\newcommand{\transactions}{\term{transactions}}
\newcommand{\coinbaseTransaction}{\term{coinbase transaction}}
\newcommand{\coinbaseTransactions}{\term{coinbase transactions}}
\newcommand{\blockchainview}{\term{blockchain view}}
\newcommand{\mempool}{\term{mempool}}
\newcommand{\treestate}{\term{treestate}}
\newcommand{\treestates}{\term{treestates}}
\newcommand{\nullifier}{\term{nullifier}}
\newcommand{\nullifiers}{\term{nullifiers}}
\newcommand{\Nullifier}{\titleterm{Nullifier}}
\newcommand{\Nullifiers}{\titleterm{Nullifiers}}
\newcommand{\nullifierSet}{\term{nullifier set}}
\newcommand{\NullifierSet}{\titleterm{Nullifier Set}}
% Daira: This doesn't adequately distinguish between zk stuff and transparent stuff
\newcommand{\paymentAddress}{\term{payment address}}
\newcommand{\paymentAddresses}{\term{payment addresses}}
\newcommand{\viewingKey}{\term{viewing key}}
\newcommand{\viewingKeys}{\term{viewing keys}}
\newcommand{\spendingKey}{\term{spending key}}
\newcommand{\spendingKeys}{\term{spending keys}}
\newcommand{\payingKey}{\term{paying key}}
\newcommand{\transmissionKey}{\term{transmission key}}
\newcommand{\transmissionKeys}{\term{transmission keys}}
\newcommand{\keyTuple}{\term{key tuple}}
\newcommand{\notePlaintext}{\term{note plaintext}}
\newcommand{\notePlaintexts}{\term{note plaintexts}}
\newcommand{\NotePlaintexts}{\titleterm{Note Plaintexts}}
\newcommand{\notesCiphertext}{\term{transmitted notes ciphertext}}
\newcommand{\incrementalMerkleTree}{\term{incremental Merkle tree}}
\newcommand{\merkleRoot}{\term{root}}
\newcommand{\merkleNode}{\term{node}}
\newcommand{\merkleNodes}{\term{nodes}}
\newcommand{\merkleHash}{\term{hash value}}
\newcommand{\merkleHashes}{\term{hash values}}
\newcommand{\merkleLeafNode}{\term{leaf node}}
\newcommand{\merkleLeafNodes}{\term{leaf nodes}}
\newcommand{\merkleInternalNode}{\term{internal node}}
\newcommand{\merkleInternalNodes}{\term{internal nodes}}
\newcommand{\MerkleInternalNodes}{\term{Internal nodes}}
\newcommand{\merklePath}{\term{path}}
\newcommand{\merkleLayer}{\term{layer}}
\newcommand{\merkleLayers}{\term{layers}}
\newcommand{\merkleIndex}{\term{index}}
\newcommand{\merkleIndices}{\term{indices}}
\newcommand{\zkSNARK}{\term{zk-SNARK}}
\newcommand{\zkSNARKs}{\term{zk-SNARKs}}
\newcommand{\memo}{\term{memo field}}
\newcommand{\Memos}{\titleterm{Memo Fields}}
\newcommand{\keyAgreementScheme}{\term{key agreement scheme}}
\newcommand{\KeyAgreementScheme}{\titleterm{Key Agreement Scheme}}
\newcommand{\keyDerivationFunction}{\term{Key Derivation Function}}
\newcommand{\KeyDerivationFunction}{\titleterm{Key Derivation Function}}
\newcommand{\symmetricEncryptionScheme}{\term{symmetric authenticated encryption scheme}}
\newcommand{\SymmetricEncryptionScheme}{\titleterm{Symmetric Authenticated Encryption Scheme}}
\newcommand{\pseudoRandomFunction}{\term{Pseudo Random Function}}
\newcommand{\pseudoRandomFunctions}{\term{Pseudo Random Functions}}
\newcommand{\PseudoRandomFunctions}{\titleterm{Pseudo Random Functions}}

% conventions
\newcommand{\bytes}[1]{\underline{\raisebox{-0.22ex}{}\smash{#1}}}
\newcommand{\zeros}[1]{[0]^{#1}}
\newcommand{\bit}{\mathds{B}}
\newcommand{\bitseq}[1]{\bit^{#1}}
\newcommand{\bitseqs}{\bit^\star}
\newcommand{\hexint}[1]{\mathbf{0x{#1}}}
\newcommand{\dontcare}{\kern -0.06em\raisebox{0.1ex}{\footnotesize{$\times$}}}
\newcommand{\ascii}[1]{\textbf{``\texttt{#1}"}}
\newcommand{\GeneralCRH}{\mathsf{GeneralCRH}}
\newcommand{\GeneralCRHInput}{\bitseqs}
\newcommand{\GeneralHashLength}{\mathsf{\ell_{General}}}
\newcommand{\GeneralCRHOutput}{\bitseq{\GeneralHashLength}}
\newcommand{\CRHbox}[1]{\SHA\left(\;\raisebox{-1.3ex}{\usebox{#1}}\;\right)}
\newcommand{\SHA}{\mathtt{SHA256Compress}}
\newcommand{\SHAName}{\term{SHA-256 compression}}
\newcommand{\FullHash}{\mathtt{SHA256}}
\newcommand{\FullHashName}{\mathsf{SHA\mhyphen256}}
\newcommand{\BlakeHash}{\mathtt{BLAKE2b\kern 0.05em\mhyphen256}}
\newcommand{\BlakeHashName}{\term{BLAKE2b\kern 0.05em-256}}
\newcommand{\BlakeFullLength}{\term{BLAKE2b}}
\newcommand{\FullHashbox}[1]{\FullHash\left(\;\raisebox{-1.3ex}{\usebox{#1}}\;\right)}
\newcommand{\Justthebox}[2]{\;\raisebox{#2}{\usebox{#1}}\;}
\newcommand{\setof}[1]{\{{#1}\}}
\newcommand{\minimum}{\mathsf{min}}
\newcommand{\floor}{\mathsf{floor}}
\newcommand{\xor}{\oplus}

% key pairs:
\newcommand{\PaymentAddress}{\mathsf{addr_{pk}}}
\newcommand{\SpendingKey}{\mathsf{addr_{sk}}}
\newcommand{\PaymentAddressLeadByte}{\hexint{16}}
\newcommand{\PaymentAddressSecondByte}{\hexint{9A}}
\newcommand{\SpendingKeyLeadByte}{\hexint{AB}}
\newcommand{\SpendingKeySecondByte}{\hexint{36}}
\newcommand{\PaymentAddressTestnetLeadByte}{\hexint{14}}
\newcommand{\PaymentAddressTestnetSecondByte}{\hexint{51}}
\newcommand{\SpendingKeyTestnetLeadByte}{\hexint{B1}}
\newcommand{\SpendingKeyTestnetSecondByte}{\hexint{EB}}
\newcommand{\NotePlaintextLeadByte}{\hexint{00}}
\newcommand{\AuthPublic}{\mathsf{a_{pk}}}
\newcommand{\AuthPrivate}{\mathsf{a_{sk}}}
\newcommand{\AuthPrivateLength}{\mathsf{\ell_{\AuthPrivate}}}
\newcommand{\AuthPublicOld}[1]{\mathsf{a^{old}_{pk,\mathnormal{#1}}}}
\newcommand{\AuthPrivateOld}[1]{\mathsf{a^{old}_{sk,\mathnormal{#1}}}}
\newcommand{\AuthPublicNew}[1]{\mathsf{a^{new}_{pk,\mathnormal{#1}}}}
\newcommand{\AuthPrivateNew}[1]{\mathsf{a^{new}_{sk,\mathnormal{#1}}}}
\newcommand{\AddressPublicNew}[1]{\mathsf{addr^{new}_{pk,\mathnormal{#1}}}}
\newcommand{\enc}{\mathsf{enc}}
\newcommand{\DHSecret}[1]{\mathsf{dhsecret}_{#1}}
\newcommand{\EphemeralPublic}{\mathsf{epk}}
\newcommand{\EphemeralPrivate}{\mathsf{esk}}
\newcommand{\TransmitPublic}{\mathsf{pk_{enc}}}
\newcommand{\TransmitPublicNew}[1]{\mathsf{pk^{new}_{\enc,\mathnormal{#1}}}}
\newcommand{\TransmitPrivate}{\mathsf{sk_{enc}}}
\newcommand{\Value}{\mathsf{v}}
\newcommand{\ValueNew}[1]{\mathsf{v^{new}_\mathnormal{#1}}}
\newcommand{\MAXMONEY}{\mathsf{MAX\_MONEY}}
\newcommand{\pubKeyHash}{\mathsf{pubKeyHash}}
\newcommand{\hSigInput}{\mathsf{hSigInput}}
\newcommand{\dataToBeSigned}{\mathsf{dataToBeSigned}}
\newcommand{\PRFOutputLength}{\mathsf{\ell_{PRF}}}

% Notes
\newcommand{\NoteTuple}[1]{\mathbf{n}_{#1}}
\newcommand{\NotePlaintext}[1]{\mathbf{np}_{#1}}
\newcommand{\NoteCommitRand}{\mathsf{r}}
\newcommand{\NoteCommitRandOld}[1]{\mathsf{r^{old}_\mathnormal{#1}}}
\newcommand{\NoteCommitRandNew}[1]{\mathsf{r^{new}_\mathnormal{#1}}}
\newcommand{\NoteAddressRand}{\mathsf{\uprho}}
\newcommand{\NoteAddressRandOld}[1]{\mathsf{\uprho^{old}_\mathnormal{#1}}}
\newcommand{\NoteAddressRandNew}[1]{\mathsf{\uprho^{new}_\mathnormal{#1}}}
\newcommand{\NoteAddressPreRand}{\mathsf{\upvarphi}}
\newcommand{\NoteAddressPreRandLength}{\mathsf{\ell_{\NoteAddressPreRand}}}
\newcommand{\NoteCommitS}{\mathsf{s}}
\newcommand{\nf}{\mathsf{nf}}
\newcommand{\nfOld}[1]{\nf^\mathsf{old}_\mathnormal{#1}}
\newcommand{\Memo}{\mathsf{memo}}
\newcommand{\CurveMultiply}{\mathsf{Curve25519}}
\newcommand{\CurveBase}{\bytes{9}}
\newcommand{\DecryptNote}{\mathtt{DecryptNote}}
\newcommand{\Plaintext}{\mathbf{P}}
\newcommand{\Ciphertext}{\mathbf{C}}
\newcommand{\Key}{\mathsf{K}}
\newcommand{\Keyspace}{\mathcal{K}}
\newcommand{\TransmitPlaintext}[1]{\Plaintext^\enc_{#1}}
\newcommand{\TransmitCiphertext}[1]{\Ciphertext^\enc_{#1}}
\newcommand{\TransmitKey}[1]{\Key^\enc_{#1}}
\newcommand{\TransmitKeyCompare}[1]{\Key^*_{#1}}
\newcommand{\KDF}{\mathsf{KDF}}
\newcommand{\kdftag}{\mathsf{kdftag}}
\newcommand{\kdfinput}{\mathsf{kdfinput}}
\newcommand{\AsymPublic}{\mathsf{AsymPublic}}
\newcommand{\AsymPrivate}{\mathsf{AsymPrivate}}
\newcommand{\AsymSharedSecret}{\mathsf{AsymSharedSecret}}
\newcommand{\KeyAgreementGen}{\mathsf{KeyAgreementGen}}
\newcommand{\KeyAgreement}{\mathsf{KeyAgreement}}
\newcommand{\SymEncrypt}[1]{\mathsf{SymEncrypt}_{#1}}
\newcommand{\SymDecrypt}[1]{\mathsf{SymDecrypt}_{#1}}
\newcommand{\SymSpecific}{\mathsf{AEAD\_CHACHA20\_POLY1305}}
\newcommand{\SymCipher}{\mathsf{ChaCha20}}
\newcommand{\SymAuth}{\mathsf{Poly1305}}
\newcommand{\Clamp}{\mathsf{clamp_{Curve25519}}}
\newcommand{\JoinSplitSigAlg}{\mathsf{JoinSplitSigAlg}}
\newcommand{\JoinSplitSigSpecific}{\mathsf{Ed25519}}
\newcommand{\JoinSplitSigHashName}{\mathsf{SHA\mhyphen512}}
\newcommand{\PRF}[2]{\mathsf{{PRF}^{#2}_\mathnormal{#1}}}
\newcommand{\PRFaddr}[1]{\PRF{#1}{addr}}
\newcommand{\PRFnf}[1]{\PRF{#1}{\nf}}
\newcommand{\PRFpk}[1]{\PRF{#1}{pk}}
\newcommand{\PRFrho}[1]{\PRF{#1}{\NoteAddressRand}}
\newcommand{\PRFdk}[1]{\PRF{#1}{dk}}
\newcommand{\cm}{\mathsf{cm}}
\newcommand{\cmNew}[1]{\mathsf{{cm}^{new}_\mathnormal{#1}}}
\newcommand{\ReplacementCharacter}{\textsf{U+FFFD}}
\newcommand{\CryptoBoxSeal}{\mathsf{crypto\_box\_seal}}
\newcommand{\EdDSAr}{R}
\newcommand{\EdDSAs}{S}
\newcommand{\EdDSAR}{\bytes{R}}
\newcommand{\EdDSAS}{\bytes{S}}

% merkle tree
\newcommand{\MerkleDepth}{\mathsf{d}}
\newcommand{\MerkleNode}[2]{\mathsf{M}^{#1}_{#2}}
\newcommand{\MerkleSibling}{\mathsf{sibling}}
\newcommand{\MerkleCRH}{\mathsf{MerkleCRH}}
\newcommand{\MerkleHashLength}{\mathsf{\ell_{Merkle}}}
\newcommand{\MerkleHash}{\bitseq{\MerkleHashLength}}

% bitcoin
\newcommand{\vin}{\mathtt{vin}}
\newcommand{\vout}{\mathtt{vout}}
\newcommand{\nJoinSplit}{\mathtt{nJoinSplit}}
\newcommand{\vJoinSplit}{\mathtt{vJoinSplit}}
\newcommand{\vpubOldField}{\mathtt{vpub\_old}}
\newcommand{\vpubNewField}{\mathtt{vpub\_new}}
\newcommand{\vsum}[2]{\smashoperator[r]{\sum_{#1}^{#2}}}
\newcommand{\anchorField}{\mathtt{anchor}}
\newcommand{\joinSplitSig}{\mathtt{joinSplitSig}}
\newcommand{\joinSplitPubKey}{\mathtt{joinSplitPubKey}}
\newcommand{\nullifiersField}{\mathtt{nullifiers}}
\newcommand{\commitments}{\mathtt{commitments}}
\newcommand{\ephemeralKey}{\mathtt{ephemeralKey}}
\newcommand{\encCiphertexts}{\mathtt{encCiphertexts}}
\newcommand{\randomSeed}{\mathtt{randomSeed}}
\newcommand{\rt}{\mathsf{rt}}
\newcommand{\Varies}{\textit{Varies}}
\newcommand{\heading}[1]{\multicolumn{1}{c|}{#1}}
\newcommand{\type}[1]{\texttt{#1}}

\newcommand{\sighashType}{\term{SIGHASH type}}
\newcommand{\sighashTypes}{\term{SIGHASH types}}
\newcommand{\SIGHASHALL}{\mathsf{SIGHASH\_ALL}}
\newcommand{\scriptSig}{\mathtt{scriptSig}}

% JoinSplit
\newcommand{\hSig}{\mathsf{h_{Sig}}}
\newcommand{\hSigText}{\texorpdfstring{$\hSig$}{hSig}}
\newcommand{\h}[1]{\mathsf{h_{\mathnormal{#1}}}}
\newcommand{\NOld}{\mathrm{N}^\mathsf{old}}
\newcommand{\NNew}{\mathrm{N}^\mathsf{new}}
\newcommand{\allN}[1]{\mathrm{1}..\mathrm{N}^\mathsf{#1}}
\newcommand{\allOld}{\allN{old}}
\newcommand{\allNew}{\allN{new}}
\newcommand{\setofOld}{\setof{\allOld}}
\newcommand{\setofNew}{\setof{\allNew}}
\newcommand{\vmacs}{\mathtt{vmacs}}
\newcommand{\zkproofSize}{\mathtt{zkproofSize}}
\newcommand{\zkproof}{\mathtt{zkproof}}
\newcommand{\joinSplitCircuit}{\term{JoinSplit circuit}}
\newcommand{\JoinSplitCircuit}{\titleterm{JoinSplit Circuit}}
\newcommand{\JoinSplitStatement}{\texttt{JoinSplit}}
\newcommand{\JoinSplitProof}{\pi_{\JoinSplitStatement}}
\newcommand{\vpubOld}{\mathsf{v_{pub}^{old}}}
\newcommand{\vpubNew}{\mathsf{v_{pub}^{new}}}
\newcommand{\nOld}[1]{\NoteTuple{#1}^\mathsf{old}}
\newcommand{\nNew}[1]{\NoteTuple{#1}^\mathsf{new}}
\newcommand{\vOld}[1]{\mathsf{v}_{#1}^\mathsf{old}}
\newcommand{\vNew}[1]{\mathsf{v}_{#1}^\mathsf{new}}
\newcommand{\NP}{\mathsf{NP}}
\newcommand{\treepath}[1]{\mathsf{path}_{#1}}
\newcommand{\COMM}[1]{\mathsf{COMM}_{#1}}
\newcommand{\commitmentTrapdoor}{\term{commitment trapdoor}}
\newcommand{\Commitment}{\mathtt{NoteCommitment}}
\newcommand{\Uncommitted}{\mathsf{Uncommitted}}
\newcommand{\Receive}{\mathsf{Receive}}

\newcommand{\consensusrule}[1]{\subparagraph{Consensus rule:}{#1}}
\newcommand{\securityrequirement}[1]{\subparagraph{Security requirement:}{#1}}


\begin{document}

\title{\doctitle \\
\Large \docversion \\
\vspace{1ex} \large as intended for the \Zcash release of summer 2016}
\author{\Large \leadauthor \\ \Large \coauthors}
\date{\today}
\maketitle

\tableofcontents
\newpage


\nsection{Introduction}

\Zcash is an implementation of the \term{Decentralized Anonymous Payment}
scheme \Zerocash \cite{ZerocashOakland} with some adjustments to terminology,
functionality and performance. It bridges the existing \emph{transparent}
payment scheme used by \Bitcoin with a \emph{confidential} payment scheme
protected by zero-knowledge succinct non-interactive arguments of knowledge
(\zkSNARKs).

Changes from the original \Zerocash are highlighted in \changed{\changedcolor}.

This specification is structured as follows:

\begin{itemize}
  \item Notation | definitions of notation used throughout the document;
  \item Concepts | the principal abstractions needed to understand the protocol;
  \item Abstract Protocol | a high-level description of the protocol in terms
        of ideal cryptographic components;
  \item Concrete Protocol | how the functions and encodings of the abstract
        protocol are instantiated;
  \item Differences from the \Zerocash protocol | a summary of changes from the
        protocol in \cite{ZerocashOakland}.
\end{itemize}


\nsubsection{Caution}

\Zcash security depends on consensus. Should your program diverge from
consensus, its security is weakened or destroyed. The cause of the divergence
doesn't matter: it could be a bug in your program, it could be an error in
this documentation which you implemented as described, or it could be you do
everything right but other software on the network behaves unexpectedly. The
specific cause will not matter to the users of your software whose wealth is
lost.

Having said that, a specification of \emph{intended} behaviour is essential
for security analysis, understanding of the protocol, and maintenance of
Zcash Core and related software. If you find any mistake in this specification,
please contact \texttt{<security@z.cash>}. While the production \Zcash network
has yet to be launched, please feel free to do so in public even if you believe
the mistake may indicate a security weakness.


\nsection{Notation}

The notation $\hexint{}$ followed by a string of \textbf{boldface} hexadecimal
digits represents the corresponding integer converted from hexadecimal.

The notation $\bitseq{\ell}$ represents the set of sequences of $\ell$ bits.
$\bitseqs$ represents the set of bit sequences of arbitrary length.

The notation $\ascii{...}$ represents the given string represented as a
sequence of bytes in US-ASCII. For example, $\ascii{abc}$ represents the
byte sequence $[\hexint{61}, \hexint{62}, \hexint{63}]$.

The notation $\allN{}$, used as a subscript, means the sequence of values
with indices $1$ through $\mathrm{N}$ inclusive. For example,
$\AuthPublicNew{\allNew}$ means the sequence $[\AuthPublicNew{\mathrm{1}},
\AuthPublicNew{\mathrm{2}}, ...\;\AuthPublicNew{\NNew}]$.

The notation $\setof{\allN{}}$ means the set of integers from $1$ through
$\mathrm{N}$ inclusive.

The symbol $\bot$ is used to indicate unavailable information or a failed decryption.

The notation $x \typecolon T$ is used to specify that $x$ has type $T$.
A cartesian product type is represented by $S \times T$, and a function type
by $S \rightarrow T$. A subscripted argument of a function is taken to be
its first argument, e.g. if $x \typecolon X$, $y \typecolon Y$, and
$\PRF{x}{}(y) \typecolon Z$, then $\PRF{}{} \typecolon X \times Y \rightarrow Z$.

The following integer constants will be instantiated in \crossref{constants}:
$\MerkleDepth$, $\NOld$, $\NNew$, $\MerkleHashLength$, $\GeneralHashLength$,
$\PRFOutputLength$, $\AuthPrivateLength$, $\NoteAddressPreRandLength$,
$\MAXMONEY$.


\nsection{Concepts}

\nsubsection{Payment Addresses and Keys}

A \keyTuple $(\AuthPrivate, \TransmitPrivate, \PaymentAddress)$ is
generated by users who wish to receive payments under this scheme.
The \viewingKey $\TransmitPrivate$ and the \paymentAddress
$\PaymentAddress = (\AuthPublic, \TransmitPublic)$ are derived from the
\spendingKey $\AuthPrivate$.

The following diagram depicts the relations between key components.
Arrows point from a component to any other component(s) that can be derived
from it.

\begin{center}
\includegraphics[scale=.8]{key_components}
\end{center}

The composition of \paymentAddresses\changed{, \viewingKeys,} and \spendingKeys
is a cryptographic protocol detail that should not normally be
exposed to users. However, user-visible operations should be provided
to obtain a \paymentAddress or \viewingKey from a \spendingKey.

Users can accept payment from multiple parties with a single \paymentAddress
$\PaymentAddress$ and the fact that these payments are destined to
the same payee is not revealed on the blockchain, even to the
paying parties. \emph{However} if two parties collude to compare a
\paymentAddress they can trivially determine they are the same. In the
case that a payee wishes to prevent this they should create a distinct
\paymentAddress for each payer.

\subparagraph{Note:}
It is conventional in cryptography to refer to the key used to encrypt
a message in an asymmetric encryption scheme as the ``public key".
However, the public key used as the \transmissionKey component
of an address ($\TransmitPublic$) need not be publically distributed; it
has the same distribution as the \paymentAddress itself. As mentioned above,
limiting the distribution of the \paymentAddress is important for some use cases.
This also helps to reduce reliance of the overall protocol on the security
of the cryptosystem used for \note encryption (see \crossref{inband}), since
an adversary would have to know $\TransmitPublic$ in order to exploit a
hypothetical weakness in that cryptosystem.


\nsubsection{\Notes}

A \note (denoted $\NoteTuple{}$) is a tuple $\changed{(\AuthPublic, \Value,
\NoteAddressRand, \NoteCommitRand)}$ which represents that a value $\Value$ is
spendable by the recipient who holds the \spendingKey $\AuthPrivate$ corresponding
to $\AuthPublic$, as described in the previous section.

\begin{itemize}
    \item $\AuthPublic$ is a sequence of $\PRFOutputLength$ bytes representing
        the \payingKey of the recipient.
    \item $\Value$ is an integer in the range $0 \leq \Value \leq \MAXMONEY$
        representing the value of the \note in \zatoshi
        ($1$ \ZEC = $10^8$ \zatoshi).
    \item $\NoteAddressRand$ is a sequence of $\PRFOutputLength$ bytes, which is
        used as input to $\PRFnf{\AuthPrivate}$ to obtain the \note's \nullifier.
    \item $\NoteCommitRand$ is a \commitmentTrapdoor.
\end{itemize}

$\NoteCommitRand$ is randomly generated by the sender. \changed{$\NoteAddressRand$
is generated from a random seed $\NoteAddressPreRand$ using
$\PRFrho{\NoteAddressPreRand}$.} Only a commitment to these values is disclosed
publicly, which allows the tokens $\NoteCommitRand$ and $\NoteAddressRand$ to blind
the value and recipient \emph{except} to those who possess these tokens.

\nsubsubsection{\NoteCommitments} \label{abstractcomm}

The underlying $\Value$ and $\AuthPublic$ are blinded with $\NoteAddressRand$
and $\NoteCommitRand$. The resulting hash $\cm = \Commitment(\NoteTuple{})$.

$\Commitment$ is required to be a computationally binding and hiding commitment
scheme.

\nsubsubsection{\Nullifiers}

A \nullifier (denoted $\nf$) is derived from the $\NoteAddressRand$ component
of a \note as $\PRFnf{\AuthPrivate}(\NoteAddressRand)$. A \note is spent by proving
knowledge of $\NoteAddressRand$ and $\AuthPrivate$ in zero knowledge while
disclosing its \nullifier $\nf$, allowing $\nf$ to be used to prevent double-spending.

\nsubsubsection{\NotePlaintexts{} and \Memos}

Transmitted \notes are stored on the blockchain in encrypted form, together with
a \noteCommitment $\cm$.

The \notePlaintexts in a \joinSplitDescription are encrypted to the
respective \transmissionKeys $\TransmitPublicNew{\allNew}$,
and the result forms part of a \notesCiphertext (see \crossref{inband}
for further details).

Each \notePlaintext (denoted $\NotePlaintext{}$) consists of
$(\Value, \NoteAddressRand, \NoteCommitRand\changed{, \Memo})$.

The first three of these fields are as defined earlier.

\changed{
$\Memo$ represents a \memo associated with this \note. The usage of the
\memo is by agreement between the sender and recipient of the \note.
}


\nsubsection{\JoinSplitTransfers{} and Descriptions} \label{joinsplit}

A \joinSplitDescription is data included in a \transaction that describes a \joinSplitTransfer,
i.e. a confidential value transfer. This kind of value transfer is the primary
\Zcash-specific operation performed by \transactions; it uses, but should not be
confused with, the \joinSplitCircuit used for the \zkSNARK proof and verification.

A \joinSplitTransfer spends $\NOld$ \notes $\nOld{\allOld}$ and transparent input
$\vpubOld$, and creates $\NNew$ \notes $\nNew{\allNew}$ and transparent output
$\vpubNew$.


\nsubsection{\NoteCommitment{} Tree} \label{merkle}

\begin{center}
\includegraphics[scale=.4]{incremental_merkle}
\end{center}

The \noteCommitmentTree is an \incrementalMerkleTree of fixed depth used to
store \noteCommitments that \joinSplitTransfers produce. Just as the \term{unspent
transaction output set} (UTXO) used in \Bitcoin, it is used to express the existence
of value and the capability to spend it. However, unlike the UTXO, it is \emph{not}
the job of this tree to protect against double-spending, as it is append-only.

Blocks in the blockchain are associated (by all nodes) with the \merkleRoot of this tree
after all of its constituent \joinSplitDescriptions' \noteCommitments have been
entered into the tree associated with the previous block.

Each \merkleNode in the \incrementalMerkleTree is associated with a \merkleHash of
size $\MerkleHashLength$ bytes.
The \merkleLayer numbered $h$, counting from \merkleLayer $0$ at the \merkleRoot, has
$2^h$ \merkleNodes with \merkleIndices $0$ to $2^h-1$ inclusive. Let $\MerkleNode{h}{i}$
be the \merkleHash associated with the \merkleNode at \merkleIndex $i$ in \merkleLayer $h$.


\nsubsection{\NullifierSet}

Transactions insert \nullifiers into a \nullifierSet which is maintained
alongside the UTXO by all nodes.

\eli{a tx is just a string, so it doesn't insert anything. Rather, nodes process 
tx's and the ``good'' ones lead to the addition of \nullifiers to the
\nullifierSet.}

Transactions that attempt to insert a \nullifier into this set that already
exists within it are invalid as they are attempting to double-spend.

\eli{After defining \term{transaction}, one should define what a \term{legal tx} is
(this definition depends on a particular blockchain [view]) and only then can one
talk about ``attempts'' of transactions, and insertions of \nullifiers into the
\nullifierSet.}

\nsubsection{The Blockchain}

At a given point in time, the \blockchainview of each \fullnode consists of a
sequence of one or more valid \blocks. Each \block consists of a sequence of one or
more \transactions. In a given node's \blockchainview, \treestates are chained in an
obvious way:

\begin{itemize}
  \item The input \treestate of the first \block is the empty \treestate.
  \item The input \treestate of the first \transaction of a \block is the final
        \treestate of the immediately preceding \block.
  \item The input \treestate of each subsequent \transaction in a \block is the
        output \treestate of the immediately preceding \transaction.
  \item The final \treestate of a \block is the output \treestate of its last
        \transaction.
\end{itemize}

An \anchor is a Merkle tree root of a \treestate, and uniquely identifies that
\treestate given the assumed security properties of the Merkle tree's hash function.

Each \transaction is associated with a \sequenceOfJoinSplitDescriptions.
\todo{They also have a transparent value flow that interacts with the \joinSplitDescription's
\changed{$\vpubOld$ and} $\vpubNew$.}
Inputs and outputs are associated with a value.

The total value of the outputs must not exceed the total value of the inputs.

\changed{
The \anchor of each \joinSplitDescription in a \transaction must refer to either
some earlier \block's final \treestate, or to the output \treestate of any prior
\joinSplitDescription in the same \transaction.
}

These conditions act as constraints on the blocks that a \fullnode will
accept into its \blockchainview.

We rely on Bitcoin-style consensus for \fullnodes to eventually converge on their 
views of valid \blocks, and therefore of the sequence of \treestates in those 
\blocks.


\subparagraph{Value pool}

Transaction inputs insert value into a \term{value pool}, and transaction outputs 
remove value from this pool. The remaining value in the pool is available to miners 
as a fee.


\nsubsection{Coinbase Transactions}

The first \transaction in a block must be a \coinbaseTransaction, which should
collect and spend any block reward and transaction fees paid by \transactions
included in this block.

\nsubsubsection{Block Subsidy and Transaction Fees}

\todo{Describe money supply curve.}
\todo{Miner's reward = transaction fees + block subsidy - founder's reward}

\nsubsubsection{Coinbase outputs}

\todo{Coinbase maturity rule.}
\todo{Any tx with a coinbase input must have no transparent outputs (vout).}


\nsection{Abstract Protocol}

\nsubsection{Abstract Cryptographic Functions}

\nsubsubsection{Hash Functions}

$\MerkleCRH \typecolon \MerkleHash \times \MerkleHash \rightarrow \MerkleHash$
is a collision-resistant hash function used in \crossref{merkletree}.
It is instantiated in \crossref{merklecrh}.

\changed{
$\GeneralCRH \typecolon \GeneralCRHInput \rightarrow \GeneralCRHOutput$
is another collision-resistant hash function used in \crossref{hsig}.
It is instantiated in \crossref{generalcrh}.
}

\nsubsubsection{\PseudoRandomFunctions}

$\PRF{x}{}$ is a \pseudoRandomFunction seeded by $x$. \changed{Four} \emph{independent}
$\PRF{x}{}$ are needed in our protocol:
$\PRFaddr{} \typecolon $, $\PRFnf{x}$, $\PRFpk{x}$\changed{,
and $\PRFrho{x}$}. These are used in \crossref{circuit}, and instantiated in
\crossref{prfs}.

In addition to being \pseudoRandomFunctions, it is required that $\PRFnf{x}$,
$\PRFaddr{x}$\changed{, and $\PRFrho{x}$} be collision-resistant across all $x$ ---
i.e. it should not be feasible to find $(x, y) \neq (x', y')$ such that
$\PRFnf{x}(y) = \PRFnf{x'}(y')$, and similarly for $\PRFaddr{}$ \changed{and $\PRFrho{}$}.

\nsubsubsection{Symmetric Authenticated Encryption Scheme}

$\SymEncrypt{} \typecolon \Keyspace \times \Plaintext \rightarrow \Ciphertext$
is a symmetric authenticated encryption algorithm.

$\SymDecrypt{} \typecolon \Keyspace \times \Ciphertext \rightarrow
\Plaintext \cup \setof{\bot}$ is the corresponding decryption algorithm, such that
for any $\Key \in \Keyspace$ and $P \in \Plaintext$,
$\SymDecrypt{\Key}(\SymEncrypt{\Key}(P)) = P$.
$\bot$ is used to represent the decryption of an invalid ciphertext.

\securityrequirement{
$\SymEncrypt{}$ is IND-CCA2-secure provided that keys are chosen randomly and
not reused. \daira{is that still IND-CCA2?}
Also, for $\Key$ chosen at random from $\Keyspace$, it is infeasible to find
$C \in \Ciphertext$ such that $\SymDecrypt{\Key}(C) = P \neq \bot$
and $\SymEncrypt{\Key}(P) \neq C$.
}

%$\AuthEnc$ is an asymmetric authenticated encryption scheme. It consists of
%a randomized key pair generation algorithm $\AuthEncGen \typecolon () -> $,
%an encryption algorithm $\AuthEncEncrypt \typecolon \Nonce \times ...$,
%and a decryption algorithm $\AuthEncDecrypt$.

\nsubsubsection{\KeyAgreementScheme}

A \keyAgreementScheme is a cryptographic protocol in which two parties agree
a shared secret, each using their private key and the other party's public key.
Such a scheme defines a type of public keys $\AsymPublic$, a type of private
keys $\AsymPrivate$, and a type of shared secrets $\AsymSharedSecret$.

Let $\KeyAgreementGen \typecolon () \rightarrow \AsymPublic \times \AsymPrivate$
be a randomized algorithm generating a (public, private) key pair.

Let $\KeyAgreement \typecolon \AsymPrivate \times \AsymPublic \rightarrow \AsymSharedSecret$
be the agreement function.


\nsubsubsection{\KeyDerivationFunction}

A \keyDerivationFunction is defined for a particular \keyAgreementScheme and
\symmetricEncryptionScheme; it takes the shared secret produced by the key
agreement and additional arguments, and derives a key suitable for the encryption
scheme.

We define $\KDF \typecolon \setofNew \times \GeneralCRHOutput \times \AsymSharedSecret
\times \AsymPublic \times \AsymPublic \rightarrow \Keyspace$ to be a
\keyDerivationFunction, suitable for use with $\KeyAgreement$ and deriving keys
for $\SymEncrypt{}$.


\nsubsection{\JoinSplitTransfers{} and Descriptions} \label{joinsplitdesc}

A \joinSplitDescription is data included in a \transaction that describes a
\joinSplitTransfer, as described in \crossref{joinsplit}.

\changed{
\Zcash \transactions have the following additional fields:

\begin{center}
\hbadness=4000
\begin{tabularx}{0.92\textwidth}{|c|l|p{10.7em}|X|}
\hline
Bytes & \heading{Name} & \heading{Data Type} & \heading{Description} \\
\hhline{|=|=|=|=|}

\Varies & $\nJoinSplit$ & \type{compactSize uint} & The number of \joinSplitDescriptions
in $\vJoinSplit$. \\ \hline

$1026 \times \nJoinSplit$ & $\vJoinSplit$ &
\type{JoinSplitDescription} \type{[$\nJoinSplit$]} &
The \sequenceOfJoinSplitDescriptions in this \transaction. \\ \hline

33 $\dagger$ & $\joinSplitPubKey$ & \type{char[32]} & An encoding of an $\JoinSplitSigAlg$
public verification key \\ \hline

64 $\dagger$ & $\joinSplitSig$ & \type{char[64]} & A signature on a prefix of the \transaction encoding,
to be verified using $\joinSplitPubKey$. \\ \hline
\end{tabularx}
\end{center}

$\dagger$ The $\joinSplitPubKey$ and $\joinSplitSig$ fields are present if and only if
$\nJoinSplit > 0$.

The encoding of $\joinSplitPubKey$ and the data to be signed are specified in
\crossref{nonmalleability}.
}

Each \type{JoinSplitDescription} consists of:

\begin{center}
\hbadness=2000
\begin{tabularx}{0.92\textwidth}{|c|l|l|X|}
\hline
Bytes & \heading{Name} & \heading{Data Type} & \heading{Description} \\
\hhline{|=|=|=|=|}

\setchanged 8 &\setchanged $\vpubOldField$ &\setchanged \type{int64\_t} &\mbox{}\setchanged
A value $\vpubOld$ that the \joinSplitTransfer removes from the value pool. \\ \hline

8 & $\vpubNewField$ & \type{int64\_t} & A value $\vpubNew$ that the \joinSplitTransfer inserts
into the value pool. \\ \hline

32 & $\anchorField$ & \type{char[32]} & A merkle root $\rt$ of the \noteCommitmentTree at
some block height in the past, or the merkle root produced by a previous \joinSplitTransfer in
this \transaction. \sean{We need to be more specific here.} \\ \hline

64 & $\nullifiersField$ & \type{char[32][$\NOld$]} & A sequence of \nullifiers of the input
\notes $\nfOld{\allOld}$. \\ \hline

64 & $\commitments$ & \type{char[32][$\NNew$]}. & A sequence of \noteCommitments for the
output \notes $\cmNew{\allNew}$. \\ \hline

\setchanged 32 &\setchanged $\ephemeralKey$ &\setchanged \type{char[32]} &\mbox{}\setchanged
A Curve25519 public key $\EphemeralPublic$. \\ \hline

434 & $\encCiphertexts$ & \type{char[217][$\NNew$]} & A sequence of ciphertext
components for the encrypted output \notes, $\TransmitCiphertext{\allNew}$. \\ \hline

\setchanged 32 &\setchanged $\randomSeed$ &\setchanged \type{char[32]} &\mbox{}\setchanged
A 256-bit seed that must be chosen independently at random for each \joinSplitDescription. \\ \hline

64 & $\vmacs$ & \type{char[32][$\NOld$]} & A sequence of message authentication tags
$\h{\allOld}$ that bind $\hSig$ to each $\AuthPrivate$ of the
$\joinSplitDescription$. \\ \hline

288 & $\zkproof$ & \type{char[288]} & An encoding, as determined by the libsnark library
\cite{libsnark}, of the zero-knowledge proof $\JoinSplitProof$. \\ \hline

\end{tabularx}
\end{center}

The $\ephemeralKey$ and $\encCiphertexts$ fields together form the \notesCiphertext.

\consensusrule{
Either $\vpubOld$ or $\vpubNew$ \MUST be zero.
}

\todo{Describe case where there are fewer than $\NOld$ real input \notes.}

\nsubsubsection{Computation of \hSigText} \label{hsig}

\newsavebox{\hsigbox}
\begin{lrbox}{\hsigbox}
\setchanged
\begin{bytefield}[bitwidth=0.04em]{1024}
    \bitbox{256}{$256$-bit $\randomSeed$}
    \bitbox{256}{\hfill $256$-bit $\nfOld{\mathrm{1}}$\hfill...\;} &
    \bitbox{256}{$256$-bit $\nfOld{\NOld}$} &
    \bitbox{256}{$256$-bit $\joinSplitPubKey$}
\end{bytefield}
\end{lrbox}

\changed{
Given a \joinSplitDescription containing the fields $\randomSeed$ and
$\nullifiersField = \nfOld{\allOld}$, and embedded in a transaction
containing the field $\joinSplitPubKey$, we compute $\hSig$ for that
\joinSplitDescription as follows:
\begin{equation*}
\begin{aligned}
\hSigInput &:= \Justthebox{\hsigbox}{-1.3ex} \\
\hSig &:= \GeneralCRH(\ascii{ZcashComputehSig},\; \hSigInput)
\end{aligned}
\end{equation*}
}

\nsubsubsection{Merkle root validity} \label{merkletree}

\daira{This paragraph is confusing and only describes one aspect of validity.}
A \joinSplitDescription is valid if $\rt$ is a \noteCommitmentTree root found in
either the blockchain or a merkle root produced by inserting the \noteCommitments
of a previous \joinSplitDescription in the \transaction to the \noteCommitmentTree
identified by that previous \joinSplitDescription's $\anchor$.

The depth of the \noteCommitmentTree is $\MerkleDepth$.

Each \merkleNode in the \incrementalMerkleTree is associated with a \merkleHash,
which is a byte sequence. The \merkleLayer numbered $h$, counting from
\merkleLayer $0$ at the \merkleRoot, has $2^h$ \merkleNodes with \merkleIndices
$0$ to $2^h-1$ inclusive.

Let $\MerkleNode{h}{i}$ be the \merkleHash associated with the \merkleNode at
\merkleIndex $i$ in \merkleLayer $h$.

The \merkleNodes at \merkleLayer $\MerkleDepth$ are called \merkleLeafNodes.
When a \noteCommitment is added to the tree, it occupies the \merkleLeafNode
\merkleHash $\MerkleNode{\MerkleDepth}{i}$ for the next available $i$. As-yet unused
\merkleLeafNodes are associated with a distinguished \merkleHash $\Uncommitted$.
It is assumed to be infeasible to find a preimage \note $\NoteTuple{}$ such that
$\Commitment(\NoteTuple{}) = \Uncommitted$.

The \merkleNodes at \merkleLayers $0$ to $\MerkleDepth-1$ inclusive are called
\merkleInternalNodes, and are associated with $\MerkleCRH$ outputs.
\MerkleInternalNodes are computed from their children in the next \merkleLayer
as follows: for $0 \leq h < \MerkleDepth$ and $0 \leq i < 2^h$,

\hskip 2em $\MerkleNode{h}{i} := \MerkleCRH(\MerkleNode{h+1}{2i}, \MerkleNode{h+1}{2i+1})$.

A \merklePath from \merkleLeafNode $\MerkleNode{\MerkleDepth}{i}$ in the
\incrementalMerkleTree is the sequence

\hskip 2em $[\MerkleNode{h}{\MerkleSibling(h, i)} \text{ for }
h \text{ from } \MerkleDepth \text{ down to } 1]$,

where

\hskip 2em $\MerkleSibling(h, i) = \floor\left(\frac{i}{2^{\MerkleDepth-h}}\right) \xor 1$

and $\xor$ denotes bitwise exclusive or. Given such a \merklePath, it is
possible to verify that \merkleLeafNode $\MerkleNode{\MerkleDepth}{i}$ is in a tree
with a given \merkleRoot $\rt = \MerkleNode{0}{0}$.

\nsubsubsection{Non-malleability} \label{nonmalleability}

\changed{
\Bitcoin defines several \sighashTypes that cover various parts of a transaction.
In \Zcash, all of these \sighashTypes are extended to cover the \Zcash-specific
fields $\nJoinSplit$, $\vJoinSplit$, and (if present) $\joinSplitPubKey$.
They \emph{do not} cover the field $\joinSplitSig$.

\consensusrule{
If $\nJoinSplit > 0$, the \transaction{} \MUSTNOT use \sighashTypes other than
$\SIGHASHALL$.
}

Let $\dataToBeSigned$ be the hash of the \transaction using the $\SIGHASHALL$
\sighashType. Note that this \emph{excludes} all of the $\scriptSig$ fields in
the non-\Zcash-specific parts of the \transaction.

In order to ensure that a \joinSplitDescription is cryptographically bound to the
transparent inputs and outputs corresponding to $\vpubNew$ and $\vpubOld$, and
to the other \joinSplitDescriptions in the same \transaction, an ephemeral $\JoinSplitSigAlg$
key pair is generated for each \transaction, and the $\dataToBeSigned$ is
signed with the private signing key of this key pair. The corresponding public
verification key is included in the \transaction encoding as $\joinSplitPubKey$.

$\JoinSplitSigAlg$ is instantiated as $\JoinSplitSigSpecific$ \cite{ed25519},
with the additional requirement that $\EdDSAs$ (the integer represented
by $\EdDSAS$) must be less than the prime
$\ell = 2^{252} + 27742317777372353535851937790883648493$ defined in \cite{ed25519},
otherwise the signature is considered invalid.
Note that $\JoinSplitSigSpecific$ is defined as using $\JoinSplitSigHashName$
internally.

If $\nJoinSplit$ is zero, the $\joinSplitPubKey$ and $\joinSplitSig$ fields are
omitted. Otherwise, a \transaction has a correct \joinSplitSignature if
$\joinSplitSig$ can be verified as an encoding of a signature on $\dataToBeSigned$
as specified above, using the $\JoinSplitSigSpecific$ public key encoded as
$\joinSplitPubKey$.
}

\newsavebox{\sigbox}
\begin{lrbox}{\sigbox}
\setchanged
\begin{bytefield}[bitwidth=0.075em]{512}
    \bitbox{256}{$256$-bit $\EdDSAR$}
    \bitbox{256}{$256$-bit $\EdDSAS$}
\end{bytefield}
\end{lrbox}

\changed{
The encoding of a signature is:
}
\begin{itemize}
  \item[] $\Justthebox{\sigbox}{-1.3ex}$
\end{itemize}

\changed{
where $\EdDSAR$ and $\EdDSAS$ are as defined in \cite{ed25519}.

The encoding of a public key is as defined in \cite{ed25519}.
}

The condition enforced by the \joinSplitCircuit specified in \crossref{nonmalleablepour}
ensures that a holder of all of $\AuthPrivateOld{\allOld}$ for each
\joinSplitDescription has authorized the use of the private signing key corresponding
to $\joinSplitPubKey$ to sign this \transaction.


\nsubsubsection{Balance}

A \joinSplitTransfer can be seen, from the perspective of the \transaction, as
an input \changed{and an output simultaneously}.
\changed{$\vpubOld$ takes value from the value pool and}
$\vpubNew$ adds value to the value pool. As a result, \changed{$\vpubOld$ is
treated like an \emph{output} value, whereas} $\vpubNew$ is treated like an
\emph{input} value.

\changed{
Note that unlike original \Zerocash \cite{ZerocashOakland}, \Zcash does not have
a distinction between Mint and Pour operations. The addition of $\vpubOld$ to a
\joinSplitDescription subsumes the functionality of both Mint and Pour. Also,
\joinSplitDescriptions are indistinguishable regardless of the number of real input
\notes.

As stated in \crossref{pourdesc}, either $\vpubOld$ or $\vpubNew$ \MUST be zero.
No generality is lost because, if a \transaction in which both $\vpubOld$ and
$\vpubNew$ were nonzero were allowed, it could be replaced by an equivalent one
in which $\minimum(\vpubOld, \vpubNew)$ is subtracted from both of these values.
This restriction helps to avoid unnecessary distinctions between \transactions
according to client implementation.
}

\nsubsubsection{\NoteCommitments{} and \Nullifiers}

A \transaction that contains one or more \joinSplitDescriptions, when entered into the
blockchain, appends to the \noteCommitmentTree with all constituent
\noteCommitments. All of the constituent \nullifiers are also entered into the
\nullifierSet of the \blockchainview \emph{and} \mempool. A \transaction is not
valid if it attempts to add a \nullifier to the \nullifierSet that already
exists in the set.

\nsubsubsection{\JoinSplitCircuit{} and Proofs} \label{circuit}

In \Zcash, $\NOld$ and $\NNew$ are both $2$.

A valid instance of $\JoinSplitProof$ assures that given a \term{primary input}:

\begin{itemize}
  \item[] $(\rt, \nfOld{\allOld}, \cmNew{\allNew}, \changed{\vpubOld,\;}
\vpubNew, \hSig, \h{\allOld})$,
\end{itemize}

there exists a witness of \term{auxiliary input}:

\begin{itemize}
  \item[] $(\treepath{\allOld}, \nOld{\allOld}, \AuthPrivateOld{\allOld},
\nNew{\allNew}\changed{, \NoteAddressPreRand})$
\end{itemize}

where:

\begin{itemize}
  \item[] for each $i \in \setofOld$: $\nOld{i} = (\AuthPublicOld{i},
\vOld{i}, \NoteAddressRandOld{i}, \NoteCommitRandOld{i})$;
  \item[] for each $i \in \setofNew$: $\nNew{i} = (\AuthPublicNew{i},
\vNew{i}, \NoteAddressRandNew{i}, \NoteCommitRandNew{i})$
\end{itemize}

such that the following conditions hold:

\subparagraph{Merkle path validity} \label{merklepathvalidity}

for each $i \in \setofOld$ \changed{$\mid$ $\vOld{i} \neq 0$}:
$\treepath{i}$ must be a valid \merklePath of depth $\MerkleDepth$, as defined in
\crossref{merkle}, from $\Commitment(\nOld{i})$ to \noteCommitmentTree root $\rt$.

\textbf{Note:} Merkle path validity covers both conditions 1. (a) and 1. (d) of the NP statement
given in section 4.2 of \cite{ZerocashOakland}.

\subparagraph{Balance}

$\changed{\vpubOld\; +} \vsum{i=1}{\NOld} \vOld{i} = \vpubNew + \vsum{i=1}{\NNew} \vNew{i}$.

\subparagraph{\Nullifier{} integrity}

for each $i \in \setofNew$:
$\nfOld{i} = \PRFnf{\AuthPrivateOld{i}}(\NoteAddressRandOld{i})$.

\subparagraph{Spend authority}

for each $i \in \setofOld$:
$\AuthPublicOld{i} = \changed{\PRFaddr{\AuthPrivateOld{i}}(0)}$.

\subparagraph{Non-malleability} \label{nonmalleablepour}

for each $i \in \setofOld$:
$\h{i} = \PRFpk{\AuthPrivateOld{i}}(i, \hSig)$.

\changed{
\subparagraph{Uniqueness of $\NoteAddressRandNew{i}$} \label{uniquerho}

for each $i \in \setofNew$:
$\NoteAddressRandNew{i} = \PRFrho{\NoteAddressPreRand}(i, \hSig)$.
}

\subparagraph{Commitment integrity}

for each $i \in \setofNew$: $\cmNew{i}$ = $\Commitment(\nNew{i})$.


\nsubsection{In-band secret distribution} \label{inband}

In order to transmit the secret $\Value$, $\NoteAddressRand$, and $\NoteCommitRand$
(necessary for the recipient to later spend) \changed{and also a \memo} to the
recipient \emph{without} requiring an out-of-band communication channel, the
\transmissionKey $\TransmitPublic$ is used to encrypt these
secrets. The recipient's possession of the associated \keyTuple
$(\AuthPrivate, \TransmitPrivate, \PaymentAddress)$ is used to reconstruct
the original \note \changed{ and \memo}.

All of the resulting ciphertexts are combined to form a \notesCiphertext.

\nsubsubsection{Encryption}

\changed{
Let $\SymEncrypt{\Key}(\Plaintext)$ be authenticated encryption using
$\SymSpecific$ \cite{rfc7539} encryption of plaintext $\Plaintext$, with empty
``associated data", all-zero nonce $\zeros{96}$, and 256-bit key $\Key$.

Similarly, let $\SymDecrypt{\Key}(\Ciphertext)$ be $\SymSpecific$
decryption of ciphertext $\Ciphertext$, with empty ``associated data",
all-zero nonce $\zeros{96}$, and 256-bit key $\Key$. The result is either
the plaintext byte sequence, or $\bot$ indicating failure to decrypt.
}

Let $\TransmitPublicNew{\allNew}$ be the \changed{Curve25519} public keys
for the intended recipient addresses of each new \note, and let
$\NotePlaintext{\allNew}$ be the \notePlaintexts. Let $\hSig$ be the
value computed in \crossref{hsig}. Let $\KDF$ be the \keyDerivationFunction
instantiated in \crossref{kdf}.

Then to encrypt:
\begin{itemize}
\changed{
  \item Generate a new Curve25519 (public, private) key pair
$(\EphemeralPublic, \EphemeralPrivate)$.
  \item For $i \in \setofNew$,
    \begin{itemize}
      \item Let $\TransmitPlaintext{i}$ be the raw encoding of $\NotePlaintext{i}$.
      \item Let $\DHSecret{i} := \CurveMultiply(\EphemeralPrivate,
\TransmitPublicNew{i})$.
      \item Let $\TransmitKey{i} := \KDF(i, \hSig, \DHSecret{i}, \EphemeralPublic,
\TransmitPublicNew{i})$.
      \item Let $\TransmitCiphertext{i} :=
\SymEncrypt{\TransmitKey{i}}(\TransmitPlaintext{i})$.
    \end{itemize}
}
\end{itemize}

The resulting \notesCiphertext is $\changed{(\EphemeralPublic,
\TransmitCiphertext{\allNew})}$.

\nsubsubsection{Decryption by a Recipient}

Let $\PaymentAddress = (\AuthPublic, \TransmitPublic)$ be the recipient's
\paymentAddress, and let $\TransmitPrivate$ be the recipient's \viewingKey.
Let $\hSig$ be the value computed in \crossref{hsig}.
Let $\cmNew{\allNew}$ be the \noteCommitments of each output coin.
Then for each $i \in \setofNew$, the recipient will attempt to decrypt that ciphertext
component as follows:

\changed{
\begin{itemize}
  \item Let $\DHSecret{i} := \CurveMultiply(\TransmitPrivate, \EphemeralPublic)$.
  \item Let $\TransmitKey{i} := \KDF(i, \hSig, \DHSecret{i}, \EphemeralPublic,
\TransmitPublicNew{i})$.
  \item Return $\DecryptNote(\TransmitKey{i}, \TransmitCiphertext{i}, \cmNew{i},
\AuthPublic).$
\end{itemize}

$\DecryptNote(\TransmitKey{i}, \TransmitCiphertext{i}, \cmNew{i}, \AuthPublic)$
is defined as follows:

\begin{itemize}
  \item Let $\TransmitPlaintext{i} :=
\SymDecrypt{\TransmitKey{i}}(\TransmitCiphertext{i})$.
  \item If $\TransmitPlaintext{i} = \bot$, return $\bot$.
  \item Extract $\NotePlaintext{i} = (\ValueNew{i},
\NoteAddressRandNew{i}, \NoteCommitRandNew{i}, \Memo_i)$ from $\TransmitPlaintext{i}$.
  \item If $\Commitment((\AuthPublic, \ValueNew{i}, \NoteAddressRandNew{i},
\NoteCommitRandNew{i})) \neq \cmNew{i}$, return $\bot$, else return $\NotePlaintext{i}$.
\end{itemize}
}

Note that this corresponds to step 3 (b) i. and ii. (first bullet point) of the
$\Receive$ algorithm shown in Figure 2 of \cite{ZerocashOakland}.

To test whether a \note is unspent in a particular \blockchainview also requires
the \spendingKey $\AuthPrivate$; the coin is unspent if and only if
$\nf = \PRFnf{\AuthPrivate}(\NoteAddressRand)$ is not in the \nullifierSet
for that \blockchainview.

Note that a \note can change from being unspent to spent on a given \blockchainview,
as \transactions are added to that view. Also, blockchain reorganisations can cause
the \transaction in which a \note was output to no longer be on the consensus
blockchain.


\changed{
\nsubsubsection{Commentary}

The public key encryption used in this part of the protocol is based loosely on
other encryption schemes based on Diffie-Hellman over an elliptic curve, such
as ECIES or the $\CryptoBoxSeal$ algorithm defined in libsodium \cite{cryptoboxseal}.
Note that:
}
\begin{itemize}
\changed{
  \item The same ephemeral key is used for all encryptions to the recipient keys
        in a given \joinSplitDescription.
  \item In addition to the Diffie-Hellman secret, the KDF takes as input the
        seed $\hSig$, the public keys of both parties, and the index $i$.
  \item The nonce parameter to $\SymSpecific$ is not used.
  \item The ``IETF" definition of $\SymSpecific$ from \cite{rfc7539} is
used; this uses a 32-bit block count and a 96-bit nonce, rather than a 64-bit
block count and 64-bit nonce as in the original definition of $\SymCipher$.
}
\end{itemize}


\nsection{Concrete Protocol}

\nsubsection{Integers, Bit Sequences, and Endianness}

All integers in \emph{\Zcash-specific} encodings are unsigned, have a fixed
bit length, and are encoded in little-endian byte order. \changed{The
$\SymSpecific$ encryption scheme \cite{rfc7539} used in \crossref{inband}
uses length fields encoded as little-endian. Also, Curve25519 public and
private keys are defined as byte sequences, which are converted from integers
using little-endian encoding.}

In bit layout diagrams, each box of the diagram represents a sequence of bits.
The bit length is given explicitly in each box, except for the case of a single
bit, or for the notation $\zeros{n}$ which represents the sequence of $n$ zero bits.

The entire diagram represents the sequence of \emph{bytes} formed by first
concatenating these bit sequences, and then treating each subsequence of 8 bits
as a byte with the bits ordered from \emph{most significant} to
\emph{least significant}. Thus the \emph{most significant} bit in each byte
is toward the left of a diagram. Where bit fields are used, the text will
clarify their position in each case.

\begin{comment}
\todo{Update example for big-bit-endian order.}

\newsavebox{\exampleabox}
\begin{lrbox}{\exampleabox}
\setchanged
\begin{bytefield}[bitwidth=1.3em]{32}
        \bitbox{1}{0} &
        \bitbox{1}{1} &
        \bitbox{1}{0} &
        \bitbox{1}{0} &
        \bitbox{16}{16 bit $\hexint{ABCD}$} &
        \bitbox{12}{12 bit $\hexint{123}$} &
\end{bytefield}
\end{lrbox}

\newsavebox{\examplebbox}
\begin{lrbox}{\examplebbox}
\setchanged
\begin{bytefield}[bitwidth=1.3em]{32}
        \bitbox{4}{4 bit $\hexint{2}$} &
        \bitbox{4}{4 bit $\hexint{D}$} &
        \bitbox{4}{4 bit $\hexint{C}$} &
        \bitbox{4}{4 bit $\hexint{B}$} &
        \bitbox{4}{4 bit $\hexint{A}$} &
        \bitbox{4}{4 bit $\hexint{3}$} &
        \bitbox{4}{4 bit $\hexint{2}$} &
        \bitbox{4}{4 bit $\hexint{1}$} &
\end{bytefield}
\end{lrbox}

\newsavebox{\examplecbox}
\begin{lrbox}{\examplecbox}
\setchanged
\begin{bytefield}[bitwidth=1.3em]{32}
        \bitbox{8}{8 bit $\hexint{D2}$} &
        \bitbox{8}{8 bit $\hexint{BC}$} &
        \bitbox{8}{8 bit $\hexint{3A}$} &
        \bitbox{8}{8 bit $\hexint{12}$} &
\end{bytefield}
\end{lrbox}

For example, the following diagrams are all equivalent:
\begin{itemize}
  \item[] $\Justthebox{\exampleabox}{-1.3ex}$
  \item[] $\Justthebox{\examplebbox}{-1.3ex}$
  \item[] $\Justthebox{\examplecbox}{-1.3ex}$
\end{itemize}

and represent the byte sequence $[\hexint{D2}, \hexint{BC}, \hexint{3A}, \hexint{12}]$.
\end{comment}

\nsubsection{Constants} \label{constants}

Define:

\begin{itemize}
  \item[] $\MerkleDepth = 32$
  \item[] $\NOld = 2$
  \item[] $\NNew = 2$
  \item[] $\MerkleHashLength = 256$
  \item[] $\GeneralHashLength = 256$
  \item[] $\PRFOutputLength = 256$
  \item[] $\AuthPrivateLength = 252$
  \item[] $\NoteAddressPreRandLength = 252$
  \item[] $\Uncommitted = \zeros{\MerkleHashLength}$
  \item[] $\MAXMONEY = 2.1 \times 10^{15}$.
\end{itemize}


\nsubsection{Concrete Cryptographic Functions}

\nsubsubsection{Merkle Tree Hash Function} \label{merklecrh}

$\MerkleCRH$ is used to hash \incrementalMerkleTree \merkleHashes.
It is instantiated by the $\SHAName$ function, which takes a 512-bit block
and produces a 256-bit hash. \cite{sha2}

\newsavebox{\merklebox}
\begin{lrbox}{\merklebox}
\begin{bytefield}[bitwidth=0.04em]{512}
    \bitbox{256}{$256$-bit $\mathsf{left}$} &
    \bitbox{256}{$256$-bit $\mathsf{right}$}
\end{bytefield}
\end{lrbox}

\hskip 2em $\MerkleCRH(\mathsf{left}, \mathsf{right}) := \CRHbox{\merklebox}$.

Note that $\SHA$ is not the same as the $\FullHashName$ function,
which hashes arbitrary-length sequences.

\securityrequirement{
$\SHA$ is collision-resistant, and it is infeasible to find a preimage $x$
such that $\SHA(x) = \zeros{256}$.
}

\nsubsubsection{General Hash Function} \label{generalcrh}

\changed{
$\GeneralCRH$ is a collision-resistant hash function. It is used in
the computation of $\hSig$ in \crossref{hsig}.

It is instantiated by $\BlakeHashName$ --- that is, $\BlakeFullLength$ with
an output digest length of 32 bytes. $\GeneralCRH(p, x)$ applies unkeyed
$\BlakeHashName$, as defined in \cite{blake2}, to a 16-byte personalization
string $p$ and input $x$.

Note that $\BlakeHashName$ is not the same as $\BlakeFullLength$ truncated to
256 bits.

\securityrequirement{
$\BlakeHashName(p, x)$ is collision-resistant for
$p = \ascii{ZcashECDSAPublicKey}$ and for $p = \ascii{ZcashComputehSig}$.
}
}

\nsubsubsection{\PseudoRandomFunctions} \label{prfs}

$\PRF{x}{}$ is a \pseudoRandomFunction seeded by $x$. \changed{Four} \emph{independent}
$\PRF{x}{}$ are needed in our scheme: $\PRFaddr{x}$, $\PRFnf{x}$, $\PRFpk{x}$\changed{,
and $\PRFrho{x}$}.

It is required that $\PRFnf{x}$, $\PRFaddr{x}$\changed{, and $\PRFrho{x}$} be
collision-resistant across all $x$ --- i.e. it should not be feasible to find
$(x, y) \neq (x', y')$ such that $\PRFnf{x}(y) = \PRFnf{x'}(y')$, and similarly for
$\PRFaddr{}$ \changed{and $\PRFrho{}$}.

In \Zcash, the $\SHAName$ function is used to construct all of these
functions.

\newcommand{\iminusone}{\hspace{0.3pt}\scriptsize{$i$\hspace{0.6pt}-1}}

\newsavebox{\addrbox}
\begin{lrbox}{\addrbox}
\setchanged
\begin{bytefield}[bitwidth=0.06em]{512}
    \bitbox{18}{$1$} &
    \bitbox{18}{$1$} &
    \bitbox{18}{$0$} &
    \bitbox{18}{$0$} &
    \bitbox{224}{$252$-bit $x$} &
    \bitbox{56}{$8$-bit $t$} &
    \bitbox{200}{$\zeros{248}$}
\end{bytefield}
\end{lrbox}

\newsavebox{\nfbox}
\begin{lrbox}{\nfbox}
\setchanged
\begin{bytefield}[bitwidth=0.06em]{512}
    \bitbox{18}{$1$} &
    \bitbox{18}{$1$} &
    \bitbox{18}{$1$} &
    \bitbox{18}{$0$} &
    \bitbox{224}{$252$-bit $\AuthPrivate$} &
    \bitbox{256}{$256$-bit $\NoteAddressRand$}
\end{bytefield}
\end{lrbox}

\newsavebox{\pkbox}
\begin{lrbox}{\pkbox}
\setchanged
\begin{bytefield}[bitwidth=0.06em]{512}
    \bitbox{18}{$0$} &
    \bitbox{18}{\iminusone} &
    \bitbox{18}{$0$} &
    \bitbox{18}{$0$} &
    \bitbox{224}{$252$-bit $\AuthPrivate$} &
    \bitbox{256}{$256$-bit $\hSig$}
\end{bytefield}
\end{lrbox}

\newsavebox{\rhobox}
\begin{lrbox}{\rhobox}
\setchanged
\begin{bytefield}[bitwidth=0.06em]{512}
    \bitbox{18}{$0$} &
    \bitbox{18}{\iminusone} &
    \bitbox{18}{$1$} &
    \bitbox{18}{$0$} &
    \bitbox{224}{$252$-bit $\NoteAddressPreRand$} &
    \bitbox{256}{$256$-bit $\hSig$}
\end{bytefield}
\end{lrbox}

\begin{equation*}
\begin{aligned}
\setchanged \PRFaddr{x}(t) &\setchanged := \CRHbox{\addrbox} \\
\PRFnf{\AuthPrivate}(\NoteAddressRand) &:= \CRHbox{\nfbox} \\
\PRFpk{\AuthPrivate}(i, \hSig) &:= \CRHbox{\pkbox} \\
\setchanged \PRFrho{\NoteAddressPreRand}(i, \hSig) &\setchanged := \CRHbox{\rhobox}
\end{aligned}
\end{equation*}

\changed{
\subparagraph{Note:}
The first four bits --i.e. the most significant four bits of the first byte--
are used to distinguish different uses of $\SHA$, ensuring that the functions
are independent. In addition to the inputs shown here, the bits $\mathtt{1011}$
in this position are used to distinguish uses of the full $\FullHashName$ hash
function --- see \crossref{concretecomm}.
(The specific bit patterns chosen here are motivated by the possibility of future
extensions that either increase $\NOld$ and/or $\NNew$ to 3, or that add an
additional bit to $\AuthPrivate$ to encode a new key type, or that require an
additional PRF.)
}

\nsubsubsection{\KeyDerivationFunction} \label{kdf}

\newsavebox{\kdftagbox}
\begin{lrbox}{\kdftagbox}
\setchanged
\begin{bytefield}[bitwidth=0.16em]{128}
    \bitbox{64}{$64$-bit $\ascii{ZcashKDF}$} &
    \bitbox{32}{$8$-bit $i\!-\!1$}
    \bitbox{56}{$\zeros{56}$}
\end{bytefield}
\end{lrbox}

\newsavebox{\kdfinputbox}
\begin{lrbox}{\kdfinputbox}
\setchanged
\begin{bytefield}[bitwidth=0.04em]{1024}
    \bitbox{256}{$256$-bit $\hSig$}
    \bitbox{256}{$256$-bit $\DHSecret{i}$} &
    \bitbox{256}{$256$-bit $\EphemeralPublic$} &
    \bitbox{256}{$256$-bit $\TransmitPublicNew{i}$} &
\end{bytefield}
\end{lrbox}

\changed{
$\BlakeHashName$ is also used to construct the \keyDerivationFunction $\KDF$.

Define:

\hskip 1.5em $\KDF(i, \hSig, \DHSecret{i}, \EphemeralPublic, \TransmitPublicNew{i}) :=
\GeneralCRH(\kdftag, \kdfinput)$

where:

\hskip 1.5em $\kdftag := \Justthebox{\kdftagbox}{-1.3ex}$

\hskip 1.5em $\kdfinput := \Justthebox{\kdfinputbox}{-1.3ex}$.

and $\GeneralCRH$ is instantiated by $\BlakeHashName$ as defined in the
preceding section.
}


\nsubsection{Key Components}

\changed{$\AuthPrivate$ is 252 bits.}
$\AuthPublic$, $\TransmitPrivate$, and $\TransmitPublic$, are each 256 bits.

\changed{$\AuthPublic$, $\TransmitPrivate$ and $\TransmitPublic$ are derived
as follows:}
{\hfuzz=50pt
\begin{equation*}
\begin{aligned}
\AuthPublic &:= \changed{\PRFaddr{\AuthPrivate}(0)} \\
\TransmitPrivate &:= \changed{\Clamp(\PRFaddr{\AuthPrivate}(1))} \\
\TransmitPublic &:= \changed{\CurveMultiply(\TransmitPrivate, \CurveBase)}
\end{aligned}
\end{equation*}
}

\changed{
where
\begin{itemize}
  \item $\CurveMultiply(\bytes{n}, \bytes{q})$ performs point
multiplication of the Curve25519 public key represented by the byte
sequence $\bytes{q}$ by the Curve25519 secret key represented by the
byte sequence $\bytes{n}$, as defined in section 2 of \cite{Curve25519};
  \item $\CurveBase$ is the public byte sequence representing the Curve25519
base point;
  \item $\Clamp(\bytes{x})$ takes a 32-byte sequence $\bytes{x}$ as input
and returns a byte sequence representing a Curve25519 private key, with
bits ``clamped'' as described in section 3 of \cite{Curve25519}:
``clear bits $0, 1, 2$ of the first byte, clear bit $7$ of the last byte,
and set bit $6$ of the last byte.'' Here the bits of a byte are numbered
such that bit $b$ has numeric weight $2^b$.
\end{itemize}
}

\nsubsection{Note Components}

\begin{itemize}
    \item $\AuthPublic$ is a 32-byte \payingKey of the recipient.
    \item $\Value$ is a 64-bit unsigned integer representing the value of the
        \note in \zatoshi ($1$ \ZEC = $10^8$ \zatoshi).
    \item $\NoteAddressRand$ is a 32-byte $\PRFnf{\AuthPrivate}$ preimage.
    \item $\NoteCommitRand$ is a 32-byte \commitmentTrapdoor.
\end{itemize}

\nsubsection{\NoteCommitments} \label{concretecomm}

The underlying $\Value$ and $\AuthPublic$ are blinded with $\NoteAddressRand$
and $\NoteCommitRand$ \changed{using the collision-resistant hash function $\FullHash$}.
The resulting hash $\cm = \Commitment(\NoteTuple{})$.

\newsavebox{\cmbox}
\begin{lrbox}{\cmbox}
\setchanged
\begin{bytefield}[bitwidth=0.036em]{840}
    \bitbox{24}{$1$} &
    \bitbox{24}{$0$} &
    \bitbox{24}{$1$} &
    \bitbox{24}{$1$} &
    \bitbox{24}{$0$} &
    \bitbox{24}{$0$} &
    \bitbox{24}{$0$} &
    \bitbox{24}{$0$} &
    \bitbox{256}{$256$-bit $\AuthPublic$} &
    \bitbox{128}{$64$-bit $\Value$} &
    \bitbox{256}{$256$-bit $\NoteAddressRand$}
    \bitbox{256}{$256$-bit $\NoteCommitRand$} &
\end{bytefield}
\end{lrbox}

\changed{
\hskip 1em $\cm := \FullHashbox{\cmbox}$

\subparagraph{Note:}
The leading byte of the $\FullHash$ input is $\hexint{B0}$.
}


\nsubsection{\NotePlaintexts{} and \Memos} \label{notept}

Transmitted \notes are stored on the blockchain in encrypted form, together with
a \noteCommitment $\cm$.

The \notePlaintexts associated with a \joinSplitDescription are encrypted to the
respective \transmissionKeys $\TransmitPublicNew{\allNew}$,
and the result forms part of a \notesCiphertext (see \crossref{inband}
for further details).

Each \notePlaintext (denoted $\NotePlaintext{}$) consists of
$(\Value, \NoteAddressRand, \NoteCommitRand\changed{, \Memo})$.

The first three of these fields are as defined earlier.
\changed{$\Memo$ is a 128-byte \memo associated with this \note.

The usage of the \memo is by agreement between the sender and recipient of the
\note. The \memo{} \SHOULD be encoded either as:
\begin{itemize}
  \item a UTF-8 human-readable string \cite{Unicode}, padded by appending zero bytes; or
  \item an arbitrary sequence of 128 bytes starting with a byte value of $\hexint{F5}$
        or greater, which is therefore not a valid UTF-8 string.
\end{itemize}

In the former case, wallet software is expected to strip any trailing zero bytes
and then display the resulting \mbox{UTF-8} string to the recipient user, where applicable.
Incorrect UTF-8-encoded byte sequences should be displayed as replacement characters
(\ReplacementCharacter).

In the latter case, the contents of the \memo{} \SHOULDNOT be displayed. A start byte
of $\hexint{F5}$ is reserved for use by automated software by private agreement.
A start byte of $\hexint{F6}$ or greater is reserved for use in future \Zcash
protocol extensions.
}

The encoding of a \notePlaintext consists of, in order:
\begin{equation*}
\begin{bytefield}[bitwidth=0.029em]{1608}
\changed{
    \bitbox{192}{$8$-bit $\NotePlaintextLeadByte$}
  &}\bitbox{192}{$64$-bit $\Value$} &
    \bitbox{256}{$256$-bit $\NoteAddressRand$} &
    \bitbox{256}{\changed{$256$}-bit $\NoteCommitRand$} &
    \changed{\bitbox{800}{$\Memo$ ($128$ bytes)}}
\end{bytefield}
\end{equation*}

\begin{itemize}
\changed{
    \item A byte, $\NotePlaintextLeadByte$, indicating this version of the
        encoding of a \notePlaintext.
}
    \item 8 bytes specifying $\Value$.
    \item 32 bytes specifying $\NoteAddressRand$.
    \item \changed{32} bytes specifying $\NoteCommitRand$.
\changed{
    \item 128 bytes specifying $\Memo$.
}
\end{itemize}

\nsubsection{Encoding Addresses and Keys}

This section describes how \Zcash encodes \paymentAddresses\changed{, \viewingKeys,}
and \spendingKeys.

Addresses and keys can be encoded as a byte sequence; this is called
the \term{raw encoding}. This byte sequence can then be further encoded using
Base58Check. The Base58Check layer is the same as for upstream \Bitcoin
addresses \cite{Base58Check}.

$\SHAName$ outputs are always represented as sequences of 32 bytes.

The language consisting of the following encoding possibilities is prefix-free.

\nsubsubsection{Transparent Payment Addresses}

These are encoded in the same way as in \Bitcoin \cite{Base58Check}.

\nsubsubsection{Transparent Private Keys}

These are encoded in the same way as in \Bitcoin \cite{Base58Check}.

\nsubsubsection{Protected Payment Addresses}

A \paymentAddress consists of $\AuthPublic$ and $\TransmitPublic$.
$\AuthPublic$ is a $\SHAName$ output.
$\TransmitPublic$ is a \changed{Curve25519} public key, for use with the
encryption scheme defined in \crossref{inband}.

The raw encoding of a \paymentAddress consists of:

\begin{equation*}
\begin{bytefield}[bitwidth=0.07em]{520}
\changed{
    \bitbox{80}{$8$-bit $\PaymentAddressLeadByte$}
    \bitbox{80}{$8$-bit $\PaymentAddressSecondByte$}
  &}\bitbox{256}{$256$-bit $\AuthPublic$} &
    \bitbox{256}{\changed{$256$}-bit $\TransmitPublic$}
\end{bytefield}
\end{equation*}

\begin{itemize}
\changed{
    \item Two bytes $[\PaymentAddressLeadByte, \PaymentAddressSecondByte]$,
        indicating this version of the raw encoding of a \Zcash \paymentAddress
        on the production network. (Addresses on the test network use
        $[\PaymentAddressTestnetLeadByte, \PaymentAddressTestnetSecondByte]$
        instead.)
}
    \item 256 bits specifying $\AuthPublic$.
    \item \changed{256 bits} specifying $\TransmitPublic$, \changed{using the
        normal encoding of a Curve25519 public key \cite{Curve25519}}.
\end{itemize}

\nsubsubsection{Spending Keys}

A \spendingKey consists of $\AuthPrivate$, which is a sequence of \changed{252} bits.

The raw encoding of a \spendingKey consists of, in order:

\begin{equation*}
\begin{bytefield}[bitwidth=0.07em]{264}
\changed{
    \bitbox{80}{$8$-bit $\SpendingKeyLeadByte$}
    \bitbox{80}{$8$-bit $\SpendingKeySecondByte$}
    \bitbox{32}{$\zeros{4}$} &
  &}\bitbox{252}{\changed{$252$}-bit $\AuthPrivate$}
\end{bytefield}
\end{equation*}

\begin{itemize}
\changed{
    \item Two bytes $[\SpendingKeyLeadByte, \SpendingKeySecondByte]$,
        indicating this version of the raw encoding of a \Zcash \spendingKey
        on the production network. (Addresses on the test network use
        $[\SpendingKeyTestnetLeadByte, \SpendingKeyTestnetSecondByte]$
        instead.)
    \item 4 zero padding bits.
}
    \item \changed{252} bits specifying $\AuthPrivate$.
\end{itemize}

\changed{
The zero padding occupies the most significant 4 bits of the third byte.

\subparagraph{Note:} If an implementation represents $\AuthPrivate$
internally as a sequence of 32 bytes with the 4 bits of zero padding
intact, it will be in the correct form for use as an input to
$\PRFaddr{}$, $\PRFnf{}$, and $\PRFpk{}$ without need for bit-shifting.
Future key representations may make use of these padding bits.
}


\nsection{Differences from the Zerocash paper}

\nsubsection{Transaction Structure} \label{trstructure}

\Zerocash introduces two new operations, which are described in
the paper as new transaction types, in addition to the original
transaction type of the cryptocurrency on which it is based
(e.g. \Bitcoin).

In \Zcash, there is only the original \Bitcoin transaction type,
which is extended to contain a sequence of zero or more
\Zcash-specific operations.

This allows for the possibility of chaining transfers of protected
value in a single \Zcash \transaction, e.g. to spend a protected \note
that has just been created. (In \Zcash, we refer to value stored in
UTXOs as ``transparent'', and value stored in \joinSplitTransfer output
\notes as ``protected''.)
This was not possible in the \Zerocash design without using multiple
transactions. It also allows transparent and protected transfers to
happen atomically --- possibly under the control of nontrivial script
conditions, at some cost in distinguishability.

\todo{Describe changes to signing.}


\nsubsection{Unification of Mints and Pours}

In the original \Zerocash protocol, there were two kinds of transaction
relating to protected \notes:
\begin{itemize}
  \item a ``Mint'' transaction takes value from transparent UTXOs as
input and produces a new protected \note as output.
  \item a ``Pour'' transaction takes up to $\NOld$ protected
\notes as input, and produces up to $\NNew$ protected \notes and a
transparent UTXO as output.
\end{itemize}

Only ``Pour'' transactions included a \zkSNARK proof.

In \Zcash, the sequence of operations added to a \transaction
(described in \crossref{trstructure}) consists only of \joinSplitTransfers.
A \joinSplitTransfer is a Pour operation generalized to take a transparent
UTXO as input, allowing \joinSplitTransfers to subsume the functionality of
Mints. An advantage of this is that a \Zcash \transaction that takes
input from an UTXO can produce up to $\NNew$ output \notes, improving
the indistinguishability properties of the protocol. A related change
conceals the input arity of the \joinSplitTransfer: an unused (zero-value)
input is indistinguishable from an input that takes value from a \note.

This unification also simplifies the fix to the Faerie Gold attack
described below, since no special case is needed for Mints.


\nsubsection{\Memos}

\Zcash adds a \memo sent from the creator of a \joinSplitDescription to
the recipient of each output \note. This feature is described in
more detail in \crossref{notept}.


\nsubsection{Faerie Gold attack and fix}

When a protected \note is created in \Zerocash, the creator is
supposed to choose a new $\NoteAddressRand$ value at random.
The \nullifier of the \note is derived from its \spendingKey
($\AuthPrivate$) and $\NoteAddressRand$. The \noteCommitment
is derived from the recipient address component $\AuthPublic$,
the value $\Value$, and the commitment trapdoor $\NoteCommitRand$,
as well as $\NoteAddressRand$. However nothing prevents creating
multiple \notes with different $\Value$ and $\NoteCommitRand$
(hence different \noteCommitments) but the same $\NoteAddressRand$.

An adversary can use this to mislead a \note recipient, by sending
two \notes both of which are verified as valid by $\Receive$ (as
defined in Figure 2 of \cite{ZerocashOakland}), but only one of
which can be spent.

We call this a ``Faerie Gold'' attack --- referring to various Celtic
legends in which faeries pay mortals in what appears to be gold,
but which soon after reveals itself to be leaves, gorse blossoms,
gingerbread cakes, or other less valuable things \cite{LG2004}.

This attack does not violate the security definitions given in
\cite{ZerocashOakland}. The issue could be framed as a problem
either with the definition of Completeness, or the definition of
Balance:

\begin{itemize}
  \item The Completeness property asserts that a validly received
\note can be spent provided that its \nullifier does not appear
on the ledger. This does not take into account the possibility
that distinct \notes, which are validly received, could have the
same \nullifier. That is, the security definition depends on
a protocol detail --\nullifiers-- that is not part of the
intended abstract security property, and that could be implemented
incorrectly.
  \item The Balance property only asserts that an adversary cannot
obtain \emph{more} funds than they have minted or received via
payments. It does not prevent an adversary from causing others'
funds to decrease. In a Faerie Gold attack, an adversary can cause
spending of a \note to reduce (to zero) the effective value of another
\note for which the attacker does not know the \spendingKey, which
violates an intuitive conception of global balance.
\end{itemize}

These problems with the security definitions need to be repaired,
but doing so is outside the scope of this specification. Here we
only describe how \Zcash addresses the immediate attack.

It would be possible to address the attack by requiring that a
recipient remember all of the $\NoteAddressRand$ values for all
\notes they have ever received, and reject duplicates (as proposed
in \cite{GGM2016}). However, this requirement would interfere
with the intended \Zcash feature that a holder of a \spendingKey
can recover access to (and be sure that they are able to spend) all
of their funds, even if they have forgotten everything but the
\spendingKey.

Instead, \Zcash enforces that an adversary must choose distinct values
for each $\NoteAddressRand$, by making use of the fact that all of the
\nullifiers in \joinSplitDescriptions that appear in a valid \blockchainview
must be distinct. The \nullifiers are used as input to $\BlakeHashName$
to derive a public value $\hSig$ which uniquely identifies the transaction,
as described in \crossref{hsig}. ($\hSig$ was already used in \Zerocash
in a way that requires it to be unique in order to maintain
indistinguishability of \joinSplitDescriptions; adding the \nullifiers
to the input of the hash used to calculate it has the effect of making
this uniqueness property robust even if the \transaction creator is an
adversary.)

The $\NoteAddressRand$ value for each output \note is then derived from
a random private seed $\NoteAddressPreRand$ and $\hSig$ using
$\PRFrho{\NoteAddressPreRand}$. The correct construction of
$\NoteAddressRand$ for each output \note is enforced by the circuit
(see \crossref{uniquerho}).

Now even if the creator of a \joinSplitDescription does not choose
$\NoteAddressPreRand$ randomly, uniqueness of \nullifiers and
collision resistance of both $\BlakeHashName$ and $\PRFrho{}$ will ensure
that the derived $\NoteAddressRand$ values are unique, at least for
any two \joinSplitDescriptions that get into a valid \blockchainview.
This is sufficient to prevent the Faerie Gold attack.


\nsubsection{Internal hash collision attack and fix}

The \Zerocash security proof requires that the composition of
$\COMM{\NoteCommitRand}$ and $\COMM{\NoteCommitS}$ is a computationally
binding commitment to its inputs $\AuthPublic$, $\Value$, and
$\NoteAddressRand$. However, the instantiation of $\COMM{\NoteCommitRand}$
and $\COMM{\NoteCommitS}$ in section 5.1 of the paper did not meet
the definition of a binding commitment at a 128-bit security level.
Specifically, the internal hash of $\AuthPublic$ and $\NoteAddressRand$
is truncated to 128 bits (motivated by providing statistical hiding
security). This allows an attacker, with a work factor on the order of
$2^{64}$, to find distinct values of $\NoteAddressRand$ with colliding
outputs of the truncated hash, and therefore the same \noteCommitment.
This would have allowed such an attacker to break the balance property
by double-spending \notes, potentially creating arbitrary amounts of
currency for themself. \cite{fixingvulns}

\Zcash uses a simpler construction with a single $\FullHash$ evaluation
for the commitment. The motivation for the nested construction in \Zerocash
was to allow Mint transactions to be publically verified without requiring
a ZK proof (as described under step 3 in section 1.3 of
\cite{ZerocashOakland}). Since \Zcash combines ``Mint'' and ``Pour''
transactions into a generalized \joinSplitTransfer which always uses a ZK proof,
it does not require the nesting. A side benefit is that this reduces the
number of $\SHA$ evaluations needed to compute each \noteCommitment from
three to two, saving a total of four $\SHA$ evaluations in the
\joinSplitCircuit.

Note that \Zcash \noteCommitments are not statistically hiding, and
so \Zcash does not support the ``everlasting anonymity'' property
described in section 8.1 of the \Zerocash paper \cite{ZerocashOakland},
even when used as described in that section. While it is possible to
define a statistically hiding, computationally binding commitment scheme
for this use at a 128-bit security level, the overhead of doing so
within the circuit was not considered to justify the benefits.

\nsubsection{Changes to PRF inputs and truncation}

\todo{}

%The need for collision resistance of \CRH(.) truncated to 253 bits was not
%explicitly stated in \ (This does not follow from collision resistance of $\CRH$.)

\nsubsection{In-band secret distribution}

\todo{}

\nsubsection{Omission in \Zerocash security proof}

\todo{see \cite{ticket836}}

\nsubsection{Miscellaneous}

\begin{itemize}
    \item The paper defines a \note as a tuple $(\AuthPublic, \Value,
\NoteAddressRand, \NoteCommitRand, \NoteCommitS, \cm)$, whereas this specification
defines it as $(\AuthPublic, \Value, \NoteAddressRand, \NoteCommitRand)$.
This is just a clarification, because the instantiation of $\COMM{\NoteCommitS}$
in section 5.1 of the paper did not use $\NoteCommitS$ (and neither does the
new instantiation of $\Commitment$). $\cm$ can be computed from the other
fields.
\end{itemize}


\nsection{Acknowledgements}

The inventors of \Zerocash are Eli Ben-Sasson, Alessandro Chiesa,
Christina Garman, Matthew Green, Ian Miers, Eran Tromer, and Madars
Virza.

The authors would like to thank everyone with whom they have discussed
the \Zerocash protocol design; in addition to the inventors, this includes
Mike Perry, Isis Lovecruft, Leif Ryge, Andrew Miller, Zooko Wilcox,
Samantha Hulsey, jl777, and no doubt others.

The Faerie Gold attack was found by Zooko Wilcox.
The internal hash collision attack was found by Taylor Hornby.
The omission in the \Zerocash security proof relating to collision-resistance
of $\PRFaddr{}$ was found by Daira Hopwood.


\nsection{Change history}

\subparagraph{2016.0-beta-1}

\begin{itemize}
    \item Major reorganisation to separate the abstract cryptographic protocol
          from the algorithm instantiations.
    \item Switch the \joinSplitSignature scheme to Ed25519, with consequent
          changes to the computation of $\hSig$.
    \item Fix the lead bytes in \paymentAddress and \spendingKey encodings to
          match the implemented protocol.
    \item Clarify cryptographic security requirements and added definitions
          relating to the in-band secret distribution.
    \item Add various citations: the ``Fixing Vulnerabilities in the Zcash
          Protocol'' blog post, and several crypto papers for security definitions.
    \item Add \joinSplitTransfers to the Concepts section.
    \item Add a section on Coinbase Transactions.
    \item Add type declarations for functions.
    \item Add an acknowledgement for jl777.
    \item Fix a \texttt{Makefile} compatibility problem with the escaping behaviour
          of \texttt{echo}.
    \item Make the date format in references more consistent.
    \item Change main font to Quattrocento.
\end{itemize}

\subparagraph{2016.0-alpha-3}

\begin{itemize}
    \item Change version numbering convention (no other changes).
\end{itemize}

\subparagraph{2.0-alpha-3}

\begin{itemize}
    \item Allow anchoring to any previous output \treestate in the same \transaction,
          rather than just the immediately preceding output \treestate.
    \item Add change history.
\end{itemize}

\subparagraph{2.0-alpha-2}

\begin{itemize}
    \item Change from truncated \BlakeFullLength to \BlakeHashName.
    \item Clarify endianness, and that uses of \BlakeHashName are unkeyed.
    \item Minor correction to what \sighashTypes cover.
    \item Add ``as intended for the \Zcash release of summer 2016" to title page.
    \item Require $\PRFaddr{}$ to be collision-resistant. \cite{ticket836}
    \item Add specification of path computation for the \incrementalMerkleTree.
    \item Add a note in \crossref{merklepathvalidity} about how this condition
          corresponds to conditions in the \Zerocash paper.
    \item Changes to terminology around keys.
\end{itemize}

\subparagraph{2.0-alpha-1}

\begin{itemize}
    \item First version intended for public review.
\end{itemize}


\nsection{References}

\begingroup
\renewcommand{\section}[2]{}
\bibliographystyle{plain}
\bibliography{zcash}
\endgroup

\end{document}
