\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{Approach}

\subsection{Keys}

Each device has: user id + password

Server login is:
hash1(user id), hash1(password)

Symmetric Crypto keys is:
hash2(user id | password)

Server has finite length queue of entries + max\_entry\_identifier +
server login key

\subsection{Entry layout}
Each entry has:
\begin{enumerate}
\item Sequence identifier
\item Random IV (if needed by crypto algorithm)
\item Encrypted payload
\end{enumerate}

Payload has:
\begin{enumerate}
\item Sequence identifier
\item Machine id (most probably something like a 64-bit random number 
that is self-generated by client)
\item HMAC of previous slot
\item Data entries
\item HMAC of current slot
\end{enumerate}

A data entry can be one of these:
\begin{enumerate}
    \item A transaction:
        \begin{itemize}
            \item Contains a sequence number, a set of key value pair updates and a guard condition that can be evaluated.
            \item Must have the same arbitrator for all its key value pair updates and reads within the guard condition
        \end{itemize}
    
    \item A Commit
        \newline{Commits a transaction into the block chain.  Until a transaction is committed, no client can be sure if that transaction's key value updates will be used to update the state of the system.  Once an arbitrator commits a transaction then that transaction becomes a permanent state change in the system.  Transactions should be committed and aborted in order of their sequence numbers.}
    
    \item An Abort
        \newline{An abort is used to show that a transactions key value update should not be used in the state change of the system.  This occurs when the guard of a transaction evaluates to false meaning that the conditions under-which this transaction should be committed no longer exists in the system (another transaction could have been committed first that would have changed the system in a way that makes the current transaction invalid).}
    
    \item New Key:
        \newline{This creates a new key and assignes an arbitrator to that key.  Only the first new key message for a given key is valid.  Once a new key message is inserted into the block chain it is never removed and no other new key entries for the same key name can be inserted into the block chain.}
        
    \item Slot sequence entry: Machine id + last message identifier 
        \newline {The purpose of this is to keep the record of the last slot from a certain client if a client's update has to expunge that other client's last entry from the queue. This is kept in the slot until the entry owner inserts a newer update into the queue.}

    \item Queue state entry: Includes queue size 
        \newline {The purpose of this is for the client to tell if the server lies about the number of slots in the queue, e.g. if there are 2 queue state entry in the queue, e.g. 50 and 70, the client knows that when it sees 50, it should expect at most 50 slots in the queue and after it sees 70, it should expect 50 slots before that queue state entry slot 50 and at most 70 slots. The queue state entry slot 70 is counted as slot number 51 in the queue.}

    \item Collision resolution entry: message identifier + machine id of a collision winner
        \newline {The purpose of this is to keep keep track of the winner of all the collisions until all clients have seen the particular entry.}
\end{enumerate}

\subsection{Live status}

Live status of entries:
\begin{enumerate}
    \item Transaction is live if it has not been committed or aborted yet.
    
    \item Abort is live until the machine ID that created the transaction that is being aborted inserts into the block chain a message with a sequence number greater than the abort (that client sees the abort).
        
    \item Commit is dead if for all key value updates in the commit there is a commit with the same key value update that is newer (larger sequence number).  The committing client (arbitrator) will see those newer commits since it is the one that generates them.
    
    \item New Key messages are always kept alive.  Keys can not be deleted.  Deleted keys will cause arbitration to fail if a key is deleted then reassigned to a new client device for arbitration.
    
    \item Slot sequence number (of either a message version data or user-level data) is dead if there is a newer slot from the same machine.

    \item Queue state entry is dead if there is a newer queue state entry.
    {In the case of queue state entries 50 and 70, this means that queue state entry 50 is dead and 70 is live. However, not until the number of slots reaches 70 that queue state entry 50 will be expunged from the queue.  Further all entries before the 50 entry will also not be expunged until the queue size has reached 70}

    \item Collision resolution entry is dead if this entry has been seen by all clients after a collision happens.
\end{enumerate}

When data is at the end of the queue ready to expunge, if:
\begin{enumerate}
    \item If any entry is not dead it must be reinserted into the queue.

    \item If the slot sequence number is not dead, then a message sequence entry must be inserted.
\end{enumerate}

\paragraph{Validation procedure on client:}
\begin{enumerate}
    \item Decrypt each new slot in order.
    \item For each slot:
        (a) check its HMAC, and
        (b) check that the previous entry HMAC field matches the previous entry (in case of a gap do not check for slots on gap margins).
    \item That no slots are slots we have seen before (server trying to pass old slots).    
    
    \item For all other machines, check that the latest sequence number is at least as large (never goes backwards).
    
    \item That the queue has a current queue state entry.
    
    \item That the number of entries received is consistent with the size specified in the queue state entry and/or the queue is growing in size.
\end{enumerate}

\subsection{Resizing Queue}
Client can make a request to resize the queue. This is done as a write that combines:
  (a) a slot with the message, and (b) a request to the server. The queue can only be expanded, never contracted; attempting to decrease the size of the queue will cause future clients to throw an error.


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

\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 requese.\\
\begin{algorithmic}[1]
\Function{GetSlot}{$s_g$}
\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'$}
\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{\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{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}

$PendingTransQueue$ = Queue of pending transactions that need to be pushed to the block chain, $\tuple{PendingTrans}$\\
$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.\\
$CommittedKV$ = set of committed key value pairs (initially $\emptyset$).\\
$SpeculatedKV$ = set of speculated key value pairs (initially $\emptyset$).

\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$ \\


% 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{id, seq}\in LastSlo \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}% 
}

