% This is based on the LLNCS.DEM the demonstration file of % the LaTeX macro
% package from Springer-Verlag % for Lecture Notes in Computer Science, version
% 2.4 for LaTeX2e as of 16. April 2010
%
% See http://www.springer.com/computer/lncs/lncs+authors?SGWID=0-40209-0-0-0
% for the full guidelines.
\documentclass{llncs}

 \addtolength{\oddsidemargin}{-.875in}
 \addtolength{\evensidemargin}{-.875in}
 \addtolength{\textwidth}{1.75in}

 \addtolength{\topmargin}{-.875in}
 \addtolength{\textheight}{1.75in}

\usepackage{graphicx}
\graphicspath{ {./assets/} }

\usepackage{enumitem}
\setlist[enumerate]{itemsep=2mm}

\usepackage{dirtytalk}
\usepackage{minted}
%\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{amsfonts}
\usepackage{extarrows}
\usepackage{pdflscape}
\usepackage[pass]{geometry}

%
% Tables
% --------
\usepackage[table]{xcolor}
\usepackage{hhline}
\usepackage{booktabs} % much better tables
\usepackage{multirow} % allows to fuse rows
\usepackage{array}    % manipulate array
\usepackage{tabularx} % better tables

% Define new tabularx column types:
%  - R: stretched right aligned
%  - C: stretched centered
%  - N: left aligned, specified space
\newcolumntype{R}{>{\raggedleft\arraybackslash}X}
\newcolumntype{C}{>{\centering\arraybackslash}X}
\newcolumntype{N}[1]{>{\raggedleft\arraybackslash}p{#1}}
\newcolumntype{S}{>{\hsize=.5\hsize}C}

% Set row height multiplier to provide more breathing space
\renewcommand{\arraystretch}{1.5}

\usepackage[backend=biber]{biblatex}
\addbibresource{bibliography.bib}

\pagestyle{plain}
\setcounter{page}{1}
\pagenumbering{arabic}

%\usepackage{pgfplots}
%\pgfplotsset{width=6cm}
\usepackage{float}
\usepackage[caption = false]{subfig}

\newcommand{\BTX}{\texttt{BTX}}
\newcommand{\XTX}{\texttt{XTX}}

\newcommand{\Enc}{\textsf{Enc}}
\newcommand{\EncGen}{\textsf{EncGen}}
\newcommand{\EncSign}{\textsf{EncSign}}
\newcommand{\EncVer}{\textsf{EncVrfy}}

\newcommand{\DecSig}{\textsf{DecSig}}
\newcommand{\KeyGen}{\textsf{Gen}}
\newcommand{\Sign}{\textsf{Sign}}
\newcommand{\Verify}{\textsf{Vrfy}}
\newcommand{\Rec}{\textsf{Rec}}
\newcommand{\RecKey}{\textsf{RecKey}}
\newcommand{\hatsigma}{\hat{\sigma}}

\newcommand{\DLGen}{\textsf{DLGen}}
\newcommand{\DLProve}{\textsf{DLProve}}
\newcommand{\DLVrfy}{\textsf{DLVrfy}}

\newcommand{\InitTx}{\textsf{InitTx}}
\newcommand{\SignTx}{\textsf{SignTx}}
\newcommand{\VrfyTx}{\textsf{VrfyTx}}
\newcommand{\PubTx}{\textsf{PubTx}}
\newcommand{\WatchTx}{\textsf{WatchTx}}
\newcommand{\RecSig}{\textsf{RecSig}}

\newcommand{\skSign}{sk_S}
\newcommand{\pkSign}{pk_S}
\newcommand{\kSign}{(\skSign,\pkSign)}
\newcommand{\skEnc}{sk_E}
\newcommand{\pkEnc}{pk_E}
\newcommand{\kEnc}{(\skEnc, \pkEnc)}
\newcommand{\rec}{\delta}

\newcommand{\bin}{\{0,1\}}

\newcommand{\GG}{\mathbb{G}}
\newcommand{\HH}{\mathbb{H}}

\begin{document}

\title{Bitcoin--Monero Cross-chain Atomic Swap}
\author{Jo\"el Gugger}

\authorrunning{Jo\"el Gugger et al.}
\tocauthor{Jo\"el Gugger}
\institute{\email{h4sh3d@protonmail.com}}

\maketitle

\begin{abstract}
    In blockchains where hashed timelock contracts are possible atomic swaps are already deployed, but when one of the blockchains doesn't have this capability it becomes a challenge. This protocol describes how to achieve atomic swaps between Bitcoin and Monero with two transactions per chain without trusting any central authority, servers, nor the other swap participant.
    We propose a swap between two participants, one holding bitcoin and the other monero, in which when both follow the protocol their funds are not at risk at any moment. The protocol does not require timelocks on the Monero side nor script capabilities but does require two proofs of knowledge of equal discrete logarithm across  the \texttt{edward25519} and the \texttt{secp256k1} groups and \texttt{ECDSA} one-time VES.
    \keywords{Blockchain, Atomic Swap, Cross-Chain Transactions, Bitcoin, Monero}
\end{abstract}

\section{Introduction}
We describe a protocol for an on-chain atomic swap between Monero and Bitcoin, but the protocol can be generalized for any cryptocurrency that fulfills the same requirements as Monero to any other cryptocurrency that fulfills the same requirements as Bitcoin. For an exhaustive list of prerequisites, see chapter \ref{prerequisites}.

Participants send funds into a specific address generated during the process (the lock) on each chain (cross-chain) where each party can take control of the funds on the other chain (swap) atomically (i.e. claiming of funds on either chain is mutually exclusive from the ability to claim funds from the other chain.)

During this process participants do not expose their funds if they follow the protocol accordingly, meaning that the swap is trustless and does not require any sort of collateral, allowing two strangers to trade without risks nor the help of a third-party.

\section{Scenario}
We describe the participants and their incentives. Alice, who owns monero (XMR), and Bob, who owns bitcoin (BTC), want to swap funds. We assume that they already have negotiated the price in advance (i.e. amount of bitcoin for amount of monero to swap.) This negotiation can also be integrated into the protocol, for example by swap services who provide a price to their customers.

Both participants wish to only have two possible execution paths (which are mutually exclusive to each other) when executing the protocol: (1) the protocol succeeds and Alice gets bitcoin, Bob gets monero, or (2) the protocol fails and both keep their original funds minus the minimum transaction fees possible.

\subsection{Successful swap}
If both participants follow the protocol there will be four transactions broadcast in total---only three if the Monero are not moved directly after completion, which is not a problem---, two on the Bitcoin blockchain and two on the Monero blockchain. The first ones on each chain lock the funds and make them ready for the trade on each chain. The second ones unlock the funds for one participant only and give knowledge to the other participant who takes control of the output on the other chain.

This is the optimal execution of the protocol, requiring no timelocks, the minimum number of transactions and only locking funds for the minimum confirmation on each chain depending on the level of security expected by each participant, i.e. how many confirmations each expects for the funding transaction to be considered final and continue to the following step of the protocol.

\subsection{Swap correctly aborted}
When locking the bitcoin, after a timelock, Alice or Bob can start the process of refunding the locked funds. At that moment the monero might not be locked yet. If no monero are locked, the refund process will just refund the bitcoin; otherwise Alice will learn enough information to refund her monero too.

When the refund transaction is broadcast Bob must spend the refund before some timelock, otherwise he might end up loosing his bitcoin without getting any monero.  We can describe this as an interactive protocol from Bob's perspective, i.e. Bob cannot go offline -- he must react to such a situation during the swap. Alice, on the other hand, can remain offline.

\subsection{Worst case scenario}
If the swap is cancelled with the refund process and Bob does not spend his refund before the timelock, Alice can claim the refund without revealing the knowledge needed for Bob to claim on the other chain. Thus one participant, Bob, ends up disadvantaged and three Bitcoin transactions are needed instead of two.

\subsubsection{Rationale}
\label{worstCaseRationale}
This choice is made to avoid the following case: if the monero are locked, Alice will be able to refund them if and only if Bob refunds his bitcoin first. We need an incentive mechanism to force Bob to spend his refund to prevent a deadlock in the refund process or compensate Alice if Bob does not follow the protocol correctly.

Otherwise Bob, with all the information already learned, can go offline and move his bitcoin a year after the swap, forcing Alice to consistently monitor the chain until she sees Bob's transaction and learns the last piece of knowledge she needs to unlock her monero.

\section{Prerequisites}
\label{prerequisites}
As previously described, conditional execution must be possible in order to achieve a swap with atomicity. Bitcoin has a simple stack-based script language that allows for conditional execution and timelocks. On the other hand, at the moment, Monero's privacy oriented RingCT design provides only signatures to unlock UTXOs. Control of UTXOs is only related to who controls the associated private keys. The challenge is then to move control of funds only with knowledge of some private keys.

In this chapter we discuss all the required pieces needed on both chains and off-chain to achieve an atomic swap under the previously exposed scenario.

\subsection{Monero}
Monero does not require any particular on-chain primitives (hashlocks, timelocks), all building blocks are off-chain primitives. Thus we need to provide proofs of the correct initialization of the protocol such as described in chapter \ref{eqDiscreteLog}: those proofs will ensure the swap atomicity for each participant.

\subsubsection{Secret shares,}
to enable a basic two-path execution in Monero. The Monero private spend key is split into two secret shares $k^s_a$ and $k^s_b$. Participants will not use any multi-signature protocol; instead, the private spend key shares are distributed during initialization of the swap process where one participant will gain knowledge of the full key $k^s \equiv k^s_a + k^s_b \pmod l$ at the end of the protocol execution, either for a completed swap or for an aborted swap.

\subsection{Bitcoin}
\label{bitcoinPrerequisites}
The bitcoin transactions in this protocol require the fix for transaction malleability provided by the \texttt{SegWit} upgrade.  This allows us to chain transactions without necessarily broadcasting them. This protocol is only compatible with cryptocurrencies which use a bitcoin style \texttt{UTXO} model and have an equivalent malleability fix such as Litecoin (i.e. Bitcoin Cash is not compatible.)

\subsubsection{Timelock,}
to enable new execution paths after some predefined amount of time, e.g. start the refund process after having locked funds on-chain without creating a race condition. It is worth noting that we do not require timelocks for the other chain.

\subsubsection{Hashlock,}
to syncronize both chains before allowing one to start the swap.

\subsubsection{2-of-2 multisig,}
to create a common path accessible only by the two participants if both agree. In this protocol we use the on-chain option in the context of Bitcoin, but off-chain multi-signature schemes are more efficient and should be preferred in other setups.

\subsubsection{Semi-Scriptless protocol,}
to reveal a secret and allow the protocol to continue execution without requiring complex scripting capabilities. We use ECDSA one-time VES such as described in \ref{oneTimeEcdsaVES}. It is worth noting that full scriptless script \cite{poelstra-adaptor} protocol should be able to achieve the same results with better efficiency.

\subsection{Equal discrete logarithm across groups zero-knowledge proof of knowledge}
Equal discrete logarithm across groups zero-knowledge proof of knowledge, as described in technical note \cite{MRL0010}, allow the verification of a common discrete logarithm $\alpha$ given two groups with fixed generators $G \in \GG$ and $H \in \HH$, where $\alpha \leq min(|G|,|H|)$, such that given $xG$ and $yH$: $x=y=\alpha$.

In this context we focus on groups \texttt{edward25519} with $|G| = l$ and \texttt{secp256k1} with $|H| = n$.

\begin{definition}[Equal discrete logarithm across groups scheme]
    An equal discrete logarithm across groups scheme is defined with two algorithms under the parameter tuple $(\GG,\HH,G,G',H,H')$:
\begin{itemize}
    \item $\DLProve(\alpha) \rightarrow (\phi,A,B)$: A probabilistic proving algorithm which on input of a discrete logarithm $\alpha$ outputs a proof $\phi$, a point $A \in \GG$, and a point $B \in \HH$.
    \item $\DLVrfy(\phi,A,B) \rightarrow \{0,1\}$: A deterministic proof verification algorithm which on input of a proof $\phi$, a point $A \in \GG$, and a point $B \in \HH$ outputs 1 if and only if $(A,B)$ share a common discrete logarithm across their respective groups.
\end{itemize}
\end{definition}

\subsubsection{Curve parameters}
\label{curveParams}
Bitcoin and Monero do not use the same elliptic curves. Bitcoin uses the \texttt{secp256k1} curve as defined in \textit{Standards for Efficient Cryptography (SEC)} with the \texttt{ECDSA} algorithm. Monero, based on the second version of CryptoNote \cite{van2013cryptonote}, uses \texttt{curve25519}, hereinafter also \texttt{edward25519}, from Daniel J. Bernstein \cite{CerRes10}.

We denote curve parameters for

\subsubsection{\texttt{edward25519}} as
\begin{equation}
\begin{split}
    q&: \text{a prime number;}\ q = 2^{255} - 19 \\
    d&: \text{an element of } \mathbb{F}_q;\ d = - 121665/121666 \\
    \mathcal{E}&: \text{an elliptic curve equation};\ -x^2 + y^2 = 1 + dx^2y^2 \\
    G&: \text{a base point};\ G = (x, -4/5) \\
    l&: \text{the base point order};\ l = 2^{252} + \text{\scriptsize27742317777372353535851937790883648493} \\
\end{split}
\end{equation}

\subsubsection{\texttt{secp256k1}} as
\begin{equation}
\begin{split}
    p&: \text{a prime number;}\ p = 2^{256} - 2^{32} - 977 \\
    a&: \text{an element of } \mathbb{F}_p;\ a = 0 \\
    b&: \text{an element of } \mathbb{F}_p;\ b = 7 \\
    \mathcal{E}'&: \text{an elliptic curve equation};\ y^2 = x^3 + ax + b \\
    H&: \text{a base point};\ H = \\ (&\texttt{\scriptsize0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798},\\ &\texttt{\scriptsize0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8}) \\
    n&: \text{the base point order};\ n = 2^{256} - \text{\scriptsize{432420386565659656852420866394968145599}} \\
\end{split}
\end{equation}

\subsection{\texttt{ECDSA} one-time VES}
\label{oneTimeEcdsaVES}
\texttt{ECDSA} one-time VES are introduced by Fournier et al. in \cite{oneTimeVES} as a generalization of the concept of adaptor signatures under \texttt{Schnorr} \cite{Schnorr:1989:EIS:646754.705037} and \texttt{ECDSA}. One-time Verifiably Encrypted Signatures, hereinafter one-time VES, are VES constructed such that with knowledge of the ciphertext and the plaintext, it is possible to recover the encrypting key.

We recall some of the algorithms defined in \cite{oneTimeVES} as:

\begin{definition}[\texttt{ECDSA} one-time VES]
    An \texttt{ECDSA} one-time VES scheme contains:
\begin{itemize}
    \item $\EncSign(\skSign, \pkEnc, m) \hskip2.3pt{\mbox{\tiny${\$}$\normalsize}}\!\!\rightarrow \hatsigma$: A possibly probabilistic encrypted signing algorithm, which on input of a secret signing key $\skSign$, a public encryption key $\pkEnc$, and a message $m$, outputs a ciphertext $\hatsigma$.
    \item $\EncVer(\pkSign, \pkEnc, m, \hatsigma) \rightarrow \bin$: A deterministic encrypted signature verification algorithm which --- on input of a public signing key $\pkSign$, a public encryption key $\pkEnc$, a message $m$ and a ciphertext $\hatsigma$ --- outputs 1 if and only if $\hatsigma$ is a valid encryption of a signature on $m$ for $\pkSign$ under $\pkEnc$.
    \item $\DecSig(\skEnc, \hatsigma) \rightarrow \sigma$: A (usually) deterministic signature decryption algorithm which --- on input of a decryption key $\skEnc$ and a valid ciphertext $\hatsigma$ under that encryption key --- outputs a valid signature $\sigma$.
    \item $\RecKey(\pkEnc, \hatsigma) \rightarrow \delta$: A deterministic recovery key extraction algorithm which extracts a recovery key $\delta$ from the ciphertext $\hatsigma$ and the public encryption key $\pkEnc$.
    \item $\Rec(\sigma,\rec) \rightarrow \skEnc$: A deterministic decryption key recovery algorithm which --- when given a decrypted signature $\sigma$ and the recovery key $\rec$ associated with the original ciphertext --- returns the secret decryption key $\skEnc$.
\end{itemize}
\end{definition}

\subsection{Generalization}
As shown in the Monero section, there are no on-chain requirements. We only make use of private key generation and addresses, meaning that this scheme can be generalized to any pair of cryptocurrencies where one fulfills the bitcoin prerequisites, making this scheme very chain agnostic, like \cite{succinct-atomic-swap} (under the assumption of the above cryptographic primitives existence for the underlying chains' parameters). However, it is worth noting that other schemes are simpler and more efficient when, in the pair, both
chains have on-chain capabilities, but such schemes are generally already deployed \cite{atomic-swap, scriptless-atomic-swap, btcGrinSwap}.

\section{Protocol}
The overall protocol is as follows: Alice moves the monero into an address where each participant controls half of the private spend key (later referred to as key ``shares''). The Bitcoin scripting language is then used with semi-scriptless protocols to reveal one of the halves of the private spend key, depending on which participant claims the bitcoin. Depending on who reveals their half of the private spend key, the locked monero change ownership. Bitcoin transactions are designed in such a way
that if a participant follows the protocol, they can't terminate with a loss.

If the deal goes through, Alice spends the bitcoin by revealing her private key share, thus allowing Bob to spend the locked monero. If the deal is cancelled, Bob spends the bitcoin after the first timelock by revealing his private key share thus allowing Alice to spend the monero, in both cases minus transaction fees.

Key exchange is performed with \texttt{ECDSA} one-time VES---also adaptor signatures---, and equal discrete logarithm across groups zero-knowledge proofs of knowledge. One-time VES are constructed such that given the ciphertext and the decrypted signature, the decryption key is easily recoverable.
By setting the private key share---one half of the Monero full private spend key---as the decryption key we have a way to atomically sell the private key share to the other participant. Thus, because Bitcoin and Monero use different curves, we need to prove the relation between points on \texttt{edward25519} and \texttt{secp256k1} to ensure protocol trustlessness.

\subsection{Non-interactive refund}
If Alice and or Bob locked their funds but one of them aborts the swap, or stop communicating at some point, the protocol must not require interactivity to complete the refund procedure for both participants. Otherwise Alice can keep Bob hostage by not responding and wait for the second timelock to get free bitcoin. In a gracefully aborted swap, Bob should reveal his Monero private key share, allowing Alice to get her monero back through one one-time VES.

\texttt{ECDSA} one-time VES are interactive: one has to provide the encrypted signature, and if the verification succeeds, the counterparty provides a valid signature for the 2-of-2 Bitcoin multisig back---a.k.a semi-scriptless scripts---, thus allowing the former to decrypt and publish two valid signatures for the 2-of-2 multisig and the latter to learn---on-chain---the decrypted signature and recover the decryption key.

As mentioned before, the refund process must be non-interactive: The protocol is designed in such a way that Alice learns Bob's refund encrypted signature and provides to Bob a valid refund 2-of-2 multisig signature before locking the funds. Bob can, in the case of a refund, decrypt and publish the signature without Alice's cooperation.

\subsection{Monero private keys}
Monero private keys are pairs of \texttt{edward25519} scalars: One is the private view key and the other is the private spend key. We use small letters to denote private keys and capital letters for public keys such that
$$X = xG$$
where $G$ is the generator element of the group $\GG$. We denote
\begin{enumerate}[label=(\roman*)]
    \item the private key $k^v$ as the full private view key,
    \item $K^v$ as the full public view key,
    \item $k^v_a$ as the private view key share of Alice and $k^v_b$ of Bob,
    \item the private key $k^s$ as the full private spend key,
    \item $K^s$ as the full public spend key,
    \item and $k^s_a$ as the private spend key share of Alice and $k^s_b$ of Bob.
\end{enumerate}

\subsubsection{Partial keys}
We denote private key shares as $k^s_a$ and $k^s_b$ such that
$$k^s_a + k^s_b \equiv k^s \pmod l$$

And then
\begin{equation}
\begin{split}
    k^s_aG &= K^s_a \\
    k^s_bG &= K^s_b \\
    K^s_a + K^s_b = (k^s_a + k^s_b)G = k^sG &= K^s
\end{split}
\end{equation}

The same holds for $k^v$ with $k^v_a$ and $k^v_b$.

\subsection{Zero-Knowledge proofs}
\label{eqDiscreteLog}
Zero-knowledge proofs are required at the beginning to make the protocol trustless. The protocol uses one-time VES to reveal private key shares, but we cannot check the discrete logarithm equality between the Monero public key share and Bitcoin public decryption key of the other participant before it goes on-chain. Thus we need to provide a proof that the discrete logarithm is the same across the two groups $\GG$ and $\HH$.

\subsubsection{Equal discrete logarithm across groups}
Alice and Bob must prove to each other with
\begin{equation}
\begin{split}
    k^s_i &\leftarrow \text{scalars on \texttt{edward25519} and \texttt{secp256k1} with an equivalent bit representation} \\
    K^s_i &= k^s_iG \in \GG \\
    B^s_i &= k^s_iH \in \HH \\
\end{split}
\end{equation}

for $i \in \{a, b\}$, given $K^s_i$ and $B^s_i$ that
\begin{equation}
\begin{split}
    \exists k^s_i \mid K^s_i = k^s_iG \land B^s_i = k^s_iH \land k^s_i < \textsf{min}(l,n)
\end{split}
\end{equation}

\subsection{Time parameters}
Two timelocks $t_0, t_1$ are defined during the initialization phase. $t_0$ sets the time window during which it is safe to execute the trade: after $t_0$, the refund process may start, making the trade unsafe to complete due to a potential race condition (even if it is hard to exploit in reality). $t_1$ sets the response time during which Bob is required to react, reveal his private Monero share to get his bitcoin back, and allow Alice to redeem her monero (if monero have been locked). After $t_1$, Alice is able to claim the bitcoin unilaterally.

\subsection{Bitcoin scripts}
Two scripts are needed on the bitcoin side: the first is used to complete the swap or start the refund process---a.k.a \texttt{SWAPLOCK}---, the second is used to complete the refund process---a.k.a \texttt{REFUND}---. In a successful swap, the second script does not go on-chain and is not used. Each script defines two possible paths, and we consequently explain the four possible ways (\textit{buy}, \textit{refund}, \textit{spend}, and \textit{claim}) of spending the two \texttt{UTXOs}.

\subsubsection{\texttt{SWAPLOCK}}
is a script used to lock funds and defines the two base execution paths: (1) swap execution---success---and (2) refund execution---fail---. We define the \texttt{SWAPLOCK} script as:

\begin{minted}[escapeinside=||,mathescape=true]{text}
OP_IF
    OP_SHA256 <|$h_s$|> OP_EQUALVERIFY
    2 <|$B_a$|> <|$B_b$|> 2 OP_CHECKMULTISIG
OP_ELSE
    <|$t_0$|> OP_CHECKSEQUENCEVERIFY OP_DROP
    2 <|$B^r_a$|> <|$B^r_b$|> 2 OP_CHECKMULTISIG
OP_ENDIF
\end{minted}

\subsubsection{Buy \texttt{SWAPLOCK},}
Alice takes control of the bitcoin and reveals her Monero key share to Bob with $\sigma_1$ --- a one-time VES leaking $k^s_a$ --- thus allowing Bob to take control of the monero. $\BTX_\textit{buy}$ redeems the \texttt{SWAPLOCK} with:

\begin{minted}[escapeinside=||,mathescape=true]{text}
OP_0 <|$\sigma_1$|> <|$\sigma_2$|> <|$s$|> OP_TRUE <|\texttt{SWAPLOCK} script|>
\end{minted}

\subsubsection{Refund \texttt{SWAPLOCK},}
signed by both participants, and moves the funds into the \texttt{REFUND} script. $\BTX_\textit{refund}$ redeems the \texttt{SWAPLOCK} with:

\begin{minted}[escapeinside=||,mathescape=true]{text}
OP_0 <|$\sigma_r'$|> <|$\sigma_r''$|> OP_FALSE <|\texttt{SWAPLOCK} script|>
\end{minted}

\subsubsection{\texttt{REFUND}}
is a script used in case the swap already started on-chain but is cancelled. This refund script is used to move the funds out of the \texttt{SWAPLOCK} script with the 2-of-2 timelocked multisig. We define the \texttt{REFUND} script as:

\begin{minted}[escapeinside=||,mathescape=true]{text}
OP_IF
    2 <|$B^r_a$|> <|$B^r_b$|> 2 OP_CHECKMULTISIG
OP_ELSE
    <|$t_1$|> OP_CHECKSEQUENCEVERIFY OP_DROP
    <|$B_a$|> OP_CHECKSIG
OP_ENDIF
\end{minted}

\subsubsection{Spend \texttt{REFUND},}
Bob cancels the swap and reveals his Monero private share with $\sigma_1'$ --- a one-time VES leaking $k^s_b$ --- thus allowing Alice to regain control over her Monero. $\BTX_\textit{spend}$ redeem the \texttt{REFUND} with:

\begin{minted}[escapeinside=||,mathescape=true]{text}
OP_0 <|$\sigma_1'$|> <|$\sigma_2'$|> OP_TRUE <|\texttt{REFUND} script|>
\end{minted}

\subsubsection{Claim \texttt{REFUND},}
Alice takes control of the bitcoin after both timelocks without revealing her Monero key share, resulting in Bob losing money for not following the protocol. $\BTX_\textit{claim}$ redeems the \texttt{REFUND} with:

\begin{minted}[escapeinside=||,mathescape=true]{text}
<|$sig_a$|> OP_FALSE <|\texttt{REFUND} script|>
\end{minted}

\subsection{Transactions}
We describe and name the Bitcoin and Monero transactions that are needed for the entire protocol.

\subsubsection{$\BTX_\textit{lock}$,}
a Bitcoin transaction with $\geq 1$ inputs from Bob and the first output (vout: 0) to the \texttt{SWAPLOCK} script and optional change outputs.

\subsubsection{$\BTX_\textit{buy}$,}
a Bitcoin transaction with 1 input consuming the \texttt{SWAPLOCK} script ($\BTX_\textit{lock}$, vout: 0) with the 2-of-2 semi-scriptless multisig and $\geq 1$ outputs.

\subsubsection{$\BTX_\textit{refund}$,}
a Bitcoin transaction with 1 input consuming the \texttt{SWAPLOCK} script ($\BTX_\textit{lock}$, vout: 0) with the 2-of-2 timelocked multisig and exactly one output to the \texttt{REFUND} script.

\subsubsection{$\BTX_\textit{spend}$,}
a Bitcoin transaction with 1 input consuming the \texttt{REFUND} script ($\BTX_\textit{refund}$, vout: 0) with the 2-of-2 semi-scriptless multisig and $\geq 1$ outputs.

\subsubsection{$\BTX_\textit{claim}$,}
a Bitcoin transaction with 1 input consuming the \texttt{REFUND} script ($\BTX_\textit{refund}$, vout: 0) with Alice signature and $\geq 1$ outputs.

\subsubsection{$\XTX_\textit{lock}$,}
a Monero transaction that sends funds to the address $(K^v,K^s)$.

\subsubsection{$\XTX_\textit{buy}$,}
a Monero transaction that spend funds from the address $(K^v,K^s)$.

\subsection{Full protocol sequence}
We describe the full protocol execution to successfully complete a swap, while computing and sharing all necessary knowledge in case any participant stops responding at any time or any participant starts the refund process actively.

During the first communication round, since both share parameters used to initialize the protocol, we might avoid schemes such as commit-reveal even with $K^s = K^s_a + K^s_b$: thanks to the equal discrete logarithm zero-knowledge proofs, one cannot arbitrarily choose $K^s$ and compute a valid proof $z_i$. However, to ensure getting a random view key for each execution, a commit-reveal must be added on $k^v_i$. Thus, without adding another round of communication, a commit-reveal might be added on $k^s_i$ also.

We define some utility algorithms to initialize, sign, and verify Bitcoin and Monero transactions.

\begin{itemize}
    \item $\InitTx()$: A generic and deterministic algorithm which --- on input of a set of parameters --- outputs a valid initialized transaction.
    \item $\Sign()$: A generic and probabilistic algorithm for siging a transaction which --- on input of a private key and an initialized transaction --- outputs a valid signature for the transaction.
    \item $\VrfyTx()$: A generic and deterministic algorithm which --- on input of a set of transactions and parameters --- outputs 1 if and only if the transactions are valid under the protocol rules and blockchain consensus.
    \item $\Verify()$: A generic and deterministic algorithm which --- on input of a public key, a transactions and a signature --- outputs 1 if and only if the signature is valid for transactions given the public key.
    \item $\PubTx()$: A generic algorithm for publishing a transactions over the network.
    \item $\WatchTx()$: A generic algorithm for waiting on a transaction to confirm.
    \item $\RecSig()$: A generic algorithm for extracting transaction's signatures.
\end{itemize}

\newpage

\begin{figure}[H]
    \begin{table}[H]
        \centering
      {\renewcommand{\arraystretch}{1.1}%
      \begin{tabular}{ | l c l | }
        \hline
          \multicolumn{1}{|c}{Alice (XMR$\rightarrow$BTC)} &  & \multicolumn{1}{c|}{Bob (BTC$\rightarrow$XMR)} \\
          $k^v_a, k^s_a \xleftarrow{R} [1, l-1]$ & & $k^v_b, k^s_b \xleftarrow{R} [1, l-1]$ \\
          %$K^s_a \leftarrow k^s_aG$ & & $K^s_b \leftarrow k^s_bG$ \\
          %$B^s_a \leftarrow k^s_aH$ & & $B^s_b \leftarrow k^s_bH$ \\
          $b_a,b^r_a \xleftarrow{R} [1, n-1]$ & & $b_b,b^r_b \xleftarrow{R} [1, n-1]$ \\
          $B_a \leftarrow b_aH$ & & $B_b \leftarrow b_bH$ \\
          $B^r_a \leftarrow b^r_aH$ & & $B^r_b \leftarrow b^r_bH$ \\
          $(z_a, K^s_a, B^s_a) \leftarrow \DLProve(k^s_a)$ & & $(z_b, K^s_b, B^s_b) \leftarrow \DLProve(k^s_b)$ \\
          & & $s \xleftarrow{R} [0, 2^{256}]$ \\
          & & $h_s \gets \texttt{SHA256}(s)$ \\
           & & \\

          \multicolumn{3}{|c|}{$\xlongleftrightarrow{\langle k^v_i, K^s_i, B_i, B^s_i, B^r_i, z_i, h_s \rangle \  \forall i \in \{a, b\}}$} \\

          & $k^v \equiv k^v_a + k^v_b \pmod l$ & \\
          & $K^v = k^vG$, \ $K^s = K^s_a + K^s_b$ & \\

          \DLVrfy$(K^s_b, B^s_b, z_b) \stackrel{?}{=} 1$ & & \DLVrfy$(K^s_a, B^s_a, z_a) \stackrel{?}{=} 1$ \\
          & & $(\BTX_\textit{lock}$, $\BTX_\textit{refund}) \gets$ \InitTx$(B_a, B_b, B^r_a, B^r_b)$ \\
          & & $\sigma_r' \gets$ \Sign$(b^r_b, \BTX_\textit{refund})$ \\

          \multicolumn{3}{|c|}{$\xleftarrow{\langle \BTX_\textit{lock}, \BTX_\textit{refund}, \BTX_\textit{spend}, \sigma_r' \rangle}$} \\

          \VrfyTx$(\BTX_\textit{lock}$, $\BTX_\textit{refund}, B_a, B_b, B^r_a, B^r_b, h_s) \stackrel{?}{=} 1$ & & \\
          \Verify$(B^r_b, \BTX_\textit{refund}, \sigma_r') \stackrel{?}{=} 1$ & & \\
          $\hatsigma_1' \gets \EncSign(b^r_a, B^s_b, \BTX_\textit{spend})$ & & \\
          $\delta' \gets \RecKey(B^s_b, \hatsigma_1')$ & & \\
          $\sigma_r'' \gets$ \Sign$(b^r_a, \BTX_\textit{refund})$ & & \\

          \multicolumn{3}{|c|}{$\xrightarrow{\langle \sigma_r'', \hatsigma_1' \rangle}$} \\

          & & $\EncVer(B^r_a, B^s_b, \BTX_\textit{spend}, \hatsigma_1') \stackrel{?}{=} 1$ \\
          & & \Verify$(B^r_a, \BTX_\textit{refund}, \sigma_r'') \stackrel{?}{=} 1$ \\
          %& & \Verify$(B^r_a, \BTX_\textit{spend}, \sigma_2') \stackrel{?}{=} 1$ \\
          & & $\BTX_\textit{buy} \gets$ \InitTx$(\BTX_\textit{lock})$ \\
          & & $\hatsigma_1 \gets \EncSign(b_b, B^s_a, \BTX_\textit{buy})$ \\
          & & $\delta \gets \RecKey(B^s_a, \hatsigma_1)$ \\
          & & \PubTx$(\BTX_\textit{lock})$ \\

          \multicolumn{3}{|c|}{$\xleftarrow{\langle \BTX_\textit{buy}, \hatsigma_1 \rangle}$} \\

          $\EncVer(B_b, B^s_a, \BTX_\textit{buy}, \hatsigma_1) \stackrel{?}{=} 1$ & & \\
          \WatchTx$(\BTX_\textit{lock}) \stackrel{?}{=} 1$ & & \\
          \multicolumn{3}{|c|}{$\dots$} \\

          $\XTX_\textit{lock} \gets$ \InitTx$(K^v, K^s)$ & & \\
          \PubTx$(\XTX_\textit{lock})$ & & \\

          \multicolumn{3}{|c|}{$\dots$} \\
          & & \WatchTx$(K^v, K^s)$ w/ $(k^v, K^s) \stackrel{?}{=} 1$ \\

          \multicolumn{3}{|c|}{$\xleftarrow{\langle s \rangle}$} \\

          $\sigma_1 \gets \DecSig(k^s_a, \hatsigma_1)$ & & \\
          $\sigma_2 \gets \Sign(b_a, \BTX_\textit{buy})$ & & \\
          $\sigma := (\sigma_1, \sigma_2)$ & & \\
          \PubTx$(\BTX_\textit{buy}, \sigma, s)$ & & \\

          & & \WatchTx$(\BTX_\textit{buy}) \stackrel{?}{=} 1$ \\
          \multicolumn{3}{|c|}{$\dots$} \\

          & & $(\sigma_1, \sigma_2) \gets \RecSig(\BTX_\textit{buy})$ \\
          & & $k^s_a \gets \Rec(\sigma_1, \delta)$ \\
          & & $k^s \equiv k^s_a + k^s_b \pmod l$ \\
          & & $\langle k^v, k^s \rangle$ \\
        \hline
      \end{tabular}}
    \end{table}
  \caption{Protocol execution between Alice and Bob for a successful swap}
  \label{fig:protocol}
\end{figure}

Dots represent synchronization timing during which one or more participants must check for transaction confirmations before continuing the protocol execution. The level of security --- i.e. the number of confirmations required by each participants --- is a local parameter, but must be set according to the timing parameters --- which are global to both participants --- to avoid the case where the timing is less or equal to the security parameter.

\section{Further research}
This protocol is implementable with today's state of Bitcoin and Monero, but further research is required to use \texttt{Schnorr} capabilities and simplicity to create a more efficient protocol with lighter on-chain footprints. This would improve anonymization of atomic swaps with respect to chain-analysis.

As discussed, this protocol can be adapted to other cryptocurrencies. Some of them might not have atomic swaps yet, and extending to other pairs might improve decentralization. Extending this protocol to privacy preserving cryptocurrency pairs only --- like Monero with Mimblewimble --- is the next challenge in atomic swaps.

Integration with services or decentralized exchanges would help democratizing trading without trusted institutions and might increase the market liquidity. Since the design presented here is asymmetric, building services might not be straightforward.

\subsection{Known limitations}
To provide liveness (if at least one participant is still online) we allow for the worst case scenario in which a participant may end up losing funds (by not being able to claim on the other chain). This can happen in the case where they do not follow the protocol, e.g. remaining online during pending swap or claiming funds in time. The rationale behind this design is explained in \ref{worstCaseRationale}.

Fees are different from one chain to the other partly because of internal blockchain parameters \& transaction complexity, and also due to external factors such as demand for blockspace. Note that within this protocol, the Bitcoin blockchain is used as a decision engine, where we use scripting features of bitcoin---although we try to put as much logic as we can off-chain---, which causes bigger transactions on the bitcoin side. These two factors combined make the Bitcoin transactions more expensive in general than those on the Monero chain.

Instant user feedback in a cross-chain atomic swap is hard to achieve.  The slowest chain and the number of confirmations required for transaction finality dictate the speed of the protocol, allowing front running in some cases. The protocol can be extended to prevent front running within certain setups however. It is worth noting that front running cannot be enforced by one participant on the other, thus making the worst case scenario the loss of transaction fees on each of the participants' respective blockchains.

\section{Acknowledgement}
The Monero Research Lab and Sarang Noether are acknowledged for their helpful comments during the completion of this work. This work has been supported and partially funded by the Monero Community --- we extend a special thanks to all donators. Finally, thanks to TrueLevel SA collaborators for the initial funding and their helpful contribution and comments.

%
% ---- Bibliography ----
%
\printbibliography

\end{document}


\documentclass[aps,preprint]{revtex4-1}
\usepackage{graphicx}
\usepackage{amsmath}
\usepackage{makeidx}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage{xcolor}

\begin{document}

\title{Efficiency and entropy production of selfish drivers}

\date{\today}

\begin{abstract}
Characterizing transport processes in a city system is important to have a better picture of efficiency and sustainability in such a complex system. In this study, we consider the process of movements of selfish drivers from their homes (origins) to work places (destinations) to see how interactions and randomness in the movements affect a measure of efficiency and entropy production in this process. Interactions are modelled by the effect of the flows on the local travel times, and by exploiting the travel information from the previous days. Here, the efficiency is computed by comparing the total travel time with the number of travels along the links. And, the entropy production is obtained by comparing the time intervals of leaving the origins and arriving at the destinations. We use  realistic models of population distributions and mobility laws for simulation of the movement process where at each step a driver moves to a neighbouring site which is closer to the destination or which is chosen randomly. We observe that interactions and a naive way of using the travel information without any coordination reduce the efficiency and increase the entropy production of the process. Moreover, the larger systems display smaller efficiencies for the same model parameters like the population density which limits the size of an efficient city. On the other hand, randomness in the movements can help to enhance the efficiency when the strength of interactions is large and congestion is high. We also find that the entropy production is a good order parameter to distinguish the low- and high-congestion phases. In the former phase, the entropy production grows monotonically with the probability of random moves whereas it displays a minimum in the congested phase; that is randomness in the movements can reduce the uncertainty in the destination time intervals.
\end{abstract}

%\pacs{}

\maketitle

\section{Introduction}\label{S0}

\begin{itemize}

\item interactions $(g,\lambda)$ increase the travel time, reduce the efficiency, and increase the entropy production.

\item $\lambda=0$:

- we observe a change in behaviour of the entropy production $\Delta S_D$ vs the disorder parameter $\alpha$ as the interaction strength $g$ increases.  For sufficiently large $g$, a bit of disorder can reduce the entropy production.

\item $\lambda=0.5$:

- we observe a change in the complexity of the time series in days as the interaction strength $g$ increases.

- the efficiency and velocity display a (nontrivial) maximum for some disorder $\alpha^*(g)$ depending on the parameter $g$.

- mutual information between $(t_O,t_D)$ increases whereas that of $(\Delta x_{OD},\Delta t_{OD})$ decreases by introducing $\lambda$.

\end{itemize}

\section{Models and Settings}\label{S1}
In this section, we present the main definitions and methods which are used to model the network flow dynamics.
Consider a city of $N$ sites with local populations $\{m_a:a=1,\dots,N\}$ and total population $M=\sum_a m_a$. The connectivity graph of the city is given by $G(V,E)$ where $V$ is the set of sites and $E$ is the set of directed edges $(ab)$. Here we take a two dimensional square lattice of size $N=L\times L$, where all edges have the same length and the same free travel times. We use the simple growth model introduced in Ref. \cite{Li-nc-2017} to produce reasonable population distributions for the model cities. The population density is fixed to $M/N=10^3$ in the following.

Given the population distribution $m_a$, we use the following mobility law to construct the flux of movements $m_{a\to b}$ from origins $a$ to destinations $b$,
\begin{align}\label{mab}
m_{a\to b}=m_ap_{a\to b}=m_a\frac{m_b/M(r_{ab})}{\sum_{c\neq a} m_c/M(r_{ac})},
\end{align}
where $M(r_{ab})$ is the population in the circle of radius $r_{ab}$ centred at site $b$. The ratio $m_b/M(r_{ab})$ can be interpreted as the attractiveness of site $b$ for an individual at site $a$.

Finally, the flows of movements on edges $(ab)\in E$ are determined by a flux distribution problem that satisfies the system constraints and preferences, as follows.

\subsection{The movement process}\label{S11}
Here is the process of moving from the origins to destinations in a single day:

\begin{itemize}

\item The starting times of the OD trips are distributed uniformly in the origin time interval $\Delta T_O$. We assume that $\Delta T_O$ is the same for all origins. In each time step, the time increases by $\Delta t=1$. Driver $i$ starts its trip and becomes active at time $t_O(i) \in \Delta T_O$. The trip will become inactive when the driver reaches its destination at time $t_D(i) \in \Delta T_D$. The destination time interval $\Delta T_D$ is determined by the system structure and dynamics (see Fig. \ref{Tday}).
The arrival times of the drivers to destination site $a$ determine the destination time interval $\Delta T_D(a)$ of that site.
The travel time from origin to destination for driver $i$ is denoted by $\Delta t_{OD}(i)=t_D(i)-t_O(i)$.

\item An active driver $i$ at site $a$ chooses the next site as follows: with probability $\alpha$ the next site is chosen randomly and uniformly from the set of neighbouring sites. With probability $1-\alpha$ the neighbour that minimizes the expected travel time to the destination $D(i)$ is selected. The expected travel time on edge $(ab)$ is denoted by $\tilde{t}_{ab}$. The expected travel times in day $d$ are estimated by using the actual travel times $t_{ab}$ from the previous day:
\begin{align}\label{tab0}
\tilde{t}_{ab}(d)=\lambda t_{ab}(d-1)+(1-\lambda) \tilde{t}_{ab}(d-1).
\end{align}
For the initial day $\tilde{t}_{ab}(0)=t_{ab}(0)$, where the $t_{ab}(0)$ are the travel times for free lines.

\item Let flow $F_{ab}(t)$ be the number of people that enter edge $(ab)$ at time step $t$. Given the input flows, then the actual travel times are obtained from
\begin{align}\label{tab}
t_{ab}(F_{ab})=t_{ab}(0)\left(1+g(\frac{F_{ab}}{F_{ab}^*})^{\mu}\right),
\end{align}
with $g (F_{ab}/F_{ab}^*)^{\mu}$ to model the influence of flows on the travel times \cite{BPR-1964,lc-trans-1976,lc-trans-2011}. Here $F_{ab}^*$ is a measure of the line capacity. For simplicity, we assume that $t_{ba}(0)=t_{ab}(0)$ and $F_{ba}^*= F_{ab}^*$.
In the following we take $\mu=3$, $t_{ab}(0)=1$, and $F_{ab}^*=M/|E|$ in all simulations.

\end{itemize}

The actual travel time $t_{ab}$ determines the time that a person spends on edge $(ab)$. The total number of persons on edge $(ab)$ at time step $t$ is denoted by the flow density $\rho_{ab}(t)$.

\section{Results}\label{S2}
Let us start with the effects of interactions on the cumulative distribution of the travel times $P(\Delta t_{OD}>T)$ in the absence of any randomness in the movements ($\alpha=0$). As Fig. \ref{Ti} shows, the travel times increase by introducing the interactions either by considering the effects of flows on the trips (with $g$) or by knowing the travel information from the previous days (with $\lambda$). The latter says that a selfish way of using the information without any coordination could result to a chaotic situation \cite{Apps-ieee-2019}. We know that interacting systems can display complex behaviours and interactions may reduce the system predictability \cite{watts-sci-2006}. In the following, we see how the interplay of the above interactions with disorder in the movements affects a measure of complexity and predictability of the movement process. In addition, we follow the changes in the efficiency and a measure of entropy production in the system to see how the relation between these qualities depend on the macroscopic state (phase) of the system \cite{efc-srep-2020}.

\subsection{Complexity and predictability}\label{S21}
A measure of predictability for two stochastic variables $x,x'$ is provided by the mutual information of the two variables,
\begin{align}
\mathrm{MI}(x,x')=\sum_{x,x'}P(x,x')\log\frac{P(x,x')}{P(x)P(x')},
\end{align}
where $P(x,x'), P(x)$ and $P(x')$ are the joint and marginalized probability distributions of the variables.

Let us define the mutual information between the destination and origin times
\begin{align}
\Pi_{t,t}=\mathrm{MI}(t_O,t_D),
\end{align}
and the mutual information between the travel time and the geometrical distance,
\begin{align}
\Pi_{x,t}=\mathrm{MI}(\Delta x_{OD},\Delta t_{OD}).
\end{align}
Figure \ref{Pi} shows the results of numerical simulations for these quantities in a square lattice of linear size $L=20$.
As expected, the above measures of predictability diminish with increasing $g$ or $\alpha$, except the small jump that is observed
for $\lambda=0.5$ when $\alpha$ changes from zero.  On the other hand, we observe that $\Pi_{t,t}$ increases but $\Pi_{x,t}$ decreases after using the travel times from the previous days (i.e., for $\lambda=0.5$). Note that when $\lambda=0$ all edges have the same estimated travel times $\tilde{t}_{ab}(d)=t_{ab}(0)=1$ where the shortest path is strongly correlated with the geometrical distance $\Delta x_{OD}$. On the other side, when $\lambda=0.5$ there are some edges with small travel times in the previous day and all drivers are aware of this information which in turn determines the shortest path to their destinations. Therefore, one expects to observe less correlations here between the geometrical distance and the actual travel times. However, the same global information now makes the arrival times to the destinations more dependent on the departure times from the origins and results to larger mutual information between the two time variables.

To address the complexity of the process, we check the presence of long range correlations in the time evolution of the system.
Consider a stationary time series $\{\cdots,x_{n-1},x_n,x_{n+1},\cdots\}$ and a string of data points which is divided into two equal data sets $\mathbf{x}_{past}$ and $\mathbf{x}_{future}$ of length $l$. A measure of complexity can be defined by the scaling of the mutual information $\mathrm{MI}(\mathbf{x}_{past},\mathbf{x}_{future})$ with $l$. This information could be independent of the size or increase logarithmically or even sub-linearly with $l$ \cite{bialek-nc-2001}. In the following, however, we study a computationally more efficient but approximate way of detecting a time series complexity, which is based on an estimation of information rate (sample entropy) in different time scales \cite{samp-ajp-2000,costa-prl-2002}.

Consider the coarse grained time series $\{\cdots,y_{n-1},y_n,y_{n+1},\cdots\}$ obtained by averaging the original time series within a window of size $w$, i.e., $y_n=(\sum_{n'=(n-1)w+1}^{nw}x_{n'})/w$. Let $\mathbf{y}_n(l)$ be a sequence of length $l$ starting at $n$. We define $p(l:r,w)$ as the probability that two such sequences are within distance $r$ of each other, i.e., $d(\mathbf{y}_n(l),\mathbf{y}_{n'}(l))<r \times std(x)$. Here $d(\mathbf{y}_{n_1}(l),\mathbf{y}_{n_2}(l))=\max_{0\le n'<l}|y_{n_1+n'}-y_{n_2+n'}|$ and $std(x)$ denotes the standard deviation of the original time series. Then the sample entropy at scale factor $w$ is given by $SampEn(l,r,w)=-\log (p(l+1:r,w)/p(l:r,w))$. The ratio of the two probabilities is indeed the conditional probability that two sequences of size $l$ which are within distance $r$ of each other are still close when the size increases to $l+1$. Here we take $l=2$ and $r=0.2$. A large value of the above sample entropy for large scale factors indicates on the presence of long range correlations in the system. It also means that still distinct sequence patterns appear when the series is looked at larger time scales.

Now let us define the average flow density, using the local flow densities $\rho_{ab}(t)$,
\begin{align}
\rho(t)=\frac{1}{|E|}\sum_{(ab)}\rho_{ab}(t).
\end{align}
To study the day to day correlations we take the maximum flow density $\rho^*=\max_{t}{\rho(t)}$ and the associated time series $\{\cdots,\rho^*_{d-1},\rho^*_d,\rho^*_{d+1},\cdots\}$ in a sequence of days indexed by $d$. Figure \ref{Sw} displays the sample entropy in terms of the scale factor $w$ for single instances of the above time series. We observe that the sample entropy decays very slowly around $g=2$ signalling the presence of long range correlations in the system. In the following we see how this change in the complexity affects the qualitative behaviour of other interesting quantities in the system.

\subsection{Efficiency and entropy production}\label{S22}
The average travel time in the process is given by
\begin{align}
\tau_{OD}=\frac{1}{M}\sum_{i} \Delta t_{OD}(i).
\end{align}
The average number of travels per person in a day is obtained from the sum of all the input flows $F_{ab}(t)$ for different edges and times,
\begin{align}
\sigma_{OD}=\frac{1}{M}\sum_{t} \sum_{(ab)} F_{ab}(t).
\end{align}
A measure of efficiency is defined by ratio of the two
\begin{align}
\eta_{OD}=\frac{1/\tau_{OD}}{\sigma_{OD}}.
\end{align}

For each person we can also define the velocity $v_{OD}(i)=\Delta x_{OD}(i)/\Delta t_{OD}(i)$, given the geometrical origin to destination distances $\Delta x_{OD}(i)$. Then the average velocity is
\begin{align}
v_{OD}=\frac{1}{M}\sum_{i} v_{OD}(i).
\end{align}

A measure of increase in the system disorder or uncertainty (entropy production) is provided by the distribution of the destination time intervals
\begin{align}
\Delta S_D=\langle \log \Delta T_D \rangle-\langle \log \Delta T_O \rangle=\frac{1}{N}\sum_a \log \Delta T_D(a)-\log \Delta T_O.
\end{align}
As mentioned above, $\Delta T_O$ is the same for all the sites $a$.

\section{Conclusion}\label{S3}
In summary, numerical simulations of the movement process shows that in general interactions $(g,\lambda)$ increase the travel time, reduce the efficiency, and increase the entropy production. A selfish usage of information from the previous days results to smaller efficiency and velocity but at the same time enhance the mutual information between the origin and destination times of the trips. This enhancement in the mutual information probably is the only good point of such a movement process. Moreover, the efficiency and velocity display a (nontrivial) maximum for some randomness probability $\alpha^*$ depending on the strength of interactions. We also observed a qualitative change in the behaviour of the entropy production $\Delta S_D$ with the randomness parameter $\alpha$ as the parameter $g$ increases. In fact, for sufficiently large $g$, one can reduce the uncertainty in the destination times by introducing randomness in the movements. In other words, the response of $\Delta S_D$ to the randomness $\alpha$ can be used to discriminate the ordered and disordered phases of the flows in the system.

An interesting observation is that the efficiency and velocity are significantly reduced by increasing the system linear size $L$ when the other model parameters are fixed even for the same density $M/N$ and $L/\Delta T_O$.  For instance here the efficiency and velocity scale roughly as $L^{-2.3}$ and $L^{-0.3}$, respectively. This means that under the above conditions the city size is limited by the efficiency or velocity of the movement process. An important quantity here is the link capacity $F^*_{ab}$, which controls the travel times for a give flow in link $(ab)$. In the numerical simulation, we set $F^*_{ab}=M/|E|$ independent of the link position in the lattice, whereas the population is not distributed homogeneously. The question then is how we should adjust the local capacities such that the efficiency approaches a desirable limit by increasing the size of the system.

\begin{thebibliography}{prsty}

%\bibitem{Lavenda-book-1978} Lavenda, B. H. Thermodynamics of irreversible processes. (London: Macmillan, 1978).
%
%
%
%\bibitem{B-book-2012} Bialek, W. Biophysics: searching for principles. (Princeton University Press, 2012).
%
%
%
%\bibitem{Emarket-jfe-1998} Fama, E. F. Market efficiency, long-term returns, and behavioral finance. {\it Journal of financial economics} {\bf 49}(3), 283-306 (1998).
%
%\bibitem{Emarket-jep-2003} Shiller, R. J. From efficient markets theory to behavioral finance. {\it Journal of economic perspectives} {\bf 17}(1), 83-104 (2003).
%
%\bibitem{Emarket-jpm-2004} Lo, A. W. The adaptive markets hypothesis. {\it The Journal of Portfolio Management}, {\bf 30}(5), 15-29 (2004).
%
%
%\bibitem{ut-nat-2010} Bettencourt, L. M. A. \& West, G. B. A unified theory of urban living. {\it Nature}
%{\bf 467}, 912–913 (2010).
%
%\bibitem{Batty-book-2013} Batty, M. The new science of cities. (MIT press, 2013).
%
%\bibitem{B-book-2016} Barthelemy, M. The Structure and Dynamics of Cities
%(Cambridge University Press, Cambridge, 2016).
%
%\bibitem{B-nr-2019} Barthelemy, M. The statistical physics of cities. {\it Nature Reviews Physics}  {\bf 1}, 406–415 (2019).
%
%
%
%
%\bibitem{cp-sci-2011} Glaeser, E. Cities, productivity, and quality of life. {\it Science} {\bf 333}, 592–594 (2011).
%
%
%\bibitem{neq-ac-2006} Pulselli, R. M., Ciampalini, F., Galli, A., \& Pulselli, F. M. Non equilibrium thermodynamics and the city: A new approach to urban studies. {\it Annali di chimica}, {\bf 96}(9‐10), 543-552 (2006).
%
%\bibitem{Batty-sci-2008} Batty, M. The size, scale, and shape of cities. {\it Science} {\bf 319}, 769–771 (2008).
%
%\bibitem{tc-spr-2009} Wilson, A. The “thermodynamics” of the city. In Complexity and Spatial Networks,  11-31 (Springer, Berlin, Heidelberg, 2009).
%
%\bibitem{cg-jie-2015} Bristow, D., \& Kennedy, C. Why do cities grow? Insights from nonequilibrium thermodynamics at the urban and global scales. {\it Journal of Industrial Ecology}, {\bf 19}(2), 211-221 (2015).
%
%
%
%
%\bibitem{scaling-sci-2013} Bettencourt, L. M. A. The origins of scaling in cities.{\it  Science} {\bf 340}, 1438–1441 (2013).
%
%\bibitem{scaling-plos-2014} Louf, R., Roth, C., \& Barthelemy, M.  Scaling in transportation networks. {\it PLoS One}, {\bf 9}(7) (2014).
%
%
%
\bibitem{Li-nc-2017} Li, R., Dong, L., Zhang, J., Wang, X., Wang, W. X., Di, Z., \& Stanley, H. E.  Simple spatial scaling rules behind complex cities. {\it Nature communications}, {\bf 8}(1), 1-7 (2017).
%
%
%\bibitem{mt-book-2011} Ortuzar, J. \& Willumsen, L. Modelling Transport. (John Wiley \& Sons., New York, 2011)
%
%
%
%\bibitem{sf-nature-1999} Banavar, J. R., Maritan, A., \& Rinaldo, A. Size and form in efficient transportation networks. {\it Nature}, {\bf 399}(6732), 130-132 (1999).
%
%\bibitem{sus-book-2005} Banister, D. Unsustainable transport: city transport in the new century (Taylor \& Francis, 2005).
%
%
%
%
%\bibitem{C-pre-1999} Crooks, G. E. Entropy production fluctuation theorem and the nonequilibrium work relation for free energy differences. {\it Physical Review E} {\bf 60}(3), 2721 (1999).
%
%\bibitem{J-cm-2011} Jarzynski, C. Equalities and inequalities: Irreversibility and the second law of thermodynamics at the nanoscale. {\it Annu. Rev. Condens. Matter Phys.} {\bf 2}(1), 329-351 (2011).
%
%\bibitem{st-rpp-2012} Seifert, U. Stochastic thermodynamics, fluctuation theorems and molecular machines. {\it Reports on progress in physics} {\bf 75}(12), 126001 (2012).
%
%
%
%\bibitem{E-njp-2003} Kolbl, R., \& Helbing, D.  Energy laws in human travel behaviour. {\it New Journal of Physics}, {\bf 5}(1), 48 (2003).
%
%
%
%
%\bibitem{rad-nature-2012} Simini, F., Gonzalez, M. C., Maritan, A., \& Barabasi, A. L.  A universal model for mobility and migration patterns. {\it Nature}, {\bf 484}(7392), 96-100 (2012).
%
%\bibitem{Hasan-jsp-2013} Hasan, S., Schneider, C. M., Ukkusuri, S. V., \& Gonzalez, M. C.  Spatiotemporal patterns of urban human mobility. {\it Journal of Statistical Physics}, {\bf 151}(1-2), 304-318 (2013).
%
\bibitem{Yan-intf-2014} Yan, X. Y., Zhao, C., Fan, Y., Di, Z., \& Wang, W. X.  Universal predictability of mobility patterns in cities. {\it Journal of The Royal Society Interface}, {\bf 11}(100), 20140834 (2014).
%
%\bibitem{Ren-nc-2014} Ren, Y., Ercsey-Ravasz, M., Wang, P., Gonzalez, M. C., \& Toroczkai, Z.  Predicting commuter flows in spatial networks using a radiation model based on temporal ranges. {\it Nature communications}, {\bf 5}(1), 1-9 (2014).
%
%\bibitem{mob-plos-2015} Kang, C., Liu, Y., Guo, D., \& Qin, K.  A generalized radiation model for human mobility: spatial scale, searching direction and trip constraint. {\it PloS one}, {\bf 10}(11) (2015).
%
%
%
%\bibitem{lo-plos-2015} Mastroianni, P., Monechi, B., Liberto, C., Valenti, G., Servedio, V. D., \& Loreto, V.  Local optimization strategies in urban vehicular mobility. {\it PloS one}, {\bf 10}(12), (2015).
%
%\bibitem{Serdar-nc-2016} Colak, S., Lima, A., \& Gonzalez, M. C.  Understanding congested travel in urban areas. {\it Nature communications}, {\bf 7}(1), 1-8 (2016).
%
%
%
%
%\bibitem{horner-epa-2002} Horner, M. W. Extensions to the concept of excess commuting. {\it Environ. Plann. A} {\bf 34}, 543–566 (2002).
%
%\bibitem{newman-jstst-2006} Gastner, M. T. \& Newman, M. E. Shape and efficiency in spatial distribution networks. {\it J. Stat. Mech-Theory E.} P01015 (2006).
%
%\bibitem{EC-trans-2015} Kanaroglou, P. S., Higgins, C. D. \& Chowdhury, T. A. Excess commuting: a critical review and comparative analysis of concepts, indices, and policy implications. {\it J. Transp. Geogr.} {\bf 44}, 13–23 (2015).
%
%\bibitem{ceff-srep-2016}Dong, L., Li, R., Zhang, J., \& Di, Z.  Population-weighted efficiency in transportation networks. {\it Scientific reports}, {\bf 6}, 26377 (2016).
%
\bibitem{indaco-arx-2018} Biazzo, I., Monechi, B., \& Loreto, V.  General scores for accessibility and inequality measures in urban areas. {\it Royal Society open science}, {\bf 6}(8), 190979 (2019).
%
%
%\bibitem{hmobility-nph-2010} Song, C., Koren, T., Wang, P., \& Barabasi, A. L.  Modelling the scaling properties of human mobility. {\it Nature Physics}, {\bf 6}(10), 818-823 (2010).
%
%\bibitem{sp-mpc-2012} Riccardo, G., Armando, B., \& Sandro, R.  Towards a statistical physics of human mobility. {\it International Journal of Modern Physics C}, {\bf 23}(09), 1250061 (2012).
%
%\bibitem{motif-rci-2013} Schneider, C. M., Belik, V., Couronné, T., Smoreda, Z., \& Gonzalez, M. C.  Unravelling daily human mobility motifs. {\it Journal of The Royal Society Interface}, {\bf 10}(84), 20130246 (2013).
%
%\bibitem{motif-nc-2017} Yan, X. Y., Wang, W. X., Gao, Z. Y., \& Lai, Y. C.  Universal model of individual and population mobility on diverse spatial scales. {\it Nature communications}, {\bf 8}(1), 1-9 (2017).
%
%
%

\bibitem{BPR-1964} US Bureau of Public Roads. Office of Planning. Urban Planning Division. Traffic Assignment Manual for Application with a Large, High Speed Computer. US Department of Commerce; 1964.

\bibitem{lc-trans-1976} Branston D. Link capacity functions: A review. Transportation research. 1976 Aug 1;10(4):223-36.

\bibitem{lc-trans-2011} Huntsinger, L. \& Rouphail, N. Bottleneck and queuing analysis: calibrating volume–delay functions of travel demand models. {\it Transp. Res. Rec.} {\bf 2255}, 117–124 (2011).

%
%
%
%\bibitem{popGridEurostat}
%Eurostat population grid;
%\newblock \textit{Available at}
%\url{http://ec.europa.eu/eurostat/web/gisco/geodata/reference-data/population-distribution-demography/geostat}.
%
%\bibitem{sedacV4}
%Center for International Earth Science Information Network CIESIN Columbia~University
%C. {Gridded Population of the World, Version 4 (GPWv4): Population Count}.
%\newblock Palisades, NY: NASA Socioeconomic Data and Applications Center (SEDAC); 2016.
%\newblock Available from: \url{http://dx.doi.org/10.7927/H4X63JVC}.
%
%
%
%\bibitem{critical-dd-1999} Batty, M., \& Yichun X. Self-organized criticality and urban development. {\it Discrete Dynamics in Nature and Society} {\bf 3}(2-3), 109-124 (1999).
%
%\bibitem{predict-sci-2010} Song, C., Qu, Z., Blumm, N., \& Barabasi, A. L.  Limits of predictability in human mobility. {\it Science}, {\bf 327}(5968), 1018-1021 (2010).
%
%\bibitem{predict-jsta-2013} Gallotti, R., Bazzani, A., Degli Esposti, M., \& Rambaldi, S.  Entropic measures of individual mobility patterns. {\it Journal of Statistical Mechanics: Theory and Experiment}, {\bf 2013}(10), P10022 (2013).
%

\bibitem{watts-sci-2006} Salganik MJ, Dodds PS, Watts DJ. Experimental study of inequality and unpredictability in an artificial cultural market. science. 2006 Feb 10;311(5762):854-6.

\bibitem{Apps-ieee-2019} Macfarlane J. When apps rule the road: The proliferation of navigation apps is causing traffic chaos. It's time to restore order. IEEE Spectrum. 2019 Sep 24;56(10):22-7.

\bibitem{efc-srep-2020} Biazzo I, Ramezanpour A. Efficiency and irreversibility of movements in a city. Scientific reports. 2020 Mar 9;10(1):1-8.

\bibitem{bialek-nc-2001} Bialek W, Nemenman I, Tishby N. Predictability, complexity, and learning. Neural computation. 2001 Nov 1;13(11):2409-63.

\bibitem{samp-ajp-2000} Richman JS, Moorman JR. Physiological time-series analysis using approximate entropy and sample entropy. American Journal of Physiology-Heart and Circulatory Physiology. 2000 Jun 1;278(6):H2039-49.

\bibitem{costa-prl-2002} Costa M, Goldberger AL, Peng CK. Multiscale entropy analysis of complex physiologic time series. Physical review letters. 2002 Jul 19;89(6):068102.

\bibitem{saad1-arxiv-2020} Po HF, Yeung CH, Saad D. The Futility of Being Selfish--The Impact of Selfish Routing on Uncoordinated and Optimized Transportation Networks. arXiv preprint arXiv:2003.06833. 2020 Mar 15.

\bibitem{saad2-arxiv-2020} Li B, Lokhov AY, Saad D. Reducing Urban Traffic Congestion Due To Localized Routing Decisions. arXiv preprint arXiv:2002.10298. 2020 Feb 24.

%\bibitem{glaw-japp-1936} Greenshields BD. Studying traffic capacity by new methods. J. Appl. Psychol. 1936;20(3):353-8.

\end{thebibliography}

\begin{figure}
\includegraphics[width=12cm]{Tday.eps}
\caption{Illustration of the origin to destination trips. (a) In each day, the trips are started from the origins in the time interval $\Delta T_O$ and reach the destinations in the time interval $\Delta T_D(a)$ with travel times $T_{OD}(i)$. (b) The travel times of day $d-1$ are used to find the shortest-time paths in the next day (see the main text).}\label{Tday}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{Ti.eps}
\caption{Cumulative probability distribution of the travel times $\Delta t_{OD}$ in the $M=1.6\times 10^5$ trips. The lattice size is $L=40$ and $\alpha=0$ here.}\label{Ti}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{Pi.eps}
\caption{Mutual information of origin times with destination times $\Pi_{t,t}$ and geometrical distances with travel times $\Pi_{x,t}$. The lattice size is $L=20$, and $\Delta T_O=16$ here. The data are averaged over $1000$ independnet realizations of the population distribution and the movement process.}\label{Pi}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{Rmax_loglog.png}
\caption{Sample entropy vs the scale factor $w$. The lattice size is $L=20$, $\Delta T_O=16$, and $\alpha=0$ here. The data are for a single realization of the population distribution and the movement process.}\label{Sw}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{Ef.eps}
\caption{The efficiency $\eta_{OD}$ vs the disorder parameter $\alpha$. The lattice size is $L=20$, and $\Delta T_O=16$ here. The data are averaged over $1000$ independnet realizations of the population distribution and the movement process. }\label{Ef}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{v.eps}
\caption{The velocity $v_{OD}$ vs the disorder parameter $\alpha$. The lattice size is $L=20$, and $\Delta T_O=16$ here. The data are averaged over $1000$ independnet realizations of the population distribution and the movement process.}\label{v}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{dS.eps}
\caption{The relative entropy $\Delta S_D$ vs the disorder parameter $\alpha$. The lattice size is $L=20$, and $\Delta T_O=16$ here. The data are averaged over $1000$ independnet realizations of the population distribution and the movement process.}\label{dS}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{Lg.eps}
\caption{Size effects with the interaction parameter $g$ for $\lambda=0$. Here $\Delta T_O=16, 24, 32$ for $L=20, 30, 40$, respectively to have the ratio $L/\Delta T_O$ fixed. Also the population density is fixed to $M/N=10^3$. The data are averaged over $1000$ (for $L=20,30$) or $500$ (for $L=40$) independnet realizations of the population distribution and the movement process.}\label{Lg}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{La.eps}
\caption{Size effects with the disorder parameter $\alpha$ for $\lambda=0$. Here $\Delta T_O=16, 24, 32$ for $L=20, 30, 40$, respectively to have the ratio $L/\Delta T_O$ fixed. Also the population density is fixed to $M/N=10^3$. The data are averaged over $1000$ (for $L=20,30$) or $500$ (for $L=40$) independnet realizations of the population distribution and the movement process.}\label{La}
\end{figure}

\begin{figure}
\includegraphics[width=12cm]{L4.eps}
\caption{Behaviour in a larger range of the disorder parameter $\alpha$ for $\lambda=0$. The lattice size is $L=40$, and $\Delta T_O=32$ here. The data are averaged over $500$ independnet realizations of the population distribution and the movement process.}\label{L4}
\end{figure}

\end{document}


%
% CMPT 300: Operating Systems I - A Course Overview
% Section: Memory Management
%
% Author: Jeffrey Leung
%

\section{Memory Management}
	\label{sec:memory-management}
\begin{easylist}

& Code location can be absolute if memory location is known during compile time, or relocatable otherwise

& \textbf{Physical address:} Location in physical memory accessed by the memory unit
& \textbf{Logical/virtual address:} CPU-managed location in memory
	&& Different from physical address if addresses are bound during execution
	&& \textbf{Memory Management Unit (MMU):} Hardware component which maps virtual addresses to physical addresses during runtime
		&&& Ensures separation and protection of memory areas
		&&& Basic components: Base and limit register

\end{easylist}
\subsection{Contiguous Allocation}
	\label{subsec:memory-management:contiguous-allocation}
\begin{easylist}

& Allocation algorithms:
	&& \textbf{First-fit algorithm:} Allocating memory in the first available sufficiently-sized hole
	&& \textbf{Best-fit algorithm:} Allocating memory in the smallest sufficiently-sized hole to create the smallest possible remaining hole
		&&& Requires searching the entire memory space
	&& \textbf{Worst-fit algorithm:} Allocating memory in the largest sufficiently-sized hole to create the largest possible remaining hole
		&&& Requires searching the entire memory space

& \textbf{External fragmentation:} Situation where the memory space exists to fulfill a request but it is not contiguous
	&& \textbf{Memory compaction:} Method to solve external fragmentation which places all free memory together
		&&& Only possible if addresses are bound during execution

\end{easylist}
\subsection{Paging}
	\label{subsec:memory-management:paging}
\begin{easylist}

& \textbf{Page:} Fixed-size, contiguous logical memory unit for non-contiguous memory allocation
	&& \textbf{Frame:} Fixed-size, contiguous physical memory unit for non-contiguous memory allocation
		&&& Associated 1:1 with each page

& Components of addresses:
	&& \textbf{Page number:} Component which contains the base address of a page in physical memory
	&& \textbf{Page offset:} Component which contains an offset of the base address sent to the MMU
	&& For $m, n$ where the address space is $2^m$ and the page size has $2^n$ entries, the number of pages is $\frac{2^m}{2^n} = 2^{m-n}$, the address has $m$ bits, the page number has $m-n$ bits, and the page offset has $n$ bits
	&& Size: Power of 2 (so that the page number and offset can be easily navigated)

& \textbf{Page table:} Set of translations from logical memory to physical memory
	&& Allows partitioning of physical memory and linkage with virtual memory in arbitrary ordering
	&& Specific to each process
	&& Located through the page table base register
	&& Requires two memory accesses (one for page table, one for instruction)
	&& Includes protection bits to specify if a page is read-only/read-write/execute-only, or if a page is valid/invalid access for the process
	&& Diagram: See figure~\ref{fig:paging:page-table-1}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=0.7\textwidth]{page-table-1}
		\caption{Diagram of a Page Table}
		\label{fig:paging:page-table-1}
	\end{figure}

	&& Page table address translation process:
	\end{easylist}
	\begin{align*}
		\textrm{Let } s &= \textrm{ page/frame size }\\
		\textrm{Let } p &= \textrm{ page number }\\
		\textrm{Let } d &= \textrm{ offset}, 0 \leq d < s \\
		\textrm{Logical address } &= p \times s + d \\
		\textrm{Let } f &= \textrm{ frame number translated from } p \textrm{ using page table } \\
		\textrm{Physical address } &= f \times s  + d
	\end{align*}
	\begin{easylist}

		&&& Example:
		\end{easylist}
		\begin{align*}
			\textrm{Page/frame size } s &= 4 \textrm{ bytes} \\
			\textrm{Page table: }
			& 0 \rightarrow 5 \\
			& 1 \rightarrow 6 \\
			& 2 \rightarrow 1 \\
			& 3 \rightarrow 2 \\
			\textrm{Logical address }
			&= 0 \\
			&= p \times s + d \\
			&= 0 \times 4 + 0 \\
			f_{p=0} &= 5 \\
			\textrm{Physical address } &= f \times s + d \\
			&= 5 \times 4 + 0 \\
			&= 20
		\end{align*}
		\begin{easylist}

		&&& Example:
		\end{easylist}
		\begin{align*}
			\textrm{Page/frame size } s &= 4 \textrm{ bytes} \\
			\textrm{Page table: }
			& 0 \rightarrow 5 \\
			& 1 \rightarrow 6 \\
			& 2 \rightarrow 1 \\
			& 3 \rightarrow 2 \\
			\textrm{Logical address }
			&= 13 \\
			&= p \times s + d \\
			&= 3 \times 4 + 1 \\
			f_{p=3} &= 2 \\
			\textrm{Physical address } &= f \times s + d \\
			&= 2 \times 4 + 1 \\
			&= 9
		\end{align*}
		\begin{easylist}

& \textbf{Translation Look-aside Buffer (TLB):} Fast-lookup associative memory structure which stores recently used page table entries
	&& \textbf{Address Space Identifier:} Component of a TLB entry containing a process ID for protection
	&& Common across processes
	&& If the page is not found, the page table is used and the entry is added to the TLB
		&&& Some TLB entries are fixed and cannot be replaced (e.g. kernel codes)
	&& Diagram: See figure~\ref{fig:paging:page-table-2-tlb}

	\begin{figure}[!htb]
		\centering
		\includegraphics[width=0.7\textwidth]{page-table-2-tlb}
		\caption{Diagram of a TLB}
		\label{fig:paging:page-table-2-tlb}
	\end{figure}

& \textbf{Effective Access Time:} Amortized time for TLB lookup and page table access
	&& TLB hit ratio is proportional to the effective access time between the time for 1 memory access and the time for 2 memory accesses
	&& Equation:
	\end{easylist}
	\begin{align*}
		\textrm{ Let } t_m &= \textrm{ memory access time} \\
		\textrm{ Let } \varepsilon &= \textrm{ TLB lookup time (significantly less than } t_m \textrm{)} \\
		\textrm{ Let } \alpha &= \textrm{ TLB hit ratio (percentage of times page found in TLB)} \\
		\textrm{Effective Access Time }
		&= \textrm{ Time for TLB hit } \times \textrm{ TLB hit percentage } + \\
		& \textrm{ Time for TLB miss } \times \textrm{ TLB miss percentage } \\
		&= (\varepsilon + t_m) \times \alpha + (\varepsilon + 2 \times t_m) \times (1 - \alpha) \\
		&= \varepsilon + t_m \times (2 - \alpha) \\
	\end{align*}
	\begin{easylist}

		&&& Example:
		\end{easylist}
		\begin{align*}
			\textrm{ Let } t_m &= 100 \textrm{ ns} \\
			\textrm{ Let } \varepsilon &= 0 \\
			\textrm{ Let } \alpha &= 0.8 \\
			\textrm{Effective Access Time }
			&= \varepsilon + t_m \times (2 - \alpha) \\
			&= 100 \textrm{ ns } \times (2 - 0.8) \\
			&= 120 \textrm{ ns} \\
			\textrm{Slowdown } &= \frac{100 \textrm{ ns}}{120 \textrm{ ns}} - 1 = 20\% \\
		\end{align*}
		\begin{easylist}

		&&& Example:
		\end{easylist}
		\begin{align*}
			\textrm{ Let } t_m &= 100 \textrm{ ns} \\
			\textrm{ Let } \varepsilon &= 0 \\
			\textrm{ Let } \alpha &= 0.99 \\
			\textrm{Effective Access Time }
			&= \varepsilon + t_m \times (2 - \alpha) \\
			&= 100 \textrm{ ns } \times (2 - 0.99) \\
			&= 101 \textrm{ ns} \\
			\textrm{Slowdown } &= \frac{100 \textrm{ ns}}{101 \textrm{ ns}} - 1 = 1\% \\
		\end{align*}
		\begin{easylist}

& \textbf{Reentrant code:} Read-only code shared among multiple processes
	&& Must appear in the same location in the logical address spaces due to processes sharing a TLB

& Page table structural alternatives:
	&& Page table requires contiguous memory or the page table will need to be paged itself
	&& For an address space of $32$ bits and a page size of $4$ KB ($2^{12}$ bytes), a process could have $2^{32-12} = 2^{20}$ pages; for a page table with entries of $4$ bytes, the size of a page table for each process could be $2^{20} \times 4 = 2^{22} $ bytes $ = 4$ MB which is very large

	&& \textbf{Hierarchical page table:} Method to make page tables less contiguous in memory by paging a page table through partitioning the page table
		&&& Requires additional memory accesses
		&&& Diagram: See figure~\ref{fig:paging:page-table-3-hierarch}
		&&& Diagram of access: See figure~\ref{fig:paging:page-table-4-hierarch-access}

		\begin{figure}[!htb]
			\centering
			\includegraphics[width=0.7\textwidth]{page-table-3-hierarch}
			\caption{Diagram of a Hierarchical Page Table}
			\label{fig:paging:page-table-3-hierarch}
		\end{figure}
		&&& Diagram: See figure~\ref{fig:paging:page-table-3-hierarch}

		\begin{figure}[!htb]
			\centering
			\includegraphics[width=0.7\textwidth]{page-table-4-hierarch-access}
			\caption{Accessing a Hierarchical Page Table}
			\label{fig:paging:page-table-4-hierarch-access}
		\end{figure}

	&& \textbf{Hashed page table:} Method to store page table entries non-contiguously by hashing page number to a linked list of elements, each with a page number and associated frame number
		&&& Diagram: See figure~\ref{fig:paging:page-table-6-inverted}

		\begin{figure}[!htb]
			\centering
			\includegraphics[width=0.7\textwidth]{page-table-6-inverted}
			\caption{Diagram of an Inverted Page Table}
			\label{fig:paging:page-table-6-inverted}
		\end{figure}

	&& \textbf{Inverted page table:} Method to use only one page table for all processes by using a table of page numbers (limited by amount of frames) and the process which owns the frame
		&&& Increases time to find a page reference
		&&& Creates difficulty in implementing a shared page

& \textbf{Internal fragmentation:} Situation where memory allocated as a fixed-size partition is larger than required which creates unusable excess memory

\end{easylist}
\subsection{Segmentation}
	\label{subsec:memory-management:segmentation}
\begin{easylist}

& \textbf{Segment:} Component of a program (e.g. function, object, main program)
	&& Segments are paged to avoid external fragmentation so the user interacts with the segments and the OS interacts with the pages

& \textbf{Segment table:} Structure which maps a logical address to a physical address using a base address and limit

\end{easylist}
\clearpage