\documentclass[11pt]{article}
\newcommand{\tuple}[1]{\ensuremath \langle #1 \rangle}
\usepackage{color}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{mathrsfs}
\usepackage{amssymb}
\usepackage{algpseudocode}% http://ctan.org/pkg/algorithmicx
\usepackage[all]{xy}
\usepackage{varwidth}

\newtheorem{theorem}{Theorem}
\newtheorem{prop}{Proposition}
\newtheorem{lem}{Lemma}
\newtheorem{defn}{Definition}
\newcommand{\note}[1]{{\color{red} \bf [[#1]]}}
\newcommand{\push}[1][1]{\hskip\dimexpr #1\algorithmicindent\relax}
\newcommand*\xor{\mathbin{\oplus}}
\algnewcommand{\LeftComment}[1]{\Statex \(\triangleright\) #1}
\begin{document}


\setlength\parindent{0pt} % Removes all indentation from paragraphs - comment this line for an assignment with lots of text


\section{\textbf{Introduction}}

\section{\textbf{Client}}

\subsection{\textbf{Client Notation Conventions}}


$k$ is key of entry \\
$v$ is value of entry \\
$size$ is a size (target size of the current block chain) \\
$kv$ is a key-value pair $\tuple{k,v}$ \\
$KV$ is a set of $kv$ \\
$id$ is a machine ID \\
$seq$ is a sequence number \\
$hmac_p$ is the HMAC value of the previous slot \\
$hmac_c$ is the HMAC value of the current slot \\
$Guard$ is a set of$ \tuple{k,v,$logical operator$}$ which can be evaluated to a boolean \\

$trans$ is a transaction entry , $\tuple{seq, id, KV, Guard}$  \\
$lastmsg$ is a last message entry, $\tuple{seq, id}$ \\
$qstate$ is a queue state entry, $\tuple{size}$ \\
$colres$ is a collision resolution entry, $\tuple{id, seq_{old}, seq_{new}, true \lor false}$ \\
$newkey$ is a new key entry, $\tuple{seq, k, id}$, $id$ is ID of arbitrator \\
$commit$ is a commit transaction entry, $\tuple{seq_{trans},KV}$, id is id of arbitrator \\
$abort$ is an abort transaction entry, $\tuple{seq_{trans},id_{trans}}$ \\


$de$ is a data entry that can one of: $trans$, $lastmsg$, $qstate$, $colres$, $newkey$, $commit$, $abort$ \\
$DE$ is a set of all data entries, possibly of different types, in a single message, set of $de$\\

$slotDat = \tuple{seq,id,DE,hmac_p,hmac_c}$ \\
$slot = \tuple{seq, Encrpt(slotDat)}$\\

\subsection{\textbf{Client State}}

\subsubsection{Constants}
$LOCAL\_ID$ = machine ID of this client.\\
$RESIZE\_THRESH\_PERCENT$ = percent of slots that need to have live data to trigger a resize.\\
$RESIZE\_PERCENT$ = percent that we should grow the block chain to.\\
$DATA\_ENTRY\_SET\_MAX\_SIZE$ = max size that a data entry set can have (in bytes).\\
$DEAD\_SLOT\_COUNT$ = number of slots to keep dead if possible at the end of the block chain.\\
$MAX\_RESCUE\_SKIPS$ = number of skips that are allowed when saving data entries.\\

\subsubsection{Primitive Variables}
$max\_size$ = max size of the block chain\\

\subsubsection{Sets and Lists}


$PendingTrans= \tuple{KV, Guard} = \tuple{$set of key value pairs, set of guard conditions$}$.\\
$Arbitrator$ = set of $\tuple{k,id}$ containing the key and its arbitrating device.\\
$LastSlot$ = set of $\tuple{id, seq}$ containing the machine ID and the largest sequence number from that machine ID.\\
$LocalSlots$ = set of slots that are in the clients local buffer (initially $\emptyset$), data is decrypted.\\
$RejectedSlotList$ = ordered list of the sequence numbers of slots that this client tried to insert but were rejected.\\


\subsection{Helper Functions}
The following helper functions are needed:\\

% Get Size
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get Byte Size:}\\
Get the size in bytes of the thing that is passed in.\\
\begin{algorithmic}[1]
\Function{GetSize}{$a$}
    \State \Return{Size in bytes of $a$}
\EndFunction
\end{algorithmic}\end{varwidth}% 
}

% Error
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{ Error:}\\
Prints an error message and halts the execution of the client.\\
\begin{algorithmic}[1]
\Function{Error}{$msg$}
    \State $Print(msg)$
    \State $Halt()$
\EndFunction
\end{algorithmic}\end{varwidth}% 
}

% Get Next Sequence Number
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get Next Sequence Number:}\\
Get the next sequence number for insertion into the block chain.\\
\begin{algorithmic}[1]
\Function{GetNextSeq}{$k$}
    \LeftComment{Get the largest known sequence number}
    \State $seq_{ret} \gets seq$ such that $\tuple{seq, DE}\in LocalSlots \land (\forall \tuple{seq', DE'} \in LocalSlots, seq \geq seq')$\\
    
    \LeftComment{Add one to the largest seq number to generate the new seq number}
    \State \Return{$seq_{ret} + 1$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Get Arbitrator
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get Arbitrator:}\\
Get the arbitrator for a given key.\\
\begin{algorithmic}[1]
\Function{GetArbitrator}{$k$}
    \State $\tuple{k_1,id_1} \gets \tuple{k_2,id_2} $ \textit{such that} $ \tuple{k_2,id_2} \in Arbitrator \land k_2=k$    
    \State \Return{$id_1$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check Transaction arbitrator
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Arbitrator for a Transaction:}\\
Check that the arbitrators for a given set are all the same arbitrator.\\
\begin{algorithmic}[1]
\Function{CheckArbitrator}{$PendingTrans_a$}
    \State $id_{arb} \gets NULL$\\
    \State $\tuple{KV_a, Guard_a} \gets PendingTrans_a$
    
    \ForAll{$\tuple{k',v'} \in KV_a$}
        \State $id' \gets$ \Call{GetArbitrator}{$k'$}\\
        
        \If{$id_{arb} = NULL$}  
            \State $id_{arb} \gets id'$
        \ElsIf{$id' \neq id_{arb}$} \Comment{Check all arbitrators are the same}
            \State \Call{Error}{"Multiple arbitrators for key values in transaction."}
        \EndIf
    \EndFor
    
    \ForAll{$\tuple{k',v', lop'} \in Guard_a$}
        \State $id' \gets$ \Call{GetArbitrator}{$k'$}\\
        
        \If{$id_{arb} = NULL$}  
            \State $id_{arb} \gets id'$
        \ElsIf{$id' \neq id_{arb}$} \Comment{Check all arbitrators are the same}
            \State \Call{Error}{"Multiple arbitrators for key values in transaction."}
        \EndIf
    \EndFor
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Get all Commits
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all Commits:}\\
Get all commits that are currently in the local block chain.  Iterate over all the local slots and extract all the commits from each slot.\\
\begin{algorithmic}[1]
\Function{GetCommits}{$ $}
    \State $ComSet \gets \emptyset$ \Comment{Set of the commits}\\
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq_2',id',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \State $ComSet \gets ComSet \cup \{c |c \in DE',c$is a $commit\}$
    \EndFor
    \State \Return{$ComSet$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Get all Transactions
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all Transactions:}\\
Get all transactions that are currently in the local block chain.  Iterate over all the local slots and extract all the transactions from each slot.\\
\begin{algorithmic}[1]
\Function{GetTrans}{$ $}
    \State $TransSet \gets \emptyset$ \Comment{Set of the trans}\\
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq_2',id',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \State $TransSet \gets TransSet \cup \{c |c \in DE',c$is a $trans\}$
    \EndFor
    \State \Return{$TransSet$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Get all aborts
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all aborts:}\\
Get all aborts that are currently in the local block chain.  Iterate over all the local slots and extract all the aborts from each slot.\\
\begin{algorithmic}[1]
\Function{GetAborts}{$ $}
    \State $AbrtSet \gets \emptyset$ \Comment{Set of the aborts}\\
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq_2',id',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \State $AbrtSet \gets AbrtSet \cup \{c |c \in DE',c$is a $abort\}$
    \EndFor
    \State \Return{$AbrtSet$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Get all Queue States
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all queue states:}\\
Get all qstates that are currently in the local block chain.  Iterate over all the local slots and extract all the qstates from each slot.\\
\begin{algorithmic}[1]
\Function{GetQStates}{$ $}
    \State $QSet \gets \emptyset$ \Comment{Set of the qstates}\\
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq_2',id',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \State $QSet \gets QSet \cup \{c |c \in DE',c$is a $qstate\}$
    \EndFor
    \State \Return{$QSet$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Get all Last Messages States
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all last message data entrues:}\\
Get all last msg that are currently in the local block chain.  Iterate over all the local slots and extract all the last msg from each slot.\\
\begin{algorithmic}[1]
\Function{GetLastMsg}{$ $}
    \State $LMSet \gets \emptyset$ \Comment{Set of the last msg}\\
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq_2',id',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \State $LMSet \gets LMSet \cup \{c |c \in DE',c$is a $lastmsg\}$
    \EndFor
    \State \Return{$LMSet$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check Queue State Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Queue State Live:}\\
A queue state is dead if there is another queue state data entry that has a larger queue state.\\
\begin{algorithmic}[1]
\Function{CheckQStateLive}{$qstate_a$}
    \State $\tuple{size_a} \gets qstate_a$
    \State $AllQStates \gets$ \Call{GetQState}{} \Comment{Get all the qstates} \\
    
    \If{$\exists \tuple{size'} \in AllQStates, size' > size_a$}
        \State \Return{false}
    \EndIf
    \State \Return{true}
    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check Commit Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Commit Live:}\\
A commit is dead if for every key value pair in the commit there is a commit with a larger transaction sequence number that has a key value pair with the same key.\\
\begin{algorithmic}[1]
\Function{CheckCommitLive}{$commit_a$}
    \State $\tuple{seq_{a_{trans}},KV_a} \gets commit_a$
    \State $KSet \gets \{k|\tuple{k,v} \in KV\}$
    \State $AllCommits \gets$ \Call{GetCommits}{} \Comment{Get all the commits} \\
    
    \LeftComment{Iterate all commits that are newer in time}
    \ForAll{$\tuple{seq_{trans}',KV'}\in AllCommits, seq_{trans}' > seq_{a_{trans}}$}
        \State $KVSet \gets KVSet \setminus \{k|\tuple{k,v} \in KV'\}$\\
        
        \If{$KVSet = \emptyset$}
            \State \Return{false} \Comment{All keys have a newer commit}
        \EndIf
    \EndFor
    \State \Return{true} \Comment{If got here then some keys still live}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check Last Message Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Last Message Live:}\\
The last message is dead if the device in question pushed a slot that has a larger sequence number than the one recorded in the last message data entry. \\
\begin{algorithmic}[1]
\Function{CheckLastMsgLive}{$lastmsg_a$}
    \State $\tuple{seq_a, id_a} \gets lastmsg_a$\\
    
    \If{$\exists \tuple{id', seq'} \in LastSlot, id'=id_a \land seq' > seq_a$}
        \State \Return{false}
    \EndIf
    \State \Return{True}    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

%Check Collision Resolution Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Collision Resolution Live:}\\
Check if a collision resolution data entry is live or not.  This done by checking if all clients that we know about have seen the collision resolution entry.  This is checked by seeing if all devices have inserted a message with a larger sequence number into the block chain.\\
\begin{algorithmic}[1]
\Function{CheckColResLive}{$colres_a$}
    \State $\tuple{id_a, seq_{a_{old}}, seq_{a_{new}}, equal_a} \gets colres_a$\\
    
    \If{$\forall \tuple{id', seq'} \in LastSlot, seq' \geq seq_{a_{new}}$}
        \State \Return{false}
    \EndIf
    \State \Return{true}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check New Key Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check New Key Live:}\\
A new key data entry is always live.\\
\begin{algorithmic}[1]
\Function{CheckNewkeyLive}{$newkey_a$}
    \State \Return{True}    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check Abort Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Abort Live:}\\
Check if an abort data entry is live or not.  Abort is dead if the device whos transaction was aborted sees the abort.  This is checked by seeing if that device inserted a slot into the block chain which has a sequence number that is larger than the aborts sequence number.\\
\begin{algorithmic}[1]
\Function{CheckAbortLive}{$abort_a, seq_a$}
    \State $\tuple{seq_{a_{trans}},id_a} \gets abort_a$\\
    
    \LeftComment{The device whos transaction was aborted saw the abort}
    \If{$\exists \tuple{id', seq'} \in LastSlot, id'=id_a \land seq' > seq_a$}
        \State \Return{false}
    \EndIf
    \State \Return{True}    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check Transaction Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Transaction Live:}\\
A transaction is dead if there is an abort for that transaction or if there is a commit for that a transaction that came after this transaction.  Since transactions must be commited in order of there insertion, seeing a transaction that is commited and has a larger sequence number than the transaction in question means that the transaction in question was commited at some point.\\
\begin{algorithmic}[1]
\Function{CheckTransLive}{$trans_a$}
    \State $\tuple{seq_a, id_a, KV_a, Guard_a} \gets trans_a$
    \State $AllCommits \gets$ \Call{GetCommits}{} \Comment{Get all the commits}
    \State $AllAborts \gets$ \Call{GetAborts}{} \Comment{Get all the aborts} \\
    
    \If{$\exists \tuple{seq_{abrt}',seq_{trans}',id'} \in AllAborts, seq_{trans}' = seq_a$}
        \State \Return{false}
    \ElsIf{$\exists \tuple{seq_{trans}',KV'} \in AllCommits, seq_{trans}' \geq seq_a$}
        \State \Return{false}
    \EndIf
    \State \Return{true}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Live:}\\
Checks if a data entry is live based on its type.\\
\begin{algorithmic}[1]
\Function{CheckLive}{$datentry, seq$}
    \If{$datentry$ is a $commit$}
        \State \Return{\Call{CheckCommitLive}{$datentry$}}\
    \ElsIf{$datentry$ is a $abort$}
        \State \Return{\Call{CheckAbortLive}{$datentry, seq$}}\
    \ElsIf{$datentry$ is a $trans$}
        \State \Return{\Call{CheckTransLive}{$datentry$}}\
    \ElsIf{$datentry$ is a $lastmsg$}
        \State \Return{\Call{CheckLastMsgLive}{$datentry$}}\
    \ElsIf{$datentry$ is a $colres$}
        \State \Return{\Call{CheckColResLive}{$datentry$}}\
    \ElsIf{$datentry$ is a $qstate$}
        \State \Return{\Call{CheckQStateLive}{$datentry$}}
    \ElsIf{$datentry$ is a $newkey$}
        \State \Return{\Call{CheckNewkeyLive}{$datentry$}}
    \Else
        \State \Call{Error}{"Unknown data entry type."}
    \EndIf
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Slot Has Live
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Slot Has Live:}\\
Check if the slot has any live data entries in it. Do this by looking at all the data entries in the slot and checking if they are live\\
\begin{algorithmic}[1]
\Function{SlotHasLive}{$slot_a$}
    \State $\tuple{s_1, \tuple{seq_2,id,DE,hmac_p,hmac_c}} \in LocalSlots$
    
    \ForAll{$datentry \in DE$}
        \If{\Call{CheckLive}{$datentry, s_1$}} \Comment{an entry is alive}
            \State \Return{true}
        \EndIf
    \EndFor
    
    \State \Return{false} \Comment{All entries were dead}    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Calculate Resize Threshold
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Calculate Resize Threshold:}\\
Calculate a threshold for how many slots need to have live data entries in them for a resize to take place.\\
\begin{algorithmic}[1]
\Function{CalcResizeThresh}{$maxsize$}
    \State \Return{$\left \lfloor {maxsize * RESIZE\_THRESH\_PERCENT} \right \rfloor$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Calculate Block Chain New Size
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Calculate Block Chain New Size:}\\
Calculate the new size of the block chain which we need if we are to resize the data structure.\\
\begin{algorithmic}[1]
\Function{CalcNewSize}{$maxsize$}
    \State \Return{$\left \lceil {maxsize * RESIZE\_THRESH\_PERCENT} \right \rceil$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Should Resize
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Should Resize:}\\
Check if the block should resize based on some metric of how many slots in the block chain are filled with live data. \\
\begin{algorithmic}[1]
\Function{ShouldResize}{$ $}
    \State $LiveSlots \gets \{slot_s|slot_s \in LocalSlots \land $\Call{SlotHasLive}{$slot_s$}$\}$
    \State $resizethreshold \gets $ \Call{CalcResizeThresh}{$max\_size$}
    \State \Return{$|LiveSlots| \geq resizethreshold$} \Comment{If passes threshold then resize}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Create Queue State 
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create Queue State:}\\
Generate a queue state data entry.\\
\begin{algorithmic}[1]
\Function{CreateQState}{$size_a$}
    \State \Return{$\tuple{size_a}$}    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Create Abort
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create Abort:}\\
Generate a abort data entry.\\
\begin{algorithmic}[1]
\Function{CreateAbort}{$seq_a, id_a$}
    \State \Return{$\tuple{seq_a, id_a}$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Create Transaction
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create Transaction:}\\
Generate a transaction data entry.\\
\begin{algorithmic}[1]
\Function{CreateTrans}{$pendingtrans_a, seq_a$}
    \State $\tuple{KV_a, Guard_a} \gets pendingtrans_a$
    \State \Return{$\tuple{seq_a, LOCAL\_ID, KV_a, Guard_a}$}    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Create Commit
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create Commit:}\\
Generate a commit data entry.\\
\begin{algorithmic}[1]
\Function{CreateCommit}{$seq_a,KV_a$}
    \State \Return{$\tuple{seq_a,KV_a}$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}


% Data Entry Set Has Space 
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Data Entry Set Has Space :}\\
Checks if a data entry set has enough space for a new data entry to be inserted.\\
\begin{algorithmic}[1]
\Function{DEHasSpace}{$DE_a, de_a$}
    \State $newsize \gets $ \Call{GetSize}{$DE_a$}
    \State $newsize \gets newsize +$ \Call{GetSize}{$de_a$}
    \State \Return{$newsize \leq DATA\_ENTRY\_SET\_MAX\_SIZE$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Create Rescued Commit
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create Rescued Date Entry:}\\
For commits only the key-value pairs that are most recent (no newer commit that has those key values in it).\\
\begin{algorithmic}[1]
\Function{CreateRescuedCommit}{$commit_a$}
    \State $AllCommits \gets $ \Call{GetCommits}{}
    \State $\tuple{seq_{a_{trans}},KV_a} \gets de_a$
    \State $NewKV \gets KV_a$\\

    \LeftComment{Get rid of all key values that have newer commits}
    \ForAll{$\tuple{k_a, v_a} \in KV_a$}
        \LeftComment{Iterate over all commits that are newer than the rescue commit}
        \ForAll{$\tuple{seq', KV'} \in AllCommits, seq' > seq_{a_{trans}}$}
            \If{$\exists \tuple{k', v'} \in KV', k' = k_a$}
                \State $NewKV \gets NewKV \setminus \tuple{k_a, v_a}$
                \State Break
            \EndIf
        \EndFor
    \EndFor
    \State \Return{$\tuple{seq_{a_{trans}}, NewKV}$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Create Rescued Date Entry
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create Rescued Date Entry:}\\
Generate the data entry rescued version of the entry.  For some data entry types such as commits, the entry is not rescued as is.  For commits only the key-value pairs that are most recent (no newer commit that has those key values in it).\\
\begin{algorithmic}[1]
\Function{CreateRescuedEntry}{$de_a$}

    \If{$de_a$is a $commit$}
        \State \Return{\Call{CreateRescuedCommit}{$de_a$}}
    \EndIf
    
    \State \Return{$de_a$} \Comment{No Modification needed}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Check and Create Last Message Data Entry
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check and Create Last Message Data Entry:}\\
Check if a last message entry needs to be created for this slot and if so create it.  The check is done by checking if there are any newer slots with the same id or if there is already a last message slot with a newer sequence number\\
\begin{algorithmic}[1]
\Function{CheckCreateLastMsgEntry}{$seq_a, id_a$}
    \State $AllLastMsg \gets$ \Call{GetLastMsg}{}\\
    
    \LeftComment{Already Has one}
    \If{$\exists  \tuple{seq', id'} \in AllLastMsg, id_a=id' \land seq'=seq_a$}
        \State \Return{$\{\}$}\\
    \EndIf\\
    
    \LeftComment{Not latest slot from that client}
    \If{$\exists  \tuple{seq_1', \tuple{seq_2',id',DE',hmac_p',hmac_c'}} \in LocalSlots, id_a=id' \land seq_1'>seq_a$}
        \State \Return{$\{\}$}\\
    \EndIf\\
    
    
    \State \Return{$\{\tuple{seq_a, id_a}\}$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Mandatory Rescue
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Mandatory Rescue:}\\
This rescue is mandatory before any types of data entries (excpet queue states) can be placed into the data entry section of the new slot.  Returns the data entry Set or null if the first slot could not be cleared (the live data in that slot could not fit in this current slot). \\
\begin{algorithmic}[1]
\Function{MandatoryRescue}{$DE_a$}
    \State $smallestseq \gets seq$ such that $\tuple{seq, DE}\in LocalSlots \land (\forall \tuple{seq', DE'} \in LocalSlots, seq \leq seq')$
    \State $cseq \gets smallestseq$\\
    
    \LeftComment{Check the least slots to rescue and live entries}
    \While{$cseq < (smallestseq + DEAD\_SLOT\_COUNT)$}
        \State $currentslot \gets s'$ such that $\tuple{s',DE'} \in LocalSlots \land s' = cseq$
        \State $\tuple{seq', \tuple{seq_2',id',DE',hmac_p',hmac_c'}} \gets currentslot$
        \State $DE' \gets DE' \cup$ \Call{CheckCreateLastMsgEntry}{$seq', id'$} \Comment{Get the last message too if we need it}\\
        
        \ForAll{$de \in DE'$} \Comment{Iterate over all the entries}
            \If{\Call{CheckLive}{$de, cseq$}} \Comment{data entry is live}
                \State $de \gets $ \Call{CreateRescuedEntry}{de} \Comment{Resize entry if needed}
                \If{\Call{DEHasSpace}{$DE_a, de$}}
                    \State $DE_a \gets DE_a \cup de$ \Comment{Had enough space to add it}
                \ElsIf{$currentseq = smallestseq$}
                    \State \Return{$NULL$}
                \Else
                    \State \Return{$DE_a$}
                \EndIf
            \EndIf
        \EndFor\\
        
        \State $cseq \gets cseq+1$ \Comment{Move onto the next slot}
    \EndWhile
    
    \State \Return{$DE_a$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Optional Rescue
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Optional Rescue:}\\
This rescue is not mandatory.  This is trying to fill the remaining portion of the slot with rescued data so that no space is wasted. If we encounter a data entry that does not fit move on to the next, maybe that one will fit.  Do this until we skipped too many live data entries\\
\begin{algorithmic}[1]
\Function{OptionalRescue}{$DE_a$}
    \State $smallestseq \gets seq$ such that $\tuple{seq, DE}\in LocalSlots \land (\forall \tuple{seq', DE'} \in LocalSlots, seq \leq seq')$
    \State $largestseq \gets seq$ such that $\tuple{seq, DE}\in LocalSlots \land (\forall \tuple{seq', DE'} \in LocalSlots, seq \geq seq')$

    \State $numofskips \gets 0$
    \State $cseq \gets smallestseq$\\
    
    \LeftComment{Check the least slots to rescue and live entries}
    \While{$cseq < largestseq$}
        \State $currentslot \gets s'$ such that $\tuple{s',DE'} \in LocalSlots \land s' = cseq$
        \State $\tuple{seq', \tuple{seq_2',id',DE',hmac_p',hmac_c'}} \gets currentslot$\\
        
        \ForAll{$de \in DE'$} \Comment{Iterate over all the entries}
            \If{\Call{CheckLive}{$de, cseq$}} \Comment{data entry is live}
                \State $de \gets $ \Call{CreateRescuedEntry}{de} \Comment{Resize entry if needed}\\
                
                \If{$de \in DE_a$} \Comment{Already being rescued}
                    \State Continue
                \EndIf\\
                
                \If{\Call{DEHasSpace}{$DE_a, de$}}
                    \State $DE_a \gets DE_a \cup de$ \Comment{Had enough space to add it}
                \ElsIf{$numofskips \geq MAX\_RESCUE\_SKIPS$}
                    \State \Return{$DE_a$}
                \Else
                    $numofskips \gets numofskips +1$
                \EndIf
            \EndIf
        \EndFor\\
        
        \State $cseq \gets cseq+1$ \Comment{Move onto the next slot}
    \EndWhile
    
    \State \Return{$DE_a$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Arbitrate
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Arbitrate:}\\
\begin{algorithmic}[1]
\Function{Arbitrate}{$DE_a$}
    \State $AllCommits \gets$ \Call{GetCommits}{}
    \State $AllTrans \gets$ \Call{GetTrans}{}
    \State $LiveCommits \gets \{c| c\in AllCommits, $\Call{CheckCommitLive}{$c$}$\}$
    \State $LiveTrans \gets \{t| t\in AllTrans, $\Call{CheckTransLive}{$t$}$\}$
    \State $KV \gets \emptyset$
    \State $lastcomseq \gets -1$
    \State $CurrKV \gets \emptyset$
    \State $DKV \gets \emptyset$
    \State $KVTmp \gets \emptyset$\\
    
    \LeftComment{Get all the latest commits}
    \ForAll{$\tuple{seq_{trans}',KV'} \in LiveCommits$}
        \State $CurrKV \gets CUrrKV \cup KV'$
    \EndFor\\
    
    \ForAll{$\tuple{seq_t, id_t, KV_t, Guard_t} \in LiveTrans$ ordered by $seq'$}    
        \If{\Call{EvaluateGuard}{$Guard_t, CurrKV$}}
            \State $abortde \gets $\Call{CreateAbort}{$seq_t, id_t$}
            \LeftComment{No more space so we cant arbitrate any further}
            \If($lnot$\Call{DeHasSpace}{$DE_a, abortde$})
                \State \Return{$DE_a$}
            \EndIf
            \State $DE_a \gets DE_a \cup abortde$
        \Else
            \State $DKV \gets \{\tuple{k,v}| \tuple{k,v} \in KV \land \tuple{k',v'}\in KV_t \land k'=v'\}$
            \State $KVTmp \gets (KV \setminus DKV) \cup KV'$
            \State $DKV \gets \{\tuple{k,v}| \tuple{k,v} \in CurrKV \land \tuple{k',v'}\in KVTmp \land k'=v'\}$
            \State $CurrKV \gets (CurrKV \setminus DKV) \cup KVTmp$
            \State $commitde \gets $ \Call{CreateCommit}{$seq_t,KVTmp$}
            
            \If{$\lnot$ \Call{DeHasSpace}{$DE_a, commitde$}}
                \If{$lastcomseq \neq -1$}
                    \State $DE_a \gets DE_a \cup$ \Call{CreateCommit}{$lastcomseq,KV$}
                \EndIf
                \State \Return{$DE_a$}
            \Else
                \State $KV \gets KVTmp$
                \State $lastcomseq \gets seq_t$
            \EndIf
        \EndIf
    \EndFor
    
    \State $DE_a \gets DE_a \cup$ \Call{CreateCommit}{$lastcomseq,KV$}
    \State \Return{$DE_a$}

    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Create New Slot
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create New Slot:}\\
Create a slot and encrypt it.\\
\begin{algorithmic}[1]
\Function{CreateNewSlot}{$seq_a, DE_a$}
    \State $\tuple{seq, SDE} \gets \tuple{seq', SDE'}$ such that $\tuple{seq', SDE'}\in LocalSlots \land (\forall \tuple{seq'', DE''} \in LocalSlots, seq' \geq seq'')$
    \State $\tuple{seq,id,DE,hmac_p,hmac_c} \gets SDE$\\
    
    \State $newhmac \gets $ \Call{GenerateHmac}{$seq_a, LOCAL\_ID, DE_a, hmac_p$}
    \State $newSDE \gets \tuple{seq,LOCAL\_ID,DE_a,hmac_c,newhmac}$
    \State $encryptnewSDE \gets $\Call{Encrypt}{newSDE}\\
    
    \State \Return{$\tuple{seq_a, encryptnewSDE}$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Send Data to Server
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Send Data to Server:}\\
Send the data to the server.  If this fails then new slots will be returned by the server.\\
\begin{algorithmic}[1]
\Function{SendToServer}{$seq_a, DE_a, newsize_a$}
    \LeftComment{Make the slot and try to send to server}
    \State $newslot \gets $ \Call{CreateNewSlot}{$seq_a, DE_a$}
    \State $\tuple{success, newslots} \gets$ \Call{PutSlot}{$seq_a, newslot, newsize_a$}\\
    
    \If{$success$}
        \State $RejectedSlotList \gets \emptyset$
        \State \Return{$\tuple{true, \{newslot\}}$}
    \Else
        \If{$|newslots| = 0$}
            \State \Call{Error}{"Server rejected but did not send any slots"}
        \EndIf
        \State $RejectedSlotList \gets RejectedSlotList \cup \{seq_a\}$
        \State \Return{$\tuple{false, newslots}$}
    \EndIf\\
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}


% Try Insert Transaction
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Try Insert Transaction:}\\
Try to insert a transaction into the block chain. Does resizing, rescues and insertion of other data entry types as needed. \\
\begin{algorithmic}[1]
\Function{TryInsertTransaction}{$pendingtrans_a, forceresize$}
    \State $DE \gets \emptyset$ \Comment{The data entries for this slot}
    \State $seq \gets $ \Call{GetNextSeq}{} \Comment{Get the sequence number for this slot}
    \State $newsize \gets 0$
    \State $trans \gets$ \Call{CreateTrans}{$pendingtrans_a, seq$}
    \State $transinserted \gets false$
    \State $slotstoinsert \gets \emptyset$\\
    
    \State $resize \gets $ \Call{ShouldResize}{ } \Comment{Check if we should resize}
    \State $resize \gets resize \lor forceresize$
    \If{$resize$}
        \State $newsize \gets$ \Call{CalcNewSize}{$max\_size$}
        \State $DE \gets DE \cup \{$\Call{CreateQState}{$newsize$}$\}$
    \EndIf\\
    
    %\If{$RejectedSlotList \neq \emptyset$}   
    %\EndIf
    
    \State $DE \gets$ \Call{MandatoryRescue}{$DE$} \Comment{Round 1 of rescue}
    \If{$DE = NULL$}
        \LeftComment{Data was going to fall off the end so try again with a forced resize}
        \State \Return{\Call{TryInsertTransaction}{$trans_a, true$}}
    \EndIf\\
    
    \State $DE \gets $\Call{Arbitrate}{$DE$}\\
    
    \If{\Call{DEHasSpace}{$DE, trans$}} \Comment{transaction fits}
        \State $DE \gets DE \cup trans$
        \State $transinserted \gets true$
    \EndIf\\
    
    \LeftComment{Rescue data to fill slot data entry section}
    \State $DE \gets$ \Call{OptionalRescue}{$DE$}\\
    
    \LeftComment{Send to server.}
    \State $\tuple{sendsuccess, newslots} \gets $ \Call{SendToServer}{$seq, DE, newsize$}
    
    \State \Return{$transinserted \land success$} \Comment{Return if  succeeded or not}
    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}



\subsection{Client Interfaces}

% Put KV pair
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Put Key Value Pair:}\\
Puts a key value pair into the key value pair buffer\\
\begin{algorithmic}[1]
\Function{PutKeyValue}{$k,v$}
    \State $\tuple{seq, KV, Guard} \gets PendingTrans$\\
    
    \LeftComment{Check if KV already has a key value pair for the specified key}
    \State $DSet \gets \{\tuple{k_1,v_1} | \tuple{k_1,v_1} \in KV \land k_1 = k\}$\\
    
    \If{$DSet \neq \emptyset$}
        \State \Call{Error}{"Value for key already in most recent update"}
    \EndIf\\
        
    \State $KV \gets KV \cup \{\tuple{k,v}\}$ \Comment{Add key value pair}
    \State $PendingTrans \gets \tuple{seq, KV, Guard}$
    \State \Call{CheckArbitrator}{$PendingTrans$} \Comment{Check that the transaction still valid}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}


% Put guard condition
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Put Guard:}\\
Puts a guard transaction into the key value update.  A guard is a key value with a logical operator ($lop$).\\
\begin{algorithmic}[1]
\Function{PutGuard}{$k,v, lop$}
    \State $\tuple{seq, KV, Guard} \gets PendingTrans$\\
    
    \If{$\tuple{k,v, lop} \in Guard$}
        \State \Return{} \Comment{Already have guard condition in update}
    \EndIf\\
    
    \State $Guard \gets Guard \cup \{\tuple{k,v,lop}\}$
    \State $PendingTrans \gets \tuple{seq, KV, Guard}$
    \State \Call{CheckArbitrator}{$PendingTrans$} \Comment{Check that the transaction still valid}
\EndFunction    
\end{algorithmic}
\end{varwidth}% 
}


% Transaction Start
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{ Transaction Start:}\\
Starts a transaction.  Clears out the key value pair update buffer.\\
\begin{algorithmic}[1]
\Function{TransactionStart}{$ $}
    \LeftComment{Reset the key value update buffer}
    \State $KVUpdate \gets \tuple{\emptyset, \emptyset}$
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Transaction Commit
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{ Transaction Commit:}\\
Commits the transaction into the block chain.  Keeps attempting to insert the transaction into the block chain until it succeeds.
\begin{algorithmic}[1]
\Function{Transaction Commit}{$ $}
    \State $success \gets False$
    \While{$\lnot success$}
        \State $success \gets$ \Call{TryInsertTransaction}{$PendingTrans, false$}
    \EndWhile
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

\end{document}