% 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$}
    \State $\tuple{k,v} \gets \tuple{k',v'}$ such that $\tuple{k',v'} \in KV$
    \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 numberl 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 committed in order of there insertion, seeing a transaction that is committed and has a larger sequence number than the transaction in question means that the transaction in question was committed 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 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}% 
}


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

% Create New Key
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create New Key:}\\
Generate a new key data entry.\\
\begin{algorithmic}[1]
\Function{CreateNewKey}{$k_a, id_a$}
    \State \Return{$\tuple{k_a,id_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 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}$}
            \If{$hmac_{a_p} \neq hmac_{last_c}$}
                \State \Call{Error}{"Invalid previous HMAC."}
            \EndIf
        \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\\
    
    \LeftComment{Check if slots have the same sequence number but different data entries}
    \ForAll{$\tuple{seq, Dat} \in Slots_a$}
        \If{$\exists \tuple{seq', Dat'} \in (LocalSlots \cup Slots_a), seq'=seq \land Dat' \neq Dat$}
            \State \Call{Error}{"Slot sequence number match but data does not"}
        \EndIf
    \EndFor
    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Get All Queue States with Sequence numbers
% \noindent\fbox{%
% \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
% \textbf{Get All Queue States with Sequence numbers:}\\
% Gets all the queue states with the sequence number of the slot that the queue state was inside.
% \begin{algorithmic}[1]
% \Function{GetQStateWithSeq}{$Slots_a$}
%     \State $QSet \gets \emptyset$\\
    
%     \ForAll{$\tuple{seq_1', \tuple{seq_2',id',DE',hmac_p', hmac_c'}} \in Slots_a$}
%         \ForAll{$de' \in DE'$}
%             \If{$de'$ is a  $qstate$}
%                 \State $QSet \gets QSet \cup \{\tuple{seq_1', de'}\}$
%             \EndIf
%         \EndFor
%     \EndFor\\
    
%     \State \Return{$QSet$}
% \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:}\\
Gets all the queue states from the slots that were passed in.\\
\begin{algorithmic}[1]
\Function{GetQState}{$Slots_a$}
    \State $QSet \gets \emptyset$\\
    
    \ForAll{$\tuple{seq_1', \tuple{seq_2',id',DE',hmac_p', hmac_c'}} \in Slots_a$}
        \ForAll{$de' \in DE'$}
            \If{$de'$ is a  $qstate$}
                \State $QSet \gets QSet \cup \{de'\}$
            \EndIf
        \EndFor
    \EndFor\\
    
    \State \Return{$QSet$}
\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}% 
}


