\documentclass[11pt]{article}
\newcommand{\tuple}[1]{\ensuremath \langle #1 \rangle}
\usepackage{color}
\usepackage{amsthm}
\usepackage{amsmath}
\usepackage{graphicx}
\usepackage{mathrsfs}
\usepackage{amssymb}
\usepackage{algorithm}
\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}
\algnewcommand{\algorithmicgoto}{\textbf{go to}}%
\algnewcommand{\Goto}[1]{\algorithmicgoto~\ref{#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{Approach}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{The Arbitrator}
Each key has an arbitrator that makes the final decision when it comes to whether a specific transaction containing that key updates the state of the system or is aborted.  This ensures that clients can make offline updates and then push those updates to the server at a later time.  The arbitrator then tries to merge those updates and if possible will commit them into the current working state of the system.  If not possible then the arbitrator will abort that transaction.  The arbitrator arbitrates on transactions in order of transaction sequence number.


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Server Algorithm}
$s \in SN$ is a sequence number\\
$sv \in SV$ is a slot's value\\
$slot_s = \tuple{s, sv} \in SL \subseteq SN \times SV$ \\ \\
\textbf{State} \\
\textit{SL = set of live slots on server} \\
\textit{max = maximum number of slots (input only for resize message)} \\
\textit{n = number of slots} \\ \\
\textbf{Helper Function} \\
$MaxSlot(SL_s)= \tuple{s, sv} \mid \tuple{s, sv}
\in SL_s \wedge \forall \tuple{s_s, sv_s} \in SL_s, s \geq s_s$ \\
$MinSlot(SL_s)= \tuple{s, sv} \mid \tuple{s, sv} 
\in SL_s \wedge \forall \tuple{s_s, sv_s} \in SL_s, s \leq s_s$ \\
$SeqN(slot_s = \tuple{s, sv})=s$ \\
$SlotVal(slot_s = \tuple{s, sv})=sv$ \\

%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get Slot:}\\
Returns to the client the slots that have a sequence number that is greater than or equal to the sequence number that is in the request.
\begin{algorithmic}[1]
\Function{GetSlot}{$s_g$} throws $Server\_Connection\_Timeout$, $Server\_Response\_Timeout$
\State \Return{$\{\tuple{s, sv} \in SL \mid s \geq s_g\}$}
\EndFunction
\end{algorithmic}%\end{varwidth}% 
%}


%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get Slot:}\\
Puts a slot in the server memory if the slot has the correct sequence number.  Also resizes the server memory if needed.
\begin{algorithmic}[1]
\Function{PutSlot}{$s_p,sv_p,max'$} throws $Server\_Connection\_Timeout$, $Server\_Response\_Timeout$
\If{$(max' \neq \emptyset)$}  \Comment{Resize}
\State $max \gets max'$
\EndIf
\State $\tuple{s_n,sv_n} \gets MaxSlot(SL)$\Comment{Last sv}
%\State $s_n \gets SeqN(\tuple{s_n,sv_n})$
\If{$(s_p = s_n + 1)$}
    \If{$n = max$}
        \State $\tuple{s_m,sv_m} \gets MinSlot(SL)$\Comment{First sv}
        \State $SL \gets SL - \{\tuple{s_m,sv_m}\}$
    \Else \Comment{$n < max$}
        \State $n \gets n + 1$
    \EndIf
    \State $SL \gets SL \cup \{\tuple{s_p,sv_p}\}$
    \State \Return{$(true,\emptyset)$}
\Else
    \State \Return{$(false,\{\tuple{s,sv}\in SL \mid 
    s \geq s_p\})$}
\EndIf
\EndFunction
\end{algorithmic}%\end{varwidth}% 
%}


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Client Algorithm}

\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$ \\
$G$ is a set of $kv$ that is the guard \\
$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 \\

$colres$ is a collision resolution entry, $\tuple{id, seq_{old}, seq_{new}, true \lor false}$ \\
$lastmsg$ is a last message entry, $\tuple{seq, id}$ \\
$qstate$ is a queue state entry, $\tuple{size}$ \\
$newkey$ is a new key entry, $\tuple{k, id}$, $id$ is ID of arbitrator \\
$abort$ is an abort transaction entry, $\tuple{seq_{clientlocal}, seq_{server}, id, arb, seq_{arb}}$ \\
$transpart$ is a transaction part entry, $\tuple{Dat,arb,seq_{clientLocal}, seq_{server}, id, partnum, isLast}$\\
$compart$ is a commit part entry, $\tuple{Dat,seq_{trans}, seq_{server}, id, partnum, isLast}$\\

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


$pendingTransaction$ is a pending transaction, $\tuple{KV, G, id, seq_{clientLocal}}$ \\
$Transaction$ is a Transaction container that houses transaction parts together, $\tuple{Parts, KV, G,seq_{local}, seq_{server},id, arb}$\\
$Commit$ is a commit container that houses commit parts together, $\tuple{Parts, KV, seq_{trans}, seq_{server},id}$
$ArbitrationRound$ is a commit and a group of aborts where all the aborts must be sent before the commit, $\tuple{commit, AbortSet, SentSet}$

$status$ is the status of a transaction and can be: $aborted, pending, committed, sentpartial, sentfully, noeffect$
$TransStatus$ is the status of a transaction, $\tuple{status}$\\

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


\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.\\
$MAX\_ROUND\_SIZE$ = max number of parts that an arbitration round can have before being full. \\

\subsubsection{Primitive Variables}
$max\_size$ = max size of the block chain.\\
$clntTransactionNum \gets 0$ = current client transaction number that this client created.\\
$newPendingTransaction$ = transaction being built.\\
$arbitrationSeqNum \gets 0$ = sequence number used by the arbitrator to label the commits and aborts it creates\\
$hadPartialSendToServer gets false$ = if the last attempt to send the server had a recieve timeout.\\


\subsubsection{Sets and Lists}

$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 sequence number of the last slot.\\
$Arbitrator$ = set of $\tuple{k,id}$ containing the key and its arbitrating device.\\ne 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.\\
$CommittedKV$ = set of committed key value pairs (initially $\emptyset$).\\
$SpeculatedKV$ = set of speculated key value pairs (initially $\emptyset$).\\
$PendingTransactionQueue$ = queue of transactions that need to be sent.\\
$LastTransactionArbitrated$ = set of $\tuple{id, seq}$ with the last sequence number an arbitrator arbitrated on.\\
$LiveTransactions$ = set of transactions with their parts.\\
$LiveCommits$ = set of live commits and their parts.\\
$OfflineTransAtServer$ = set of transactions that were sent to the server but were arbitrated through local communication.\\ 
$SendArbQueue$ = queue of arbitration rounds that have yet to be sent to the server.\\
$LastTransSeenMid$ = Last transaction seen from a specific machine from the server.\\
$LastArbLocalArbitrated$ = Last local sequence number seen from a client.\\
$LastCommitSeenFromArbitrator$ = last commit seen from a specific arbitrator.\\

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

$MaxSlot(SL_s)= \tuple{s, sv} \mid \tuple{s, sv} \in SL_s \wedge \forall \tuple{s_s, sv_s} \in SL_s, s \geq s_s$ \\
$MinSlot(SL_s)= \tuple{s, sv} \mid \tuple{s, sv} \in SL_s \wedge \forall \tuple{s_s, sv_s} \in SL_s, s \leq s_s$ \\
$DecodeParts(transpart)= $ Converts the part data into KV sets and Guard Condition sets.\\
$DecodeParts(compart)= $ Converts the part data into a KV set.\\
$GenerateParts(Commit)= $ Fills the commit with parts generated by its content.\\
$GenerateParts(Transaction)= $ Fills the transaction with parts generated by its content.\\
$SetTransStatus(TransStatus, Transaction_Identifier) = $ saves a transaction status.\\ 
$ChangeTransStatus(TransStatus, newStatus) = $ changes a transaction status.\\ 
$GetTransStatus(Transaction_Identifier) = $ gets a transaction status.\\ 
$DeleteTransStatus(Transaction_Identifier) = $ delete a transaction status.\\ 

% 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}% 
%}

% 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 $lower \gets \left \lfloor {maxsize * RESIZE\_THRESH\_PERCENT} \right \rfloor - 1$
    \State \Return{$lower + $\Call{Random}{$maxsize - lower$}}
\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\_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 \Return{$|LiveSlots| \geq $\Call{CalcResizeThresh}{$max\_size$}} 
\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$} $ + $ \Call{GetSize}{$de_a$}
    \State \Return{$newsize \leq DATA\_ENTRY\_SET\_MAX\_SIZE$}
\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}% 
%}

% Get Arbitrator KV
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get Arbitrator for KV Set:}\\
Get the arbitrator for a given key value set.
\begin{algorithmic}[1]
\Function{GetArbitratorKV}{$KV_a$} 
    \State \Return{$id'$ such that $\exists \tuple{k',v'} \in KV_a, id' =$ \Call{GetArbitrator}{$k'$}}
\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{id, seq}\in LastSlot \land (\forall \tuple{id', seq'} \in LastSlo, 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}% 
%}

% Create Collision
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create ColRes:}\\
Generate a colres data entry.
\begin{algorithmic}[1]
\Function{CreateColRes}{$is_a, seq_{a_{old}}, seq_{a_{new}}, isequal_a$}
    \State \Return{$\tuple{id_a, seq_{a_{old}}, seq_{a_{new}},}isequal_a$}
\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{$\emptyset$}
    \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{$\emptyset$}\\
    \EndIf\\
    
    \State \Return{$\{\tuple{seq_a, id_a}\}$}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

%Evaluate Guard
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Evaluate Guard:}\\
Evaluate Guard Condition checks if all the KV pairs in the guard condition match the declared KV pairs.
\begin{algorithmic}[1]
\Function{EvaluateGuard}{$G_a, KV_a$}

    \If{$\exists \tuple{k_G, v_G} \in G_a, \tuple{k_{KV},v_{KV}} \in KV_a, k_G=K_{KV} \land v_G \neq v_{KV}$}
        \State \Return{False}
    \EndIf
    
    \State \Return{True}