% % Initialize the expected size of the block chain
% \noindent\fbox{%
% \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
% \textbf{Initialize the expected size of the block chain:}\\
% Initialize the expected size of the block chain based on the size at the server.\\
% \begin{algorithmic}[1]
% \Function{InitExpSize}{$seq_a$}
%     \State $startingsize \gets 0$\\

%     \If{$seq_a < max\_size$} \Comment{Check whether saves slots are full on server}
%         \State $startingsize \gets seq_a$
%     \Else
%         \State $startingsize \gets max\_size$
%     \EndIf\\
    
%     \State \Return{$startingsize$}
% \EndFunction
% \end{algorithmic}
% \end{varwidth}% 
% }

% % Update the expected size of the block chain
% \noindent\fbox{%
% \begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
% \textbf{Update the expected size of the block chain:}\\
% Update the expected size of the block chain.\\
% \begin{algorithmic}[1]
% \Function{UpdateExpSize}{$size_a$}
%     \State $size_a \gets size_a + 1$\\
    
%     \If{$size_a > max\_size$}\Comment{Expected size $\leq max\_size$}
%         \State $ssize_a \gets max_\_size$
%     \EndIf\\
    
%     \State \Return{$size_a$}
% \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, LstSlt_a, updateinglocal_a$}
    \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{$\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
    \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 \Return{$LstSlt_a \setminus \{\tuple{id, seq} | \tuple{id, seq} \in LstSlt_a, id=id_a\}$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Process Commit Data Entry
\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{ProcessCommit}{$commit_a$}
    \State $\tuple{seq_{a_{trans}},KV_a} \gets commit_a$
    \State $DKV \gets \{\tuple{k,v}| \tuple{k,v} \in CommittedKV \land \tuple{k',v'}\in KV_a \land k'=k\}$
    \State $CommittedKV \gets (CommittedKV \setminus DKV) \cup KV_a$
\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 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 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 $\tuple{seq_a, k_a, id_a} \gets newkey_a$
    \State $Arbitrator \gets Arbitrator \cup \{\tuple{k_a,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,LstSlt_a$}
    \If{$datentry_a$ is a $commit$}
        \State \Call{ProcessCommit}{$dataentry_a$}
        
    \ElsIf{$datentry_a$ is a $abort$}
        \LeftComment{Do Nothing in this case}
        
    \ElsIf{$datentry_a$ is a $trans$}
        \LeftComment{Do Nothing in this case}
    
    \ElsIf{$datentry_a$ is a $lastmsg$}
        \State $\tuple{seq_a, id_a} \gets dataentry_a$
        \State $LstSlt_a \gets$ \Call{UpdateLastMessage}{$seq_a, id_a, LstSlt_a, false$}
    
    \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}% 
}


% Delete Local Slots
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Delete Local Slots:}\\
Deletes local slots that are deleted at the server.  This keeps the size of the local block chain bounded.\\
\begin{algorithmic}[1]
\Function{DeleteLocalSlots}{$ $}
    \State $\tuple{seq_{max}, Dat_{max}} \gets $ \Call{MaxSlot}{$LocalSlots$}
    \State $seq_{min} \gets seq_{max} - max\_size$ \Comment{Min sequence number we should keep}
    \State $LSDelete \gets \emptyset$
        
    \If{$|LocalSlots| \leq max\_size$}
        \State \Return{} \Comment{Nothing to delete}
    \EndIf\\
    
    \State $LSDelete \gets \{\tuple{seq', Dat'}|\tuple{seq', Dat'} \in LocalSlots, seq' > seq_{min}\}$
    \State $LocalSlots \gets LocalSlots \setminus LSDelete$    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Create Speculative KV
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Create Speculative KV:}\\
Speculates on what the most recent key value pairs will be based on the latest committed key value pairs and the uncommitted transactions.\\
\begin{algorithmic}[1]
\Function{SpeculateKV}{$ $}
    \State $AllTrans \gets$ \Call{GetTrans}{}
    \State $LiveTrans \gets \{t| t\in AllTrans, $\Call{CheckTransLive}{$t$}$\}$
    \State $CurrKV \gets CommittedKV$
    \State $DKV \gets \emptyset$

    \ForAll{$\tuple{seq_t, id_t, KV_t, Guard_t} \in LiveTrans$ ordered by $seq'$} 
        \If{\Call{EvaluateGuard}{$Guard_t, CurrKV$}}
            \State $DKV \gets \{\tuple{k,v}| \tuple{k,v} \in CurrKV \land \tuple{k',v'}\in KV_t \land k'=k\}$
            \State $CurrKV \gets (CurrKV \setminus DKV) \cup KV_t$
        \EndIf
    \EndFor
    
    \State \Return{$CurrKV$}
\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 $LastSlotTmp \gets LastSlot$\\
    %\State $currsize \gets $\Call{InitExpSize}{$seq_{oldest}$}\\
    
    \State \Call{CheckSlotsHmacAndSeq}{$NewSlots_a$} \Comment{Check all the HMACs}
    \State \Call{CheckHmacChain}{$NewSlots_a$} \Comment{Check HMAC Chain} 
    \State \Call{CheckOldSlots}{$NewSlots_a$} \Comment{Check if new slots are actually old slots} 
    \State \Call{CheckSize}{$NewSlots_a$} \Comment{Check if the size is correct}\\
    
    \ForAll{$slot_a \in NewSlots_a$ in order of sequence number}
        \If{$slot_a \in LocalSlots$} \Comment{Client already has this slot}
            \State $NewSlots_a \gets NewSlots_a \setminus \{slot_a\}$
            \State Continue
        \EndIf\\
    
        \State $\tuple{seq_{a_1}, \tuple{seq_{a_2},id_a,DE_a,hmac_{a_p},hmac_{a_c}}} \gets slot_a$
        \State $LstSlt_a \gets$ \Call{UpdateLastMessage}{$seq_{a_1}, id_a, LstSlt_a, updatinglocal_a$}\\
        
        \ForAll{$de_a \in DE_a$} \Comment{Process each data entry}
            \State $LstSlt_a \gets $ \Call{ProccessDatEntry}{$de_a, NewSlots_a,LstSlt_a$}
        \EndFor\\
    
        %\State $currsize \gets $ \Call{UpdateExpSize}{$currsize$}\\
        \State $LocalSlots \gets LocalSlots \cup \{slot_a\}$ \Comment{Add to local Chain}
    \EndFor\\
    
    \If{$seq_{oldest} > (seq_{local} +1) \land LastSlotTmp \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 $SpeculatedKV \gets $\Call{SpeculateKV}{ } \Comment{Speculate on what will be latest KV set}
    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Decrypt Validate Insert Slots
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Decrypt Validate Insert Slots:}\\
Decrypts slots, validates (checks for malicious activity) slots and inserts the slots into the local block chain.\\
\begin{algorithmic}[1]
\Function{DecryptValidateInsert}{$NewSlots_a, updatinglocal_a$}
    \State $DecryptedSlots \gets \emptyset$
    \State $DDat \gets NULL$\\
    
    \ForAll{$\tuple{seq', EDat'} \in NewSlots_a$}
        \State $DDat \gets $ \Call{Decrypt}{$EDat'$}
        \State $DecryptedSlots \gets DecryptedSlots \cup \tuple{seq',DDat}$
    \EndFor\\
    \State \Call{ValidateUpdate}{$DecryptedSlots, updatinglocal_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{$\{\}$}\\
    \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 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}% 
}


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



% 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{GetArbitratorKV}{$KV_t$} $\neq LOCAL\_ID$}
            \State Continue \Comment{Client not arbitrator for this transaction}
        \EndIf\\
    
        \If{$\lnot$\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'=k\}$
            \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'=k\}$
            \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$}   
        \State $DE \gets$ \Call{RejectedMessages}{$DE$}
    \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$}\\
    
    \LeftComment{Insert the slots into the local bloakc chain}
    \State \Call{DecryptValidateInsert}{$newslots, true$}\\
    
    \State \Return{$transinserted \land success$} \Comment{Return if  succeeded or not}
    
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}


% Try Insert New Key
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Try Insert New Key:}\\
Try to insert a new key into the block chain. Does resizing, rescues and insertion of other data entry types as needed. \\
\begin{algorithmic}[1]
\Function{TryInsertNewKey}{$k_a, id_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 $newkey \gets$ \Call{CreateNewKey}{$k_a, id_a$}
    \State $newkeyinserted \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$}   
        \State $DE \gets$ \Call{RejectedMessages}{$DE$}
    \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{TryInsertNewKey}{$k_a, id_a, true$}}
    \EndIf\\
    
    \State $DE \gets $\Call{Arbitrate}{$DE$}\\
    
    \If{\Call{DEHasSpace}{$DE, newkey$}} \Comment{new key fits}
        \State $DE \gets DE \cup newkey$
        \State $newkeyinserted \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$}\\
    
    \LeftComment{Insert the slots into the local block chain}
    \State \Call{DecryptValidateInsert}{$newslots, true$}\\
    
    \State \Return{$newkeyinserted \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}% 
}

% 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 while speculating.\\
\begin{algorithmic}[1]
\Function{GetValueSpeculate}{$k_a$}
    %\State $\tuple{k,v} \gets \tuple{k,v}$ \textit{such that} $\tuple{k,v} \in SpeculatedKV \land k = k_a$
    
    \State $\tuple{k,v} \gets \tuple{k,v}$ \textit{such that} $\tuple{k,v} \in SpeculatedKV \land k = k_a$
\State \Return{$v$}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}

% Update
\noindent\fbox{%
\begin{varwidth}{\dimexpr\linewidth-2\fboxsep-2\fboxrule\relax}
\textbf{Update}\\
Sync with the server and get all the latest slots.\\
\begin{algorithmic}[1]
\Function{Update}{$ $}
    \State $\tuple{seq, Dat} \gets $ \Call{MaxSlot}{$LocalSlots$}
    \State $NewSlots \gets$ \Call{GetSlots}{$seq$}
    \State \Call{DecryptValidateInsert}{$NewSlots, false$}
\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{GetValueCommit}{$k_a$}
    \State $\tuple{k,v} \gets \tuple{k,v}$ \textit{such that} $\tuple{k,v} \in Committed \land k = k_a$
    \State \Return{$v$}
\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}$
    \State $PendingTrans \gets NULL$