\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',id',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \ForAll{$a' \in DE', a'$ is a $abort$}
            \State $\tuple{seq_l', seq_s', id', arb', seq_{arb}'} \gets a'$
            \State $AbrtSet \gets AbrtSet \cup \{seq_l', seq_s', id', arb', seq_{arb}', seq'\}$
        \EndFor
    \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',id',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \ForAll{$q' \in DE', q'$ is a $qstate$}
            \State $\tuple{size'} \gets q'$
            \State $QSet \gets QSet \cup \{\tuple{size', seq'}\}$
        \EndFor
    \EndFor
    \State \Return{$QSet$}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Get all New Keys
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all new keys:}\\
Get all new keys that are currently in the local block chain.  Iterate over all the local slots and extract all the new keys from each slot.
\begin{algorithmic}[1]
\Function{GetNewKeys}{$ $}
    \State $NKSet \gets \emptyset$ \Comment{Set of the new keys}\\
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq',id_1',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \ForAll{$nk' \in DE', nk'$ is a $newkey$}
            \State $\tuple{k', id_2'} \gets nk'$
            \State $NKSet \gets NKSet \cup \{\tuple{k', id_2', seq'}\}$
        \EndFor
    \EndFor
    \State \Return{$NKSet$}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Get all Collision Resolutions
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all collision resolutions:}\\
Get all the collision resolution entries fron the slots. 
\begin{algorithmic}[1]
\Function{GetColRes}{$ $}
    \State $CRSet \gets \emptyset$ \Comment{Set of the new keys}\\
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq',id_1',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \ForAll{$cr' \in DE', nk'$ is a $colres$}
            \State $\tuple{id', seq_{old}', seq_{new}', local'} \gets cr'$
            \State $CRSet \gets CRSet \cup \{\tuple{id', seq_{old}', seq_{new}', local', seq'}\}$
        \EndFor
    \EndFor
    \State \Return{$CRSet$}
\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 entries:}\\
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_1',id_1',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \ForAll{$lm' \in DE', lm'$ is a $lastmsg$}
            \State $\tuple{seq_2', id_2'} \gets lm'$
            \State $LMSet \gets LMSet \cup \{\tuple{seq_2', id_2', seq_1'}\}$
        \EndFor
    \EndFor
    \State \Return{$LMSet$}
\EndFunction
\end{algorithmic}
%\end{varwidth}%
%}

% Get all Transaction Parts
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all the transaction part entries:}\\
Get all the transaction parts from the slots.
\begin{algorithmic}[1]
\Function{GetTransParts}{$ $}
    \State $TPSet \gets \emptyset$ 
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq_1',id_1',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \ForAll{$tp' \in DE', tp'$ is a $transpart$}
            \State $\tuple{Dat',arb',seq_{clientLocal}', seq_{server}', id', partnum', isLast'} \gets tp'$
            \State $TPSet \gets TPSet \cup \{\tuple{Dat',arb',seq_{clientLocal}', seq_{server}', id', partnum', isLast', seq_1'}\}$
        \EndFor
    \EndFor
    \State \Return{$TPSet$}
\EndFunction
\end{algorithmic}
%\end{varwidth}%
%}

% Get all Commit Parts
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get all the commit part entries:}\\
Get all the commit parts from the slots.
\begin{algorithmic}[1]
\Function{GetComParts}{$ $}
    \State $CPSet \gets \emptyset$ 
        
    \LeftComment{Iterate over all the slots saved locally}
    \ForAll{$\tuple{s_1', \tuple{seq_1',id_1',DE',hmac_p',hmac_c'}} \in LocalSlots$}
        \ForAll{$cp' \in DE', cp'$ is a $compart$}
            \State $\tuple{Dat',seq_{trans}', seq_{server}', id', partnum', isLast'} \gets cp'$
            \State $CPSet \gets CPSet \cup \{\tuple{Dat',seq_{trans}', seq_{server}', id', partnum', isLast', seq_1'}\}$
        \EndFor
    \EndFor
    \State \Return{$CPSet$}
\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, seq_a$}
    \State $\tuple{size_a} \gets qstate_a$
    \State $AllQStates \gets$ \Call{GetQState}{} \Comment{Get all the qstates} \\
    
    \If{$\exists \tuple{size', seq'} \in AllQStates, size' > size_a$}
        \State \Return{false}
    \ElsIf{$\exists \tuple{size', seq'} \in AllQStates, size' = size_a \land seq' > seq_a$}
        \State \Return{false}
    \EndIf
    \State \Return{true}
    
\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$\\
    \State $AllLastMsg \gets$ \Call{GetLastMsg}{} \Comment{Get all the last messages} \\
    
    \If{$\exists \tuple{seq_1', id', seq_2'} \in AllLastMsg, id'=id_a \land seq_1' > seq_a$}
        \State \Return{false}
    \ElsIf{$\exists \tuple{seq_1', id', seq_2'} \in AllLastMsg, id'=id_a \land seq_1' = seq_a \land seq_2' > seq_a$}
        \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 unless there is a resuced version of the new key that is newer.
\begin{algorithmic}[1]
\Function{CheckNewkeyLive}{$newkey_a, seq$}
    \State $\tuple{k_a, id_a} \gets newkey_a$
    \State $AllNewKeys \gets$ \Call{GetNewKeys}{} \Comment{Get all the new keys} \\
    
    \If{$\exists \tuple{k', id', seq'} \in AllNewKeys, k'=k_a \land id'=id_a \land seq' > seq$}
        \State \Return{False}
    \ElsIf{$\exists \tuple{k', id', seq'} \in AllNewKeys, k'=k_a \land id'\neq id_a \land seq' > seq$}
        \State \Return{False} \Comment{Delete an attempt to insert a new key that already exists}
    \EndIf
    
    \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}
    \Else
        \State $AllAborts \gets$ \Call{GetAborts}{} \Comment{Get all the aborts} \\
        \If{$\exists \tuple{seq_{trans}',id_{trans}', seq'} \in AllAborts,  seq_{a_{trans}} = seq_{trans}' \land id_a = id_{trans}' \land seq' > seq_a$}
            \State \Return{false}
        \EndIf
    \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, seq_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 $AllColRes \gets$ \Call{GetColRes}{}
    \If{$\exists \tuple{id', seq_{old}', seq_{new}', local', seq'} \in AllColRes, id'=id_a \land seq_{old}'= seq_{a_{old}} \land seq_{new}'= seq_{a_{new}} \land local'=equal_a \land seq_2' > seq_a$}
        \State \Return{false}
    \EndIf
    
    \State \Return{true}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

%Check Transaction Part Live
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Transaction Part Live:}\\
Check if a transaction part is live or not.
\begin{algorithmic}[1]
\Function{CheckTransPartLive}{$transpart_a, seq_a$}
    \State $\tuple{Dat, arb,seq_{clientLocal}, seq_{server}, id, partnum,isLast} \gets transpart_a$
    
    \If{$\exists \tuple{id',seq'} \in LastTransactionArbitrated \land id'=arb land seq' \geq seq_{server}$}
        \State \Return{False}
    \EndIf
    
    \State $AllTransParts \gets$ \Call{GetTransParts}{} 
    \If{$\exists \tuple{Dat',arb',seq_{clientLocal}', seq_{server}', id', partnum', isLast', seq'} \in AllTransParts, seq_{server} = seq_{server}' \land partnum' = partnum \land seq' > seq_a$}
        \State \Return{false}
    \EndIf    
    \State \Return{True}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

%Check Commit Part Live
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Commit Part Live:}\\
Check if a commit part is live or not.
\begin{algorithmic}[1]
\Function{CheckCommitPartLive}{$commitpart_a, seq_a$}
    \State $\tuple{Dat,seq_t, seq_s, id, partnum, isLast, seq} \gets commitpart_a$
    \State $AllComParts \gets $ \Call{GetComParts}{}\\
    
    \If{$\exists \tuple{Dat',seq_t', seq_s', id, partnum', isLast', seq'} \in AllComParts, seq_s = seq_s' \land partnum'= partnum \land seq' > seq_a$}
        \State \Return{False}
    \EndIf
    
    \ForAll{$\tuple{P, KV, seq_t, seq_s,id} \in LiveCommits$}
        \If{$commitpart_a \in P$}
            \State \Return{True}
        \EndIf
    \EndFor
    
    \State \Return{False}
\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 $compart$}
        \State \Return{\Call{CheckCommitPartLive}{$datentry, seq$}}\
    \ElsIf{$datentry$ is a $abort$}
        \State \Return{\Call{CheckAbortLive}{$datentry, seq$}}\
    \ElsIf{$datentry$ is a $transpart$}
        \State \Return{\Call{CheckTransPartLive}{$datentry,seq$}}\
    \ElsIf{$datentry$ is a $lastmsg$}
        \State \Return{\Call{CheckLastMsgLive}{$datentry, seq$}}\
    \ElsIf{$datentry$ is a $colres$}
        \State \Return{\Call{CheckColResLive}{$datentry, seq$}}\
    \ElsIf{$datentry$ is a $qstate$}
        \State \Return{\Call{CheckQStateLive}{$datentry, seq$}}
    \ElsIf{$datentry$ is a $newkey$}
        \State \Return{\Call{CheckNewkeyLive}{$datentry, seq$}}
    \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{seq_1, \tuple{seq_2,id,DE,hmac_p,hmac_c}} \in LocalSlots$
    
    \ForAll{$datentry \in DE$}
        \If{\Call{CheckLive}{$datentry, seq_1$}} \Comment{an entry is alive}
            \State \Return{true}
        \EndIf
    \EndFor
    
    \State \Return{false} \Comment{All entries were dead}    
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Rejected Messages
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Rejected Messages:}\\
\begin{algorithmic}[1]
\Function{RejectedMessages}{$DE_a$}
    \State $seq_{old} \gets seq$ such that $\tuple{seq} \in RejectedSlotList \land \forall \tuple{seq'} \in RejectedSlotList, seq \geq seq'$
    \State $prev \gets -1$\\
    
    \If{$|RejectedSlotList| \geq REJECTED\_THRESH$}
        \State $seq_{new} \gets seq$ such that $\tuple{seq} \in RejectedSlotList \land \forall \tuple{seq'} \in RejectedSlotList, seq \leq seq'$\\
        \State $colres \gets $ \Call{CreateColRes}{$LOCAL\_ID, seq_{old}, seq_{new}, false$}    
        \State \Return{$DE_a \cup \{colres\}$}
    \EndIf\\
    
    \ForAll{$\tuple{seq} \in RejectedSlotList$ sorted by $seq$}
        \If{$\exists \tuple{seq',Dat'} \in LocalSlots$}
            \State Break
        \EndIf
        \State $prev \gets seq$
    \EndFor\\
    
    \If{$prev \neq -1$}
        \State $DE_a \gets DE_a \cup$ \Call{CreateColRes}{$LOCAL\_ID, seq_{old}, prev, false$}
    \EndIf\\
    
    \State $RejectedSlotList \gets \{\tuple{seq}| \tuple{seq} \in RejectedSlotList, seq > prev\}$\\
    
    \ForAll{$\tuple{seq} \in RejectedSlotList$ sorted by $seq$}
        \State $DE_a \gets DE_a \cup$ \Call{CreateColRes}{$LOCAL\_ID, seq,seq, false$}
    \EndFor\\
    
    \State \Return{$DE_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}
                \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{$\tuple{$true$,DE_a}$}
                \Else
                    \State \Return{$\tuple{$false$,DE_a}$}
                \EndIf
            \EndIf
        \EndFor\\
        
        \State $cseq \gets cseq+1$ \Comment{Move onto the next slot}
    \EndWhile
    
    \State \Return{$\tuple{$false$,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 enoug 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}% 
%}

% 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}% 
%}













% Fill Slot
%% \noindent\fbox{%
%% \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
% \begin{algorithm}
\textbf{Fill Slot:}\\
Fill a slot with data that needs to be inserted into the block chain.
\begin{algorithmic}[1]
\Function{FillSlot}{$newkey_a $}
    \State $resize \gets False$
    \State $newsize \gets 0$
     
    \State $DE \gets \emptyset$ \Comment{The data entries for this slot} \label{resetMarker}
    \State $seq \gets $ \Call{GetNextSeq}{} \Comment{Get the sequence number for this slot}

     
    \State $resize \gets resize \lor $ \Call{ShouldResize}{ } \Comment{Check if we should resize}
    \If{$resize$}
        \State $newsize \gets$ \Call{CalcNewSize}{$max\_size$}
        \State $DE \gets DE \cup \{$\Call{CreateQState}{$newsize$}$\}$
    \EndIf\\
     
    \If{$RejectedSlotList \neq \emptyset$}   
        \State $DE \gets$ \Call{RejectedMessages}{$DE$}
    \EndIf\\

    \State $\tuple{needRezize,DE} \gets$ \Call{MandatoryRescue}{$DE$} \Comment{Round 1 of rescue}
    \If{$needRezize \land \lnot resize$}
        \LeftComment{Data was going to fall off the end so try again with a forced resize}
        \State $resize \gets $ true
        \State \Goto{resetMarker}
    \EndIf\\
    
    \If{$newkey_a \neq NULL \land $\Call{DEHasSpace}{$DE, newkey_a$}}
        \State $DE \gets DE \cup \{newkey_a\}$
    \EndIf\\
    
    \ForAll{$\tuple{commit, AbortSet, SentSet} \in ArbitrationRound$ in order of insertion}
        \ForAll{$abort \in (AbortSet \setminus SentSet)$}  
            \State $\tuple{seq_{clientlocal}, seq_{server}, id, arb, seq_{arb}} \gets abort$
            \State $abort \gets \tuple{seq_{clientlocal}, seq, id, arb, seq_{arb}}$ \Comment{Set sequence number}
            
            \If{\Call{DEHasSpace}{$De, abort$}}
                \State $DE \gets DE \cup abort$
            \Else
                \State \Goto{EndArb}
            \EndIf
        \EndFor
        
        \If{$commit \neq NULL$}
            \If{\Call{DEHasSpace}{$De, commit$}}
                \State $DE \gets DE \cup commit$
            \Else
                \State \Goto{EndArb}
            \EndIf
        \EndIf
    \EndFor \label{EndArb}
    
    
    \If{$|PendingTransactionQueue| > 0$}
        \State $\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb}, Sent, hadTimeout} \gets PendingTransactionQueue.peak()$
        
        \If{$(|Sent| = 0 \land \lnot hadTimeout) \lor (seq_s = -1)$}
            \State $seq_s \gets seq$
            \ForAll{$part \in P$}
                \State $\tuple{Dat,arb,seq_{cl}, seq_{server}, id, partnum, isLast} \gets part$
                \State $part \gets \tuple{Dat,arb,seq_{cl}, seq, id, partnum, isLast}$
            \EndFor
        \EndIf
        
        \ForAll{$part \in (P \setminus Sent)$}
            \If{\Call{DEHasSpace}{$De, part$}}
                \State $DE \gets DE \cup part$
            \Else
                \State \Goto{EndTrans}
            \EndIf
        \EndFor
    \EndIf \label{EndTrans}
    

    \LeftComment{Rescue data to fill slot data entry section}
    \State $DE \gets$ \Call{OptionalRescue}{$DE$}\\
    \State $newslot \gets $\Call{CreateNewSlot}{$seq, DE$}
    \State \Return{$\tuple{newslot,DE, newsize}$}    
\EndFunction
\end{algorithmic}
% \end{algorithm}

% %\end{varwidth}% 
% } 








% Send to Server
%% \noindent\fbox{%
%% \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
% \begin{algorithm}
\textbf{Send to Server:}\\
Send local data to server if there is any local data that needs to be sent.
\algblock[TryCatchFinally]{try}{endtry}
\algcblock[TryCatchFinally]{TryCatchFinally}{finally}{endtry}
\algcblockdefx[TryCatchFinally]{TryCatchFinally}{catch}{endtry}
    [1]{\textbf{catch} #1}
    {\textbf{end try}}

\begin{algorithmic}[1]
\Function{SendToServer}{$slot_a, newsize_a$} throws $Server\_Connection\_Timeout$, $Server\_Response\_Timeout$
    \State $\tuple{seq_a, DE_A} \gets slot_a$
    \State $EDE_a \gets $ \Call{Encrypt}{$DE_A$}
    \State $slot_a \gets \tuple{seq_a, EDE_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 $NewSlots_{decrypt} \gets \emptyset$
        \ForAll{$\tuple{seq', EDat'} \in NewSlots$}
            \State $DDat \gets $ \Call{Decrypt}{$EDat'$}
            \State $NewSlots_{decrypt} \gets NewSlots_{decrypted} \cup \tuple{seq',DDat}$
        \EndFor\\
        
        \If{$hadPartialSendToServer$}
            
            \If{$\exists \tuple{seq_1, \tuple{seq_2,id,DE,hmac_p,hmac_c}} \in NewSlots_{decrypt}, id=LOCAL\_ID \land seq_2 = seq_a$}
                \Return{$\tuple{true, NewSlots_{decrypted}}$}
            \EndIf\\
            
             \If{$\exists \tuple{seq_1, \tuple{seq_2,id,DE,hmac_p,hmac_c}} \in NewSlots_{decrypt}, \exists \tuple{seq', id'} \in DE, \tuple{seq', id'}$ is a $ \land id'=LOCAL\_ID \land seq'=seq_a$}
                \Return{$\tuple{true, NewSlots_{decrypted}}$}
            \EndIf
        \EndIf\\
        
        \State $RejectedSlotList \gets RejectedSlotList \cup \{seq_a\}$
        \State \Return{$\tuple{false, NewSlots_{decrypted}}$}
    \EndIf\\
    
\EndFunction
\end{algorithmic}
% \end{algorithm}
% %\end{varwidth}% 
% }







% Send to Server
%% \noindent\fbox{%
%% \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
% \begin{algorithm}
\textbf{Send to Server:}\\
Send local data to server if there is any local data that needs to be sent.
\algblock[TryCatchFinally]{try}{endtry}
\algcblock[TryCatchFinally]{TryCatchFinally}{finally}{endtry}
\algcblockdefx[TryCatchFinally]{TryCatchFinally}{catch}{endtry}
    [1]{\textbf{catch} #1}
    {\textbf{end try}}

\begin{algorithmic}[1]
\Function{SendToServer}{$NewKey_a$}
    \State $SlotDE \gets \emptyset$
    
    \try
        \While{$|PendingTransactionQueue| > 0 \lor |SendArbQueue| > 0 \lor NewKey_a \neq NULL$}
            \State $\tuple{slot, SlotDE, newsize} \gets $ \Call{FillSlot}{$NewKey_a$}
            \State $\tuple{inserted, NewSlots} \gets $ \Call{SendToServer}{$slot, newsize$} 
            \If{$inserted$} 
                \State $NewKey_a \gets NULL$
                
                
                \ForAll{$\tuple{commit, AbortSet, SentSet} \in ArbitrationRound$}
                    \State $ArbitrationRound \gets ArbitrationRound \setminus \tuple{commit, AbortSet, SentSet}$
                    \State $SentSet \gets SentSet \cup \{e| e\in(\{commit\} \cup AbortSet) \land e \in SlotDE\}$
                    
                    \LeftComment{Add Back to the set if not done sending}
                    \If{$(commit=NULL \land |AbortSet| \neq |SentSet|) \land (commit \neq NULL \land (|AbortSet|+1) \neq |SentSet|)$}
                        \State $ArbitrationRound \gets ArbitrationRound \cup \tuple{commit, AbortSet, SentSet}$
                    \EndIf
                \EndFor

            
                \ForAll{$\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb},SentSet,hadTimeout} \in PendingTransactionQueue$ where $\exists p \in P, p \in SlotDE$}
                    \State $pos \gets PendingTransactionQueue.remove(\setminus \{\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb},SentSet,hadTimeout})$
                    \State $SentSet \gets SentSet \cup \{p|p \in P \land p \in SlotDE\}$\\
                    
                    \If{$|SentSet| > 0 \land id = LOCAL\_ID$}
                        \State $TransStatus \gets $ \Call{GetTransStatus}{$id,seq_l$}
                        \State \Call{ChangeTransStatus}{$TransStatus,sentfully$}
                    \EndIf\\
                    
                    \If{$|P| \neq |SentSet|$}
                        \State $PendingTransactionQueue.insert(pos, \{\tuple{\tuple{P, KV, G,seq_l, -1,id, arb},SentSet,false})$
                    \ElsIf{$id = LOCAL\_ID$}
                        \State $TransStatus \gets $ \Call{GetTransStatus}{$id,seq_l$}
                        \State \Call{ChangeTransStatus}{$TransStatus,sentfully$}
                        \State \Call{DeleteTransStatus}{$id,seq_l$}
                    \EndIf                    
                \EndFor                
            \Else
                \ForAll{$\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb},SentSet,hadTimeout} \in PendingTransactionQueue$ where $\exists p \in P, p \in SlotDE$}
            \If{$|Sent| = 0$}
                \State $PendingTransactionQueue.replace(\{\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb},SentSet,hadTimeout},\tuple{\tuple{P, KV, G,seq_l, -1,id, arb},SentSet,hadTimeout})\}$
            \EndIf
        \EndFor
            \EndIf
            
            
            \State \Call{ValidateAndUpdate}{$NewSlots$}        
        \EndWhile
    \catch{$Server\_Connection\_Timeout$}        
        \ForAll{$\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb},SentSet,hadTimeout} \in PendingTransactionQueue$ where $\exists p \in P, p \in SlotDE$}
            \If{$|Sent| = 0$}
                \State $PendingTransactionQueue.replace(\{\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb},SentSet,hadTimeout}, \tuple{\tuple{P, KV, G,seq_l, -1,id, arb},SentSet,hadTimeout})$
            \EndIf
        \EndFor
        
        \State \textbf{rethrowException}\\
        
    \catch{$Server\_Response\_Timeout$}
        \State $hadPartialSendToServer \gets True$
        \ForAll{$\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb},SentSet,hadTimeout} \in PendingTransactionQueue$ where $\exists p \in P, p \in SlotDE$}
            \State $PendingTransactionQueue.replace(\{\tuple{\tuple{P, KV, G,seq_l, seq_s,id, arb},SentSet,hadTimeout}, \tuple{\tuple{P, KV, G,seq_l, -1,id, arb},SentSet,True})$
        \EndFor
        \State \textbf{rethrowException}
    \endtry
    
    \State \Return{$NewKey_a = NULL$}
\EndFunction
\end{algorithmic}
% \end{algorithm}

% %\end{varwidth}% 
% }




% Check Slot Hmacs
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Slot HMACs:}\\
Check that each slot has not been tampered with by checking that the stored HMAC matches the calculated HMAC.  Also check thatthe slot number reported by the server matches the slot number of the actual slot.
\begin{algorithmic}[1]
\Function{CheckSlotsHmacAndSeq}{$Slots_a$}
    \ForAll{$slot_a \in Slots_a$}
        \State $\tuple{seq_{a_1}, \tuple{seq_{a_2},id_a,DE_a,hmac_{a_p},hmac_{a_c}}} \gets slot_a$
        \State $calchmac \gets $ \Call{GenerateHmac}{$seq_{a_2}, id_a, DE_a, hmac_{a_p}$}
    
        \If{$seq_{a_1} \neq seq_{a_2}$}
          \State \Call{Error}{"Slot sequence number mismatch"}
        \ElsIf{$calchmac \neq hmac_{a_c}$}
            \State \Call{Error}{"Slot HMAC mismatch"}
        \EndIf
    \EndFor
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Check HMAC Chain
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check HMAC Chain:}\\
Check that the HMAC chain has not been violated.
\begin{algorithmic}[1]
\Function{CheckHmacChain}{$Slots_a$}
    \State $SlotsList \gets Slots_a$ sorted by sequence number\\  
    
    \LeftComment{Check all new slots}
    \ForAll{$index \in [2: |SlotsList|]$}
        \State $\tuple{seq_{a_1}, \tuple{seq_{a_2},id_a,DE_a,hmac_{a_p},hmac_{a_c}}} \gets SlotList[i-1]$
        \State $\tuple{seq_{b_1}, \tuple{seq_{b_2},id_b,DE_b,hmac_{b_p},hmac_{b_c}}} \gets SlotList[i]$
        
        \If{$hmac_{b_p} \neq hmac_{b_c}$}
            \State \Call{Error}{"Invalid previous HMAC."}
        \EndIf    
    \EndFor\\
    
    \LeftComment{Check against slots that we already have in the block chain}
    \If{$|LocalSlots| \neq 0$}
        \State $\tuple{seq, SDE} \gets $\Call{MaxSlot}{$LocalSlots$}
        \State $\tuple{seq{last_2},id_{last},DE_{last},hmac_{last_p},hmac_{last_c}} \gets SDE$
        \State $\tuple{seq_{a_1}, \tuple{seq_{a_2},id_a,DE_a,hmac_{a_p},hmac_{a_c}}} \gets SlotList[1]$\\

        \If{$(seq_{last_2} + 1) = seq_{a_1} \land hmac_{a_p} \neq hmac_{last_c}$}    
            \State \Call{Error}{"Invalid previous HMAC."}
        \EndIf
    \EndIf
    
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Check For Old Slots
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check For Old Slots:}\\
Check if the slots are not new.  Checks if the "new" slots are actually new or if they are older than the most recent slot that we have.
\begin{algorithmic}[1]
\Function{CheckOldSlots}{$Slots_a$}
    \State $\tuple{seq_{new}, Dat_{new}} \gets$ \Call{MinSlot }{$Slots_a$} \Comment{Get the oldest new slot}
    \State $\tuple{seq_{local}, Dat_{local}} \gets$ \Call{MaxSlot }{$LocalSlots$} \Comment{Get the newest slot seen}\\
    
    \If{$seq_{new} \leq seq_{local}$} \Comment{The slots were not newer than what was already seen}
        \State \Call{Error}{"Server sent old slots."}
    \EndIf
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Check Size With Gap
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Size With Gap:}\\
Checks that the block chain size is correct when there is a gap in the block chain.  This check makes sure that the server is not hiding any information from the client.  If there is a gap and there is only 1 queue state in the new slot entries then there must have at least that many slots since the old slot entry must have been purged.  If there is more than 1 queue state then the block chain is still growing check the smallest max size and there should be at least that many slots. 
\begin{algorithmic}[1]
\Function{CheckSizeWithGap}{$Slots_a$}    
    %\State $QSSet \gets $ \Call{GetQStateWithSeq}{$Slots_a$}
    %\State $\tuple{seq_{max}, size_{max}} \gets \tuple{seq, size}$ such that $\tuple{seq, size} \in QSSet \land \forall \tuple{seq', size'} \in QSSet, size \geq size'$ \Comment{Get largest size}
    %\State $\tuple{seq_{min}, size_{min}} \gets \tuple{seq, size}$ such that $\tuple{seq, size} \in QSSet \land \forall \tuple{seq', size'} \in QSSet , size \leq size'$ \Comment{Get smallest size}
    
    \State $QSet \gets $ \Call{GetQState}{$Slots_a$}
    \State $size_{max} \gets size$ such that $size \in QSet \land \forall size' \in QSet, size \geq size'$ 
    \State $size_{min} \gets size$ such that $size \in QSet \land \forall size' \in QSet, size \leq size'$     
    \State $Slots_{oldmax} \gets \emptyset$\\

    
    \LeftComment{If only 1 max size then we must have all the slots for that size}
    \If{$(|QSSet| = 1) \land (|Slots_a| \neq size_{max})$}
        \State \Call{Error}{"Missing Slots"}
    \EndIf\\
    
    \LeftComment{We definitely have all the slots}
    \If$|Slots_a| = size_{max}$
        \State \Return{} \Comment{We have all the slots}
    \EndIf\\
    
    \LeftComment{We must have at least this many slots}
    \If$|Slots_a| < size_{min}$
        \State \Call{Error}{"Missing Slots"}
    \EndIf\\

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

% Check Size
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Check Size:}\\
\begin{algorithmic}[1]
\Function{CheckSize}{$Slots_a$}    
    \State $\tuple{seq_{old_{max}}, Dat_{old_{max}}} \gets $ \Call{MaxSlot}{$LocalSlots$}
    \State $\tuple{seq_{new_{max}}, Dat_{new_{max}}} \gets $ \Call{MinSlot}{$Slots_a$}\\
    
    \If{$(seq_{old_{max}} + 1) = seq_{new_{max}}$}
        \LeftComment{No Gap so cannot say anything about the size}
        \State \Return{} 
    \Else 
        \LeftComment{Has a gap so we need to do checks}
        \State \Call{CheckSizeWithGap}{$Slots_a$}
    \EndIf
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Process New Key Data Entry
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Process New Key Entry:}\\
Process a queue state entry. Adds a key to the key arbitrator set.
\begin{algorithmic}[1]
\Function{ProcessNewkey}{$newkey_a$}
    \State $Arbitrator \gets Arbitrator \cup \{newkey_a\}$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Process Collision Resolution Entry
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Process Queue State Entry:}\\
Process a collision resolution entry.
\begin{algorithmic}[1]
\Function{ProcessColres}{$colres_a, NewSlots_a$}
    \State $\tuple{id_a, seq_{a_{old}}, seq_{a_{new}}, isequal_a}$
    \State $AllSlots \gets LocalSlots \cup NewSlots_a$
    \State $index \gets seq_{a_{old}}$\\
    
    \While{$index <= seq_{a_{new}}$}
        \State $slt \gets \tuple{seq' Dat'}$ such that $\tuple{seq' Dat'} \in AllSlots \land seq'=index$
        
        \If{$\exists \tuple{seq' Dat'} \in AllSlots, seq' = index$}
            \State $\tuple{seq, Dat} \gets \tuple{seq' Dat'}$ such that $\tuple{seq' Dat'} \in AllSlots \land seq'=index$
            \State $\tuple{seq,id,DE,hmac_p,hmac_c} \gets Dat$
            \If{$isequal_a \neq (id=id_a)$}
                \State \Call{Error}{"Trying to insert rejected messages for slot"}
            \EndIf
        \EndIf\\
        \State $index \gets index + 1$
    \EndWhile
    
    
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Process Queue State Data Entry
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Process Queue State Entry:}\\
Process a queue state entry. Updates the max size of the block chain.
\begin{algorithmic}[1]
\Function{ProcessQState}{$qstate_a$}
    \State $\tuple{size_a} \gets qstate_a$
    \State $max\_size \gets size_a$ \Comment{Update the max size we can have}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Process Transaction Part Entry
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Process Transaction Part Entry:}\\
Process a new Transaction Part Entry.
\begin{algorithmic}[1]
\Function{ProcessTransPart}{$TransactionPart_a$}
    \State $\tuple{Dat,arb,seq_{clientLocal}, seq_{server}, id, partnum, isLast} \gets TransactionPart_a$
    \State $Transaction \gets NULL$\\
    
    \If{$\exists \tuple{id',seq'} \in LastTransactionArbitrated \land id'=arb land seq' \geq seq_{server}$}
        \State \Return{}
    \EndIf\\
    
    \If{$\exists \tuple{Parts', KV', G',seq_{clientlocal}', seq_{server}',id', arb'} \in LiveTransactions, seq_{server}' = seq_{server}$}
        \State $Transaction \gets \tuple{Parts', KV', G',seq_{clientlocal}', seq_{server}',id', arb'} \in LiveTransactions$such that$ seq_{server}' = seq_{server}$
        \State $LiveTransactions \gets LiveTransactions \setminus \{Transaction\}$
    \Else
        \State $Transaction \gets \tuple{\emptyset, \emptyset, \emptyset, seq_{clientlocal}, seq_{server},id, arb}$
    \EndIf\\
    
    \State $\tuple{Parts, KV, G,seq_{local}, seq_{server},id, arb} \gets Transaction$
    \State $Parts \gets Parts \cup TransactionPart_a$\\
    
    \If{$\exists \tuple{Dat,arb,seq_{clientLocal}, seq_{server}, id, partnum, isLast} \in Parts \land isLast \land |Parts| = partnum$}
        \State $\tuple{KV, G} \gets $\Call{DecodeParts}{$Parts$}
    \EndIf
    
    \State $Transactin \gets \tuple{Parts, KV, G,seq_{local}, seq_{server},id,arb}$.
    \State $LiveTransactions \gets LiveTransactions \cup \{Transaction\}$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Process Abort Entry
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Process Abort Entry:}\\
Process a new Abort Entry.
\begin{algorithmic}[1]
\Function{ProcessAbort}{$abort_a$}
    \State $\tuple{seq_{cl}, seq_{s}, id, arb, seq_{arb}} \gets abort_a$
    
    \If{$\lnot(\exists \tuple{id',seq'} \in LastArbLocalArbitrated, id'=id \land seq' > seq_{arb})$}
        \State $LastArbLocalArbitrated\gets \tuple{\tuple{id',seq'}|\tuple{id',seq'}  \in LastArbLocalArbitrated, id' \neq id} \cup \{\tuple{id, }\}$
    \EndIf
    
    \If{$\lnot(\exists \tuple{id',seq'} \in LastTransactionArbitrated, id'=id \land seq' > seq_{s})$}
        \State $LastTransactionArbitrated \gets \tuple{\tuple{id',seq'}|\tuple{id',seq'}  \in LastTransactionArbitrated, id' \neq id} \cup \{\tuple{id, seq_{s}}\}$
    \EndIf    
    
    \If{$id = LOCAL\_ID$}
        \State $TransStatus \gets $ \Call{GetTransStatus}{$id, seq_{cl}$}
        \State \Call{ChangeTransStatus}{$TransStatus,abort$}
        \State \Call{DeleteTransStatus}{$id, seq_{cl}$}
    \EndIf
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Process Commit Part Entry
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Process Commit Part Entry:}\\
Process a new Commit Part Entry.
\begin{algorithmic}[1]
\Function{ProcessCommitPart}{$CommitPart_a$}
    \State $\tuple{Dat,seq_t, seq_s, id, partnum, isLast} \gets CommitPart_a$
    \State $Commit \gets NULL$\\
    
    \If{$\exists \tuple{P', KV', seq_t', seq_s',id'} \in LiveCommits, seq_s' = seq_s$}
        \State $Commit \gets \tuple{P', KV', seq_t', seq_s',id} \in LiveCommits$ such that$ seq_{s}' = seq_{s}$
        \State $LiveCommits \gets LiveCommits \setminus \{Commit\}$
    \Else
        \State $Commit \gets \tuple{\emptyset, \emptyset, seq_t, seq_s,id}$
    \EndIf\\
    
    \State $\tuple{P, KV, seq_t, seq_s,id} \gets Commit$
    \State $P \gets P \cup CommitPart_a$\\
    
    \If{$\exists \tuple{Dat',seq_t', seq_s', id', partnum', isLast'} \in P \land isLast' \land |P| = partnum$}
        \State $KV \gets $\Call{DecodeParts}{$P$}
    \EndIf\\
    
    \State $Commit \gets \tuple{P, KV, seq_t, seq_s,id}$
    \State $LiveCommits \gets LiveCommits \cup \{Commit\}$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Update Last Message
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Process Commit Data Entry:}\\
Process a commit entry.  Updates the local copy of commits.
\begin{algorithmic}[1]
\Function{UpdateLastMessage}{$seq_a, id_a, updateinglocal_a, MachinesSeen$}
    \State $\tuple{id_{old}, seq_{old}} \gets \tuple{id', seq'}$ such that $\tuple{id', seq'} \in LastSlot \land id'=id$\\
    
    \If{$id_a = LOCAL\_ID$}
        \If{$hadPartialSendToServer$}
            \If{$\lnot updateinglocal_a \land (seq_a < seq_{old})$}
                \LeftComment{This client did not make any updates so its latest sequence number should not change}
                \State \Call{Error}{"Mismatch on local machine sequence number"}
            \EndIf
        \Else
            \If{$\lnot updateinglocal_a \land (seq_a \neq seq_{old})$}
                \LeftComment{This client did not make any updates so its latest sequence number should not change}
                \State \Call{Error}{"Mismatch on local machine sequence number"}
            \EndIf
        \EndIf
    \Else
        \If{$seq_{old} > seq_a$}
            \State \Call{Error}{"Rollback on remote machine sequence number"}
        \EndIf
    \EndIf\\
    
    \State $LastSlot \gets LastSlot \setminus \{\tuple{id, seq} | \tuple{id, seq} \in LastSlot, id=id_a\}$
    \State $LastSlot \gets LastSlot \cup \{\tuple{id_a, seq_a}\}$
    \State $MachinesSeen \gets MachinesSeen \setminus \{id_a\}$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Process Process Data Entry
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Process Data Entry:}\\
Process the data entry based on what kind of entry it is.
\begin{algorithmic}[1]
\Function{ProcessDatEntry}{$slot_a, NewSlots_a,MachinesSeen$}
    \If{$datentry_a$ is a $compart$}
        \State \Call{ProcessCommitPart}{$dataentry_a$}
        
    \ElsIf{$datentry_a$ is a $abort$}
        \LeftComment{Do Nothing in this case}
        
    \ElsIf{$datentry_a$ is a $transpart$}
        \State \Call{ProcessTransPart}{$dataentry_a$}
    
    \ElsIf{$datentry_a$ is a $lastmsg$}
        \State $\tuple{seq_a, id_a} \gets dataentry_a$
        \State \Call{UpdateLastMessage}{$seq_a, id_a, false, MachinesSeen$}
    
    \ElsIf{$datentry_a$ is a $colres$}
        \State \Call{ProcessColres}{$dataentry_a, NewSlots_a$}
        
    \ElsIf{$datentry_a$ is a $qstate$}
        \State \Call{ProcessQState}{$dataentry_a$}
        
    \ElsIf{$datentry_a$ is a $newkey$}
        \State \Call{ProcessNewkey}{$dataentry_a$}
    \Else
        \State \Call{Error}{"Unknown data entry type."}
    \EndIf
    
    \State \Return{$LstSlt_a$}    
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Update Committed Table
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Update Committed Key value Table:}\\
Update the table of committed Key Value Pairs based on commits that we received.
\begin{algorithmic}[1]
\Function{UpdateCommitTable}{$ $}   
    
    \State $ArbSet \gets \{id'| \tuple{P, KV, seq_t, seq_s,id'} \in LiveCommits\}$
    
    \ForAll{$id \in ArbSet$}
        \State $Commits \gets \{\tuple{P, KV, seq_t, seq_s,id'}| \tuple{P, KV, seq_t, seq_s,id'} \in LiveCommits \land id' = id\}$
        
        \State $lastComSeenSeq \gets -1$
        \If{$\exists \tuple{id',seq'} \in LastCommitSeenFromArbitrator, id'=id$}
            \State $lastComSeenSeq  \gets seq$ such that $\tuple{id',seq'} \in LastCommitSeenFromArbitrator, id'=id$
        \EndIf\\
        
        \ForAll{$\tuple{P, KV, seq_t, seq_s,id} \in Commits$ sorted by $seq_s$ where $seq_s > lastComSeenSeq$}

            \If{$(\forall \tuple{D',seq_t', seq_s', id', pn', isLast'} \in P, \lnot isLast')\lor(\exists \tuple{D',seq_t', seq_s', id', pn', isLast'} \in P,isLast') \land |P| \neq pn)$}
                \If{$\forall \tuple{P', KV', seq_t', seq_s',id'} \in Commits, seq_s' < seq_s$}
                    \State Break \Comment{This is the last slot so ignore it}
                \Else
                    \State Continue
                \EndIf
            \EndIf\\
            
            \If{$\lnot(\exists \tuple{id',seq'} \in LastArbLocalArbitrated, id'=id \land seq' > seq_s)$}
                \State $LastArbLocalArbitrated\gets \tuple{\tuple{id',seq'}|\tuple{id',seq'}  \in LastArbLocalArbitrated, id' \neq id} \cup \{\tuple{id, seq_s}\}$
            \EndIf
            
            \State $LastCommitSeenFromArbitrator \gets \{ \tuple{id',seq'}| \tuple{id',seq'} \in LastCommitSeenFromArbitrator,id' \neq id\} \cup \{\tuple{id, seq_s}\}$

             \If{$\lnot(\exists \tuple{id',seq'} \in LastTransactionArbitrated, id'=id \land seq' > seq_{t})$}
                \State $LastTransactionArbitrated \gets \tuple{\tuple{id',seq'}|\tuple{id',seq'}  \in LastTransactionArbitrated, id' \neq id} \cup \{\tuple{id, seq_{t}}\}$
            \EndIf    
            
            \LeftComment{Update Committed Table}
            \State $CommittedKV \gets \{\tuple{k,v}| \tuple{k,v} \in CommittedKV \land \forall \tuple{k',v'} \in KV, k\neq k' \} \cup KV$              
            \State $LiveCommits \gets LiveCommits \cup \tuple{P, KV, seq_t, seq_s,id}$\\
        
            \ForAll{$\tuple{P, KV, seq_t, seq_s,id} \in LiveCommits$}
                \LeftComment{All Key Values in this commit have been overridden by a newer commit}    
                \If{$\forall \tuple{k,v} \in KV, \exists \tuple{P', KV', seq_t', seq_s',id'} \in LiveCommits, \exists \tuple{k',v'} \in KV', k'=k \land seq_s' > seq_s$}
                    \State $LiveCommits \gets LiveCommits \setminus \{\tuple{P, KV, seq_t, seq_s,id}\}$
                \EndIf
            \EndFor            
        \EndFor
    \EndFor
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Update Speculative Table
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Update Speculated Key value Table:}\\
Update the table of speculative Key Value Pairs based on commits that we received.
\begin{algorithmic}[1]
\Function{UpdateSpeculativeKV}{$ $}
    \State $SpecKV \gets CommittedKV$\\
    
    \ForAll{$\tuple{P, KV, G,seq_{cl}, seq_s,id, arb} \in LiveTransactions$ sorted by $seq_s$}
         \If{$\forall \tuple{D',arb',seq_{l}', seq_{s}', id', pn', isLast'} \in P, \lnot isLast'$}
            \State Continue
        \ElsIf{$(\exists \tuple{D',arb',seq_{l}', seq_{s}', id', pn', isLast'} \in P,isLast') \land |P| \neq pn$}
            \State Continue
        \EndIf\\
        
        \If{\Call{EvaluateGuard}{$G, SpecKV$}}
            \State $SpecKV\gets \{\tuple{k',v'}| \tuple{k',v'} \in SpecKV \land \forall \tuple{k,v} \in KV, k' \neq k\}\cup KV$
        \EndIf
    \EndFor\\
    
    \ForAll{$\tuple{KV, G, id, seq} \in PendingTransactionQueue$ sorted by $seq$}
        \If{\Call{EvaluateGuard}{$G, SpecKV$}}
            \State $SpecKV\gets \{\tuple{k',v'}| \tuple{k',v'} \in SpecKV \land \forall \tuple{k,v} \in KV, k' \neq k\}\cup KV$
        \EndIf
    \EndFor\\
    
    \State $SpeculatedKV \gets SpecKV$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Compact Arbitration Rounds
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Compact Arbitration Rounds:}\\
Compact Arbitration Rounds to reduce the amount of data needed to be sent to the server.
\begin{algorithmic}[1]
\Function{CompactArbitrationRounds}{$ $}
    \If{$|SendArbQueue| < 2$}
        \State \Return{False}
    \EndIf\\
    
    \State $didMergeWithCommit \gets False$
    
    \While{$|SendArbQueue| > 1$}
        \State $\tuple{c_1, A_1, S_1} \gets SendArbQueue.peak(|SendArbQueue|)$
        \State $\tuple{c_2, A_2, S_2} \gets SendArbQueue.peakEnd(|SendArbQueue| - 1)$\\
        
        \If{$|S_1| \neq 0 \lor |S_2| \neq 0$}
            \State \Return{$didMergeWithCommit$}
        \EndIf\\
        
        \If{$c_2 = NULL$}
            \If{$|A_1| + |A_2| > MAX\_ROUND\_SIZE$}
                \State \Return{$didMergeWithCommit$}
            \EndIf            
            \State $SendArbQueue.remove(|SendArbQueue|)$
            \State $SendArbQueue.remove(|SendArbQueue|)$
            \State $SendArbQueue \gets SendArbQueue \cup \tuple{c_1, A_1 \cup A_2, \emptyset}$
        \Else
            \State $\tuple{P_1, KV_1, seq_{1_t}, seq_{1_s},id_1} \gets c_1$
            \State $\tuple{P_2, KV_2, seq_{2_t}, seq_{2_s},id_2} \gets c_2$
            \State $newKV \gets \{\tuple{k_2,v_2}| \tuple{k_2,v_2} \in KV_2 \land \forall \tuple{k_1,v_1} \in KV_1 \land k_1 \neq k_2\} \cup KV_1$
            \State $NewCom \gets \tuple{P_1, newKV, seq_{1_t}, seq_{1_s},id_1}$
            \State \Call{GenerateParts}{$NewCom$}
            \State $\tuple{P_1, newKV, seq_{1_t}, seq_{1_s},id_1} \gets NewCom$\\
            
            \If{$|P_1| > MAX\_ROUND\_SIZE$}
                \State \Return{$didMergeWithCommit$}
            \EndIf\\
            
            \State $SendArbQueue.remove(|SendArbQueue|)$
            \State $SendArbQueue.remove(|SendArbQueue|)$
            \State $SendArbQueue \gets SendArbQueue \cup \tuple{newCom, A_1 \cup A_2, \emptyset}$
            \State $didMergeWithCommit \gets True$
        \EndIf
    \EndWhile  
    
    \State \Return{$didMergeWithCommit$}
    
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Arbitrate From Server
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Arbitrate Form Server:}\\
Arbitrate on the transactions that were received from the server
\begin{algorithmic}[1]
\Function{ArbitrateFromServer}{$ $}
    
    \State $KVCom \gets \emptyset$
    \State $KVTmp \gets CommittedKV$
    \State $lastTransCommitted = 0$
    \State $AbortSet \gets \emptyset$
    \State $NewCom \gets NULL$
    
    \State $TransArb \gets \{\tuple{P, KV, G,seq_{l}, seq_{s},id,arb}|\tuple{p, KV, G,seq_{l}, seq_{s},id,arb} \in LiveTransactions \land arb = LOCAL\_ID\}$\\
    
    \ForAll{$\tuple{P, KV, G,seq_{cl}, seq_{s},id,arb} \in Transarb$ sorted by $seq_{s}$}
        
        \If{$\forall \tuple{D',arb',seq_{l}', seq_{s}', id', pn', isLast'} \in P, \lnot isLast'$}
            \State Break
        \ElsIf{$(\exists \tuple{D',arb',seq_{l}', seq_{s}', id', pn', isLast'} \in P,isLast') \land |P| \neq pn$}
            \State Break
        \ElsIf{$\exists \tuple{id', seq_{l}'} \in OfflineTransAtServer, id' = id\land seq_{cl}' = seq_{cl} $}
            \State Break
        \EndIf\\
        
        \State $LastTransSeenMid \gets \{\tuple{id',seq'}|\tuple{id',seq'} \in LastTransSeenMid \land id'\neq id\} \cup \{\tuple{id, seq_s}\}$\\
        
        
        \If{\Call{EvaluateGuard}{$G, KVTmp$}}
            \State $KVTmp \gets \{\tuple{k',v'} |\tuple{k',v'} \in KVTmp \land \forall \tuple{k,v} \in KV, k' \neq k\}\cup KV$
            \State $KVCom \gets \{\tuple{k',v'} |\tuple{k',v'} \in KVCom \land \forall \tuple{k,v} \in KV, k' \neq k\}\cup KV$
            \State $lastTransCommitted \gets seq_{s}$ 
        \Else
            \State $newAbort \gets \tuple{seq_{cl}, seq_{s}, id, arb, arbitrationSeqNum}$
            \State $AbortSet \gets AbortSet \cup newAbort$
            \State $arbitrationSeqNum \gets arbitrationSeqNum + 1$
            \State \Call{ProcessAbort}{$newAbort$}
        \EndIf
    \EndFor
    
    \If{$|KVCom| \neq 0$}
        \State $NewCom \gets \tuple{\emptyset, KVCom, lastTransCommitted, arbitrationSeqNum,id}$
        \State \Call{GenerateParts}{$NewCom$}
        \State $arbitrationSeqNum \gets arbitrationSeqNum + 1$
        \ForAll{$compart \in NewCom$}
                \State \Call{ProcessCommitPart}{compart}
        \EndFor
    \EndIf
    
    \If{$|KVCom| \neq 0 \lor |AbortSet| \neq 0$}
        \State $ArbitrationQueue \gets ArbitrationQueue \cup \tuple{NewCom, AbortSet, \emptyset}$
        
        \If{\Call{CompactArbitrationRounds}{$ $}}
            \State $\tuple{NewCom, AbortSet, \emptyset} \gets ArbitrationQueue.peakEnd()$
            \ForAll{$compart \in NewCom$}
                \State \Call{ProcessCommitPart}{compart}
            \EndFor
        \EndIf
    \EndIf    
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}



% Arbitrate From Local
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Arbitrate from local:}\\
Arbitrate on the transactions that were received from the local.
\begin{algorithmic}[1]
\Function{ArbitrateFromLocal}{$Transaction_a$}
    \State $\tuple{Parts, KV, G,seq_l, seq_s,id, arb} \gets Transaction_a$\\
    
    \If{$id \neq LOCAL\_ID$} \Comment{If is arbitrator}
        \State \Return{$\tuple{False, False}$}
    \EndIf\\
    
    \LeftComment{transaction is complete}
    \If{$\forall \tuple{D',arb',seq_{l}', seq_{s}', id', pn', isLast'} \in P, \lnot isLast'$}
        \State \Return{$\tuple{False, False}$}
    \ElsIf{$(\exists \tuple{D',arb',seq_{l}', seq_{s}', id', pn', isLast'} \in P,isLast') \land |P| \neq pn$}
        \State \Return{$\tuple{False, False}$}
    \EndIf\\
    
    \If{$id \neq LOCAL\_ID$}
        \If{$\exists \tuple{id',seq'} \in LastTransSeenMid, id'=id \land seq' > seq_l$}
            \State \Return{$\tuple{False, False}$} \Comment{Already seen this transaction}
        \EndIf
    \EndIf\\
    
    \If{\Call{EvaluateGuard}{$G, CommittedKV$}}        
        \State $NewCom \gets \tuple{\emptyset, KV, seq_s, arbitrationSeqNum,id}$
        \State \Call{GenerateParts}{$NewCom$}
        \State $arbitrationSeqNum \gets arbitrationSeqNum + 1$
        \ForAll{$compart \in NewCom$}
                \State \Call{ProcessCommitPart}{compart}
        \EndFor\\
        
        \State $ArbitrationQueue \gets ArbitrationQueue \cup \tuple{NewCom, \emptyset, \emptyset}$
        \If{\Call{CompactArbitrationRounds}{$ $}}
            \State $\tuple{NewCom, AbortSet, \emptyset} \gets ArbitrationQueue.peakEnd()$
            \ForAll{$compart \in NewCom$}
                \State \Call{ProcessCommitPart}{compart}
            \EndFor
        \EndIf
        
        
         \If{$id = LOCAL\_ID$}
                \State $TransStatus \gets $ \Call{GetTransStatus}{$id,seq_l$}
                \State \Call{ChangeTransStatus}{$TransStatus,committed$}
                \State \Call{DeleteTransStatus}{$id,seq_l$}
        \EndIf
        
        \State \Call{UpdateCommittedKV}{}
        \State \Call{UpdateLiveTransactionsAndStatuses}{}
        \State \Call{UpdateSpeculativeKV}{}    
        \State \Return{$\tuple{True, True}$}        
    \Else
        
        \If{$id = LOCAL\_ID$}
            \State $TransStatus \gets $ \Call{GetTransStatus}{$id,seq_l$}
            \State \Call{ChangeTransStatus}{$TransStatus,aborted$}
            \State \Call{DeleteTransStatus}{$id,seq_l$}
        \Else
            \State $newAbort \gets \tuple{seq_{cl}, seq_{s}, id, arb, arbitrationSeqNum}$
            \State $arbitrationSeqNum \gets arbitrationSeqNum + 1$
            \State \Call{ProcessAbort}{$newAbort$}        
            \State $ArbitrationQueue \gets ArbitrationQueue \cup \tuple{NULL, \{newAbort\}, \emptyset}$
        
            \If{\Call{CompactArbitrationRounds}{$ $}}
                \State $\tuple{NewCom, AbortSet, \emptyset} \gets ArbitrationQueue.peakEnd()$
                \ForAll{$compart \in NewCom$}
                    \State \Call{ProcessCommitPart}{compart}
                \EndFor
            \EndIf
        \EndIf    
    \EndIf
    
    \State \Call{UpdateCommittedKV}{}
    \State \Call{UpdateLiveTransactionsAndStatuses}{}
    \State \Call{UpdateSpeculativeKV}{}    
    \State \Return{$\tuple{True, False}$}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Update Live Transaction and Statuses
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Update Live Transactions And Statuses:}\\
Update the live transactions and the transaction statuses.
\begin{algorithmic}[1]
\Function{UpdateLiveTransactionsAndStatuses}{$ $}
    \ForAll{$\tuple{P, KV, G,seq_l, seq_s,id, arb} \in LiveTransactions$}
        \If{$\exists \tuple{id',seq'} \in LastTransactionArbitrated, id=id' \land seq' > seq_s$}
            \If{$id = LOCAL\_ID$}
                \State $TransStatus \gets $ \Call{GetTransStatus}{$id,seq_l$}
                \State \Call{ChangeTransStatus}{$TransStatus,committed$}
                \State \Call{DeleteTransStatus}{$id,seq_l$}
            \EndIf
        \EndIf
    \EndFor
    \State $LiveTransactions \gets \{\tuple{P, KV, G,seq_l, seq_s,id, arb}| \tuple{P, KV, G,seq_l, seq_s,id, arb} \in LiveTransactions \land \forall \tuple{id',seq'} \in LastTransactionArbitrated, id'\neq id \lor seq_s > seq'\}$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Validate and Update 
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Validate Update:}\\
Validate the block chain and insert into the local block chain.
\begin{algorithmic}[1]
\Function{ValidateUpdate}{$NewSlots_a, updatinglocal_a$}
    \State $\tuple{seq_{oldest}, Dat_{oldest}} \gets$ \Call{MinSlot}{$NewSlots_a$}
    \State $\tuple{seq_{newest}, Dat_{newest}} \gets$ \Call{MaxSlot}{$NewSlots_a$}
    \State $\tuple{seq_{local}, Dat_{local}} \gets$ \Call{MaxSlot}{$LocalSlots$}
    \State $MachinesSeen \gets \{id'|\tuple{id',seq'} \in LastSlot\}$\\
    
    \State \Call{CheckSlotsHmacAndSeq}{$NewSlots_a$}
    \State \Call{CheckHmacChain}{$NewSlots_a$}
    \State \Call{CheckOldSlots}{$NewSlots_a$}
    \State \Call{CheckSize}{$NewSlots_a$}\\
    
    \ForAll{$slot_a \in NewSlots_a$ in order of sequence number}    
        \State $\tuple{seq_{a_1}, \tuple{seq_{a_2},id_a,DE_a,hmac_{a_p},hmac_{a_c}}} \gets slot_a$
        \State \Call{UpdateLastMessage}{$seq_{a_1}, id_a, updatinglocal_a, MachinesSeen$}\\
        
        \ForAll{$de_a \in DE_a$}
            \State \Call{ProccessDatEntry}{$de_a, NewSlots_a, MachinesSeen$}
        \EndFor\\
    
        \State $LocalSlots \gets LocalSlots \cup \{slot_a\}$ \Comment{Add to local Chain}
    \EndFor\\
    
    \If{$seq_{oldest} > (seq_{local} +1) \land MachinesSeen \neq \emptyset$}
        \LeftComment{There was a gap so there should be a complete set of information on each previously seen client}
        \State \Call{Error}{"Missing records for machines"}
    \EndIf\\
    
    \State \Call{DeleteLocalSlots}{ } \Comment{Delete old slots from local}
    
    \State \Call{ArbitrateFromServer}{}
    \State \Call{UpdateCommittedKV}{}
    \State \Call{UpdateLiveTransactionsAndStatuses}{}
    \State \Call{UpdateSpeculativeKV}{}
        
    \State $offlineTransactionAtServer \gets \emptyset$
    \State $hadPartialSendToServer \gets false$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Accept from local 
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Accept from Local:}\\
The local transaction handling accept.
\begin{algorithmic}[1]
\Function{AcceptFromLocal}{$seq_a, transaction_a$}
    \State $arbitrated \gets false$
    \State $committed \gets false$
    \State $ReturnSet \gets \emptyset$\\
        
    \If{$transaction_a \neq NULL$}
        \State $\tuple{arbitrated, committed} \gets $ \Call{ArbitrateFromLocal}{$transaction_a$} 
        \State $\tuple{P, KV, G,seq_l, seq_s,id, arb} \gets transaction_a$
        \If{$seq_s \neq -1$}
            \State $OfflineTransAtServer \gets OfflineTransAtServer \cup \{\tuple{id, seq_l}\}$
        \EndIf
        \State \Call{UpdateCommittedKV}{}
        \State \Call{UpdateLiveTransactionsAndStatuses}{}
        \State \Call{UpdateSpeculativeKV}{}
    \EndIf\\
    
    \State $AllAborts \gets$ \Call{GetAborts}{} \Comment{Get all the aborts} \\
    \State $ReturnSet \gets ReturnSet \cup \{\tuple{seq_l', seq_s', id', arb', seq_{arb}'}|\tuple{seq_l', seq_s', id', arb', seq_{arb}', seq'} \in A \land id'=LOCAL\_ID \land seq_l' > seq_a\}$
    \State $ReturnSet \gets ReturnSet \cup \{p'|p'\in P' \land \tuple{P', KV', seq_t', seq_s',id'} \in LiveCommits \land id'=LOCAL\_ID \land seq_s' > seq_a\}$
    \State \Return{$\tuple{arbitrated, committed,ReturnSet}$}   
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}


% Send to local 
%% \noindent\fbox{%
%% \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Send To Local:}\\
Send transaction to local to be arbitrated on or not.
\begin{algorithmic}[1]
\Function{SendToLocal}{$transaction_a$}
    \State $\tuple{P, KV, G,seq_l, seq_s,id, arb} \gets transaction_a$
    \If{Cannot communicate locally with client $id$}
        \State \Return{$False$}
    \EndIf


    \State $seq_{lastseen} \gets seq'$ such that $\tuple{id',seq'} \in LastArbLocalArbitrated \land id'=id$
    \State $\tuple{arbitrated, committed,ReturnSet} \gets $\Call{AcceptFromLocal}{$seq_{lastseen}, transaction_a$}\\

    \ForAll{$e \in ReturnSet$}
        \If{$e$ is an $abort$}
            \State \Call{ProcessAbort}{$e$}
        \Else
            \State \Call{ProcessCommitPart}{$e$}
        \EndIf
    \EndFor\\
    
    \State \Call{UpdateCommittedKV}{}
    \State \Call{UpdateLiveTransactionsAndStatuses}{}
    \State \Call{UpdateSpeculativeKV}{}\\
    
    \State $TransStatus \gets $ \Call{GetTransStatus}{$id,seq_l$}
    \If{$arbitrated$}
        \If{$committed$}
            \State \Call{ChangeTransStatus}{$TransStatus,committed$}
        \Else
            \State \Call{ChangeTransStatus}{$TransStatus,aborted$}
        \EndIf
    \ElsIf{$\exists \tuple{seq_l', seq_s', id', arb', seq_{arb}'} \in ReturnSet, \tuple{seq_l', seq_s', id', arb', seq_{arb}'}$ is an $abort \land id' = LOCAL\_ID \land seq_l' = seq_l$}
        \State \Call{ChangeTransStatus}{$TransStatus,aborted$}
    \Else
        \State \Call{ChangeTransStatus}{$TransStatus,committed$} 
    \EndIf
    
    \State \Call{DeleteTransStatus}{$id,seq_l$}
    \State \Return{$True$}
\EndFunction
\end{algorithmic}
% %\end{varwidth}% 
% }


\subsection{Client Interfaces}




% Update
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Update}\\
Sync with the server and get all the latest slots.

\algblock[TryCatchFinally]{try}{endtry}
\algcblock[TryCatchFinally]{TryCatchFinally}{finally}{endtry}
\algcblockdefx[TryCatchFinally]{TryCatchFinally}{catch}{endtry}
    [1]{\textbf{catch} #1}
    {\textbf{end try}}

\begin{algorithmic}[1]
\Function{UpdateFromServer}{$ $}
    \State $NewSlots_{decrypt} \gets \emptyset$
    \State $\tuple{seq, Dat} \gets $ \Call{MaxSlot}{$LocalSlots$}\\
    
    \try
        \State $NewSlots \gets$ \Call{GetSlots}{$seq$}\\
        
        \ForAll{$\tuple{seq', EDat'} \in NewSlots$}
            \State $DDat \gets $ \Call{Decrypt}{$EDat'$}
            \State $NewSlots_{decrypt} \gets NewSlots_{decrypted} \cup \tuple{seq',DDat}$
        \EndFor\\
        
        \State \Call{ValidateAndUpdate}{$NewSlots_{decrypt}$}        
        \State \Call{SendToServer}{$Null$}
        \State \Return{$True$}    
    \catch{$Exception$}
        \LeftComment{Do nothing here}
    \endtry
    
    \State \Return{$False$}
    
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Update from local
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Update from local}\\
Get the latest from a client through local communication.
\begin{algorithmic}[1]
\Function{UpdateFromLocal}{$id_a$}
    \If{Cannot communicate locally with client $id$}
        \State \Return{}
    \EndIf
    
    \State $seq_{lastseen} \gets seq'$ such that $\tuple{id',seq'} \in LastArbLocalArbitrated \land id'=id_a$
    \State $\tuple{arbitrated, committed,ReturnSet} \gets $\Call{AcceptFromLocal}{$seq_{lastseen}, transaction_a$}\\

    \ForAll{$e \in ReturnSet$}
        \If{$e$ is an $abort$}
            \State \Call{ProcessAbort}{$e$}
        \Else
            \State \Call{ProcessCommitPart}{$e$}
        \EndIf
    \EndFor\\
    
    \State \Call{UpdateCommittedKV}{}
    \State \Call{UpdateLiveTransactionsAndStatuses}{}
    \State \Call{UpdateSpeculativeKV}{}\\

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


%Create New Key 
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create New Key:}\\
Creates a new key and specifies which machine ID is the arbitrator. If there is already a new key entry in the block chain for this key name then do not insert into the chain, another client got there first.
\begin{algorithmic}[1]
\Function{Transaction Commit}{$k_a, id_a$}
    \State $success \gets false$\\
    \While{$\lnot success$}
        \If{$\exists \tuple{k',id'} \in Arbitrator, k' = k_a$}
            \State \Return{$false$} \Comment{Key already created}
        \EndIf\\
        
        \State $success \gets$ \Call{SendToServer}{$\tuple{k_a, id_a}$}
    \EndWhile
    
    \State \Return{$true$} \Comment{If got here then insertion was correct}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Transaction Start
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{ Transaction Start:}\\
Starts a transaction.
\begin{algorithmic}[1]
\Function{TransactionStart}{$ $}
    \State $newPendingTransaction \gets \tuple{\emptyset, \emptyset, LOCAL\_ID,clntTransactionNum}$
    \State $clntTransactionNum \gets clntTransactionNum + 1$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% 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{KV, G,id, seq_{clientLocal}} \gets newPendingTransaction$
    \State $KV \gets \{\tuple{k',v'}| \tuple{k,v} \in KV, k \neq k'\}\cup \{\tuple{k,v}\}$ 
    \State $ArbSet \gets \{arb| \exists \tuple{k',v'} \in (KV \cup G), arb=$\Call{GetArbitrator}{$k'$}$\}$
    \If{$|ArbSet| > 1$}
        \State \Call{Error}{"Multiple arbitrators for key values in transaction."}
    \EndIf
    \State $newPendingTransaction \gets \tuple{KV, G,id, seq_{clientLocal}}$
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Transaction Commit
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{ Transaction Commit:}\\
Commits a transaction.

\algblock[TryCatchFinally]{try}{endtry}
\algcblock[TryCatchFinally]{TryCatchFinally}{finally}{endtry}
\algcblockdefx[TryCatchFinally]{TryCatchFinally}{catch}{endtry}
    [1]{\textbf{catch} #1}
    {\textbf{end try}}
\begin{algorithmic}[1]
\Function{TransactionCommit}{$ $}
    \State $\tuple{KV, G,id, seq_{clientLocal}} \gets newPendingTransaction$
    
    \If{$|KV| = 0$} \Comment{Nothing To Update}
        \State $TransStatus \gets \tuple{noeffect}$ 
        \State \Return{$TransStatus$}
    \EndIf
    \State $transArb \gets $\Call{GetArbitratorKV}{$KV$}
    
    \If{$transArb = LOCAL\_ID$}
        \State \Call{ArbitrateFromLocal}{$\tuple{\emptyset, KV, G,seq_{clientLocal},-1,LOCAL\_ID,transArb}$}
        \State \Call{UpdateCommittedKV}{}
        \State \Call{UpdateLiveTransactionsAndStatuses}{}
        \State \Call{UpdateSpeculativeKV}{}    
    \Else
        \State $TransStatus \gets \tuple{pending}$ 
        \State \Call{SetTransStatus}{$LOCAL\_ID, seq_{clientLocal}, TransStatus$}
        
        \State $newTrans \gets \tuple{\emptyset, KV, G,seq_{clientLocal},-1,LOCAL\_ID,transArb}$
        \State \Call{GenerateParts}{newTrans}        
        \State $PendingTransactionQueue.push(\tuple{newTrans, \emptyset, false}$    
    \EndIf
    
    \State $newPendingTransaction \gets \tuple{\emptyset, \emptyset, LOCAL\_ID,clntTransactionNum}$
    \State $clntTransactionNum \gets clntTransactionNum + 1$

    \try
        \State \Call{SendToServer}{$NULL$}
    \catch{$Exception$}   
        \ForAll{$transaction \in PendingTransactionQueue$}
            \If{\Call{SendToLocal}{$transaction$}}
                \State $PendingTransactionQueue.remove(transaction)$
            \EndIf
        \EndFor
    \endtry
    
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Get KV Pair Committed
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get KV Pair Committed:}\\
Get the value for the key which have been committed.
\begin{algorithmic}[1]
\Function{GetCommit}{$k_a$}
    \If{$\exists \tuple{k,v} \in CommittedKV \land k \neq k_a$}
        \State \Return{$NULL$}
    \EndIf
    \State \Return{$v$ such that $\tuple{k,v} \in CommittedKV \land k = k_a$}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Get KV Pair Committed Atomic
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get KV Pair Committed Atomic:}\\
Get the value for the key which have been committed and add it to the guard condition of the current pending transaction.
\begin{algorithmic}[1]
\Function{GetCommitAtomic}{$k_a$}
    \State $val \gets NULL$
    \If{$\exists \tuple{k,v} \in CommittedKV \land k = k_a$}
        \State $val \gets v$ such that $\tuple{k,v} \in CommittedKV \land k = k_a$
    \EndIf\\
    
    \State $\tuple{KV, G, seq_{clientLocal}} \gets newPendingTransaction$
    \State $G \gets G \cup \{\tuple{k_a,val}\}$
    \State $ArbSet \gets \{arb| \exists \tuple{k',v'} \in (KV \cup G), arb=$\Call{GetArbitrator}{$k'$}$\}$
    \If{$|ArbSet| > 1$}
        \State \Call{Error}{"Multiple arbitrators for key values in transaction."}
    \EndIf
    \State $newPendingTransaction \gets \tuple{KV, G, seq_{clientLocal}}$
    \State \Return{$val$}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Get KV Pair Speculative 
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get KV Pair Speculative:}\\
Get the value for the key which have been speculated on.
\begin{algorithmic}[1]
\Function{GetSpeculated}{$k_a$}
    \If{$\exists \tuple{k,v} \in SpeculatedKV \land k \neq k_a$}
        \State \Return{$NULL$}
    \EndIf
    \State \Return{$v$ such that $\tuple{k,v} \in SpeculatedKV \land k = k_a$}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

% Get KV Pair Speculative Atomic
%\noindent\fbox{%
%\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Get KV Pair Speculative Atomic:}\\
Get the value for the key which have been speculative and add it to the guard condition of the current pending transaction.
\begin{algorithmic}[1]
\Function{GetSpeculatedAtomic}{$k_a$}
    \State $val \gets NULL$
    \If{$\exists \tuple{k,v} \in SpeculatedKV \land k = k_a$}
        \State $val \gets v$ such that $\tuple{k,v} \in SpeculatedKV \land k = k_a$
    \EndIf\\
    
    \State $\tuple{KV, G, id,seq_{clientLocal}} \gets newPendingTransaction$
    \State $G \gets G \cup \{\tuple{k_a,val}\}$
    \State $ArbSet \gets \{arb| \exists \tuple{k',v'} \in (KV \cup G), arb=$\Call{GetArbitrator}{$k'$}$\}$
    \If{$|ArbSet| > 1$}
        \State \Call{Error}{"Multiple arbitrators for key values in transaction."}
    \EndIf
    \State $newPendingTransaction \gets \tuple{KV, G, seq_{clientLocal}}$
    \State \Return{$val$}
\EndFunction
\end{algorithmic}
%\end{varwidth}% 
%}

\end{document}