\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 $DKV \gets \emptyset$
    \State $pt \gets NULL$\\
    
    \State $PendingTransQueue.$\Call{push}{$PendingTrans$}\\
        
    \While{\Call{HasConnectionToServer}{ } $\land PendingTransQueue \neq \emptyset$}
        \State $pt \gets PendingTransQueue.$\Call{peak}{ }\\
    
        \If{\Call{TryInsertTransaction}{$pt, false$}}
            \State $PendingTransQueue.$\Call{pop}{ }
        \EndIf
    \EndWhile\\    
    
    \LeftComment{Go Through local pending transactions and speculate}
    \ForAll{$\tuple{KV, Guard} \in PendingTransQueue$}
        \If{\Call{EvaluateGuard}{$Guard, SpeculatedKV$}}
            \State $DKV \gets \{\tuple{k,v}| \tuple{k,v} \in SpeculatedKV \land \tuple{k',v'}\in KV \land k'=k\}$
            \State $SpeculatedKV \gets (SpeculatedKV \setminus DKV) \cup KV$
        \EndIf
    \EndFor
    
\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{TryInsertNewKey}{$k_a, id_a, false$}
    \EndWhile
    
    \State \Return{$true$} \Comment{If got here then insertion was correct}
\EndFunction
\end{algorithmic}
\end{varwidth}% 
}


\end{document}
