ipfs-cap2pfs.tex 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  1. \documentclass{sig-alternate}
  2. \usepackage{tikz}
  3. \usetikzlibrary{arrows}
  4. \usetikzlibrary{trees}
  5. \usetikzlibrary{positioning}
  6. \usepackage{array}
  7. \usepackage{amstext}
  8. \usepackage{mathtools}
  9. \DeclarePairedDelimiter{\ceil}{\lceil}{\rceil}
  10. \begin{document}
  11. \title{IPFS - Content Addressed, Versioned, P2P File System (DRAFT 2)}
  12. \subtitle{}
  13. \numberofauthors{1}
  14. \author{
  15. \alignauthor
  16. Juan Benet\\
  17. \email{juan@benet.ai}
  18. }
  19. \maketitle
  20. \begin{abstract}
  21. The InterPlanetary File System is a peer-to-peer distributed file system
  22. capable of sharing the same files with millions of nodes. IPFS combines a
  23. distributed hashtable, cryptographic techniques, merkle trees, content-
  24. addressable storage, bittorrent, and tag-based filesystems to build a single
  25. massive file system shared between peers. IPFS has no single point of failure,
  26. and nodes do not need to trust each other.
  27. \end{abstract}
  28. \section{Introduction}
  29. [Motivate IPFS. Introduce problems. Describe BitTorrent existing problems (
  30. multiple files. one swarm. sloppy dht implementation.) Describe version
  31. control efforts. Propose potential combinations of good ideas.]
  32. [Cite:
  33. CFS,
  34. Kademlia,
  35. Bittorrent,
  36. Chord,
  37. DHash,
  38. SFS,
  39. Ori,
  40. Coral]
  41. This paper introduces
  42. IPFS, a novel peer-to-peer version-controlled filesystem;
  43. and BitSwap, the novel peer-to-peer block exchange protocol serving IPFS.
  44. %The rest of the paper is organized as follows.
  45. %Section 2 describes the design of the filesystem.
  46. %Section 3 evaluates various facets of the system under benchmark and common
  47. %workloads.
  48. %Section 4 presents and evaluates a world-wide deployment of IPFS.
  49. %Section 5 describes existing and potential applications of IPFS.
  50. %Section 6 discusses related and future work.
  51. Notation Notes:
  52. (a) data structures are specified in Go syntax,
  53. (b) rpc protocols are specified in capnp interfaces,
  54. (c) wire protocols are specified in capnp schemas.
  55. \section{Background}
  56. This section reviews important properties of successful peer-to-peer systems, which IPFS combines.
  57. \subsection{Distributed Hash Tables}
  58. Distributed Hash Tables (DHTs) are widely used to coordinate and maintain metadata about peer-to-peer systems. For example, the BitTorrent MainlineDHT tracks sets of peers part of a torrent swarm.
  59. \subsubsection{Kademlia DHT}
  60. Kademlia \cite{Kademlia} is a popular DHT that provides:
  61. \begin{enumerate}
  62. \item Efficient lookup through massive networks:
  63. queries on average contact $ \ceil{log_2 (n)} $ nodes.
  64. (e.g. $20$ hops for a network of $10,000,000$ nodes).
  65. \item Low coordination overhead: it optimizes the number of
  66. control messages it sends to other nodes.
  67. \item Resistance to various attacks, by preferring nodes who have been
  68. part of the DHT longer.
  69. \item wide useage in peer-to-peer applications, including \\
  70. Gnutella and Bittorrent, forming networks of over 100 million nodes.
  71. \end{enumerate}
  72. \subsubsection{Coral DSHT}
  73. While some peer-to-peer filesystems store data blocks directly in DHTs,
  74. this ``wastes storage and bandwidth, as data must be stored at nodes where it
  75. is not needed'' \cite{Coral}. Coral extends Kademlia in three particularly important ways:
  76. \begin{enumerate}
  77. \item Kademlia stores values in nodes whose ids are ``nearest'' (using
  78. XOR-distance) to the key. This does not take into account application
  79. data locality, ignores ``far'' nodes who may already have the data, and
  80. forces ``nearest'' nodes to store it, whether they need it or not.
  81. This wastes significant storage and bandwith. Instead, Coral stores
  82. addresses to peers who can provide the data blocks.
  83. \item Coral relaxes the DHT API from \texttt{get\_value(key)} to
  84. \texttt{get\_any\_values(key)} (the ``sloppy'' in DSHT).
  85. This still works since Coral users only need a single (working) peer,
  86. not the complete list. In return, Coral can distribute only subsets of
  87. the values to the ``nearest'' nodes, avoiding hot-spots (overloading
  88. \textit{all the nearest nodes} when a key becomes popular).
  89. \item Additionally, Coral organizes a hierarchy of separate DSHTs called
  90. \textit{clusters} depending on region and size. This enables nodes to
  91. query peers in their region first, ``finding nearby data without
  92. querying distant nodes'' and greatly reducing the latency of
  93. lookups.
  94. \end{enumerate}
  95. \subsubsection{S/Kademlia DHT}
  96. S/Kademlia extends Kademlia to protect against malicious attacks:
  97. \begin{enumerate}
  98. \item S/Kademlia provides schemes to secure \texttt{NodeId} generation,
  99. and prevent Sybill attacks. It requires nodes to create a PKI key pair, derive their identity from it, and sign their messages to each other. One scheme includes a proof-of-work crypto puzzle to make generating Sybills expensive.
  100. \item S/Kademlia nodes lookup values over disjoint paths, in order to
  101. ensure honest nodes can connect to each other in the presence of a large fraction of adversaries in the network. S/Kademlia achieves a success rate of 0.85 even with an adversarial fraction as large as half of the nodes.
  102. \end{enumerate}
  103. \subsection{Block Exchanges - BitTorrent}
  104. BitTorrent \cite{BitTorrent} is a widely successful peer-to-peer filesharing system, which succeeds in coordinating networks of untrusting peers (swarms) to cooperate in distributing pieces of files to each other. Key BitTorrent features that inform IPFS design:
  105. \begin{enumerate}
  106. \item BitTorrent's data exchange protocol uses a quasi tit-for-tat strategy
  107. which rewards nodes that contribute to each other, and punishes nodes who would only leech others' resources.
  108. \item BitTorrent peers track the availability of file pieces, prioritizing
  109. sending rarest-first. This takes load off seeds, making non-seed peers capable of trading with each other.
  110. \item BitTorrent's standard tit-for-tat is vulnerable to some exploitative
  111. bandwidth sharing strategies. PropShare \cite{propshare} is a different peer bandwidth allocation strategy that better resists exploitative strategies, and improves the performance of swarms.
  112. \end{enumerate}
  113. \subsection{Version Control Systems - Git}
  114. Version Control Systems provide facilities to model files changing over time and distribute different versions efficiently. The popular version control system Git provides a powerful Merkle DAG \footnote{Merkle Directed Acyclic Graph -- similar but more general construction than a Merkle Tree. Deduplicated, does not need to be balanced, and non-leaf nodes contain data.} object model that captures changes to a filesystem tree in a distributed-friendly way.
  115. \begin{enumerate}
  116. \item Immutable objects represent Files (\texttt{blob}), Directories (\texttt{tree}), and Changes (\texttt{commit}).
  117. \item Objects are content-addressed, by the cryptographic hash of their contents.
  118. \item Links to other objects are embedded, forming a Merkle DAG. This
  119. provides many useful integrity and workflow properties.
  120. \item Most versioning metadata (branches, tags, etc) are simply pointer references, and thus inexpensive to create and update.
  121. \item Version changes only update references or add objects.
  122. \item Distributing version changes to other users is simply transferring objects and updating remote references.
  123. \end{enumerate}
  124. \section{Design}
  125. IPFS is a distributed file system which synthesizes successful ideas from previous peer-to-peer sytems, including DHTs, BitTorrent, Git, and SFS. The contribution of IPFS is simplifying, evolving, and connecting proven techniques into a single cohesive system, greater than the sum of its parts. IPFS presents a new platform for writing and deploying applications, a new system for distributing and versioning large data, and could evolve the web itself.
  126. IPFS is peer-to-peer; no nodes are privileged. IPFS nodes store IPFS objects in local storage. Nodes connect to each other and transfer objects. These objects represent files and other data structures. The IPFS Protocol is divided into a stack of sub-protocols responsible for different functionality:
  127. \begin{enumerate}
  128. \item \textbf{Identities} - manages node identity generation and verification. Described in Section 3.1.
  129. \item \textbf{Network} - manages connections to other peers, using various underlying network protocols. Configurable. Described in Section 3.2.
  130. \item \textbf{Routing} - maintains information to locate specific peers and objects. Responds to both local and remote queries. Defaults to a DHT, but is swappable. Described in Section 3.3.
  131. \item \textbf{Exchange} - a novel block exchange protocol (BitSwap) that governs efficient block distribution. Modelled as a market, weakly intentivizes replication. Trade Strategies swappable. Described in Section 3.4.
  132. \item \textbf{Objects} - a Merkle DAG of content-addressed immutable objects with links. Used to represent arbitrary datastructures, e.g. file hierarchies and communication systems. Described in Section 3.5.
  133. \item \textbf{Files} - versioned file system hierarchy, inspired by Git. Described in Section 3.6.
  134. \item \textbf{Naming} - A self-certifying mutable name system. Described in Section 3.7.
  135. \end{enumerate}
  136. These subsystems are not independent; they are integrated and leverage
  137. blended properties. However, it is useful to describe them separately,
  138. building the protocol stack from the bottom up.
  139. \subsection{Identities}
  140. Nodes are identified by a \texttt{NodeId}, the cryptographic hash\footnote{throughout this document, \textit{hash} and \textit{checksum} refer specifically to cryptographic hash checksums of data} of a public-key, created as in \cite{skademlia}. Nodes store their public and private keys (encrypted with a passphrase). Users are free to instatiate a ``new'' node identity on every launch, though that loses accrued network benefits. Nodes are incentivized to remain the same.
  141. \begin{verbatim}
  142. type NodeId Multihash
  143. type Multihash []byte
  144. // self-describing cryptographic hash digest
  145. type PublicKey []byte
  146. type PrivateKey []byte
  147. // self-describing keys
  148. type Node struct {
  149. nodeid NodeID
  150. pubkey PublicKey
  151. prikey PrivateKey
  152. }
  153. \end{verbatim}
  154. Upon first connecting, peers exchange public keys, and check: \texttt{hash(other.PublicKey) equals other.NodeId}. If not, the connection is terminated.
  155. \paragraph{Note on Cryptographic Functions} Rather than locking the system to a particular set of function choices, IPFS favors self-describing values. Hash digest values are ``multihashes'', a format including a short header identifying the hash function used, and the digest length in bytes. Example:
  156. \begin{verbatim}
  157. <function code><digest length><digest bytes>
  158. \end{verbatim}
  159. This allows the system (a) chose the best function for the use case (e.g. stronger security vs faster performance), and (b) evolve as function choices change. Self-describing values allow using different parameter choices compatibly.
  160. \subsection{Network}
  161. IPFS nodes communicate regualarly with hundreds of other nodes in the network, across the wide internet. IPFS can use any reliable transport protocol, and is best suited for WebRTC DataChannels \cite{WebRTC} (for browser connectivity) or uTP \cite{uTP} (LEDBAT) \cite{LEDBAT}. IPFS also uses the ICE NAT traversal techniques \cite{ICE} to increase connectivity between peers.
  162. \begin{itemize}
  163. \item \textbf{Reliability:} IPFS can provide reliability if underlying networks do not provide it, using uTP or SCTP.
  164. \item \textbf{Integrity:} optionally checks integrity of messages using a hash checksum.
  165. \item \textbf{Authenticity:} optionally checks authenticity of messages using HMAC with sender's public key.
  166. \end{itemize}
  167. \subsection{Routing}
  168. IPFS nodes require a routing system that can find (a) other peers' network addresses and (b) peers who can serve particular objects. IPFS achieves this using a DSHT based on S/Kademlia and Coral, using the properties discussed in 2.1. The size of objects and use patterns of IPFS are similar to Coral \cite{Coral} and Mainline \cite{Mainline}, so references are stored in the DHT instead of entire blocks. References are the \texttt{NodeIds} of peers who can serve the block.
  169. The interface of this DSHT is:
  170. \begin{verbatim}
  171. routing.findPeer(NodeId)
  172. // gets a particular peer's network address
  173. routing.findValuePeers(Multihash, int)
  174. // gets a number of peers serving a value.
  175. routing.provideValue(Multihash)
  176. // announces that this node can serve a value.
  177. \end{verbatim}
  178. Note: different use cases will call for substantially different routing systems (e.g. DHT in wide network, static HT in local network). Thus the IPFS routing system can be swapped for one to fit the users' needs. As long as the interface above is met, the rest of the system will continue to function.
  179. \subsection{Block Exchange - BitSwap Protocol}
  180. The exchange of data in IPFS happens by exchanging blocks with peers using a
  181. BitTorrent inspired protocol: BitSwap. Like BitTorrent, BitSwap peers are
  182. looking to acquire a set of blocks, and have blocks to offer in exchange.
  183. Unlike BitTorrent, BitSwap is not limited to the blocks in one torrent.
  184. BitSwap operates as a persistent marketplace where node can acquire the
  185. blocks they need, regardless of what files the blocks are part of. The
  186. blocks could come from completely unrelated files in the filesystem.
  187. But nodes come together to barter in the marketplace.
  188. While the notion of a barter system implies a virtual currency could be
  189. created, this would require a global ledger to track ownership
  190. and transfer of the currency. This can be implemented as a BitSwap Strategy, and will be explored in a future paper.
  191. In the base case, BitSwap nodes have to provide direct value to each other
  192. in the form of blocks. This works fine when the distribution of blocks across
  193. nodes is such that they have complements, what each other wants. This will
  194. seldom be the case. Instead, it is more likely that nodes must \textit{work}
  195. for their blocks. In the case that a node has nothing that its peers want (or
  196. nothing at all), it seeks the pieces its peers want, with lower
  197. priority than what the node wants itself. This incentivizes nodes to cache and
  198. disseminate rare pieces, even if they are not interested in them directly.
  199. \subsubsection{BitSwap Credit}
  200. The protocol must also incentivize nodes to seed when they do not need
  201. anything in particular, as they might have the blocks others want. Thus,
  202. BitSwap nodes send blocks to their peers optimistically, expecting the debt to
  203. be repaid. But, leeches (free-loading nodes that never share) must be protected against. A simple credit-like system solves the problem:
  204. \begin{enumerate}
  205. \item Peers track their balance (in bytes verified) with other nodes.
  206. \item Peers send blocks to debtor peers probabilistically, according to
  207. a function that falls as debt increases.
  208. \end{enumerate}
  209. Note that if a peer decides not to send, the peer subsequently ignores the
  210. other node for an \texttt{ignore\_cooldown} timeout. This prevents senders
  211. from trying to game the probability by just causing more dice-rolls.
  212. (Default BitSwap is 10 seconds).
  213. \subsubsection{BitSwap Strategy}
  214. The differing strategies that BitSwap peers might employ have wildly different effects on the performance of the exchange as a whole. In BitTorrent, while a standard strategy is specified (tit-for-tat), a variety of others have been implemented, ranging from BitTyrant \cite{BitTyrant} (sharing the least-possible), to BitThief \cite{BitThief} (exploiting a vulnerability and never share), to PropShare \cite{PropShare} (sharing proportionally). A range of strategies (good and malicious) could similarly be implemented by BitSwap peers. The choice of function, then, should aim to:
  215. \begin{enumerate}
  216. \item maximize the trade performance for the node, and the whole exchange
  217. \item prevent freeloaders from exploiting and degrading the exchange
  218. \item be effective with and resistant to other, unknown
  219. strategies
  220. \item be lenient to trusted peers
  221. \end{enumerate}
  222. The exploration of the space of such strategies is future work.
  223. One choice of function that works in practice is a sigmoid, scaled by a
  224. \textit{debt retio}:
  225. Let the \textit{debt ratio} $ r $ between a node and its peer be:
  226. \[ r = \dfrac{\texttt{bytes\_sent}}{\texttt{bytes\_recv} + 1} \]
  227. Given $r$, let the probability of sending to a debtor be:
  228. \[ P\Big( \; send \; | \; r \;\Big) = 1 - \dfrac{1}{1 + exp(6-3r)} \]
  229. \begin{figure}
  230. \centering
  231. \begin{tikzpicture}[domain=0:4]
  232. \draw[->] (-0,0) -- (4.2,0) node[right] {$r$};
  233. \draw[->] (0,-0) -- (0,1.20) node[above] {$P(\;send\;|\;r\;)$};
  234. %ticks
  235. \foreach \x in {0,...,4}
  236. \draw (\x,1pt) -- (\x,-3pt)
  237. node[anchor=north] {\x};
  238. \foreach \y in {1,...,1}
  239. \draw (1pt,\y) -- (-3pt,\y)
  240. node[anchor=east] {\y};
  241. \draw[color=red] plot[] function{1 - 1/(1+exp(6-3*x))};
  242. \end{tikzpicture}
  243. \caption{Probability of Sending as $r$ increases}
  244. \label{fig:psending-graph}
  245. \end{figure}
  246. As you can see in Figure \ref{fig:psending-graph}, this function drops off quickly as the nodes' \
  247. \textit{debt ratio} surpasses twice the established credit.
  248. The \textit{debt ratio} is a measure of trust:
  249. lenient to debts between nodes that have previously exchanged lots of data
  250. successfully, and merciless to unknown, untrusted nodes. This
  251. (a) provides resistance to attackers who would create lots of new nodes
  252. (sybill attacks),
  253. (b) protects previously successful trade relationships, even if one of the
  254. nodes is temporarily unable to provide value, and
  255. (c) eventually chokes relationships that have deteriorated until they
  256. improve.
  257. % \begin{center}
  258. % \begin{tabular}{ >{$}c<{$} >{$}c<{$}}
  259. % P(\;send\;|\quad r) \;\;\;\;\;& \\
  260. % \hline
  261. % \hline
  262. % P(\;send\;|\;0.0) =& 1.00 \\
  263. % P(\;send\;|\;0.5) =& 1.00 \\
  264. % P(\;send\;|\;1.0) =& 0.98 \\
  265. % P(\;send\;|\;1.5) =& 0.92 \\
  266. % P(\;send\;|\;2.0) =& 0.73 \\
  267. % P(\;send\;|\;2.5) =& 0.38 \\
  268. % P(\;send\;|\;3.0) =& 0.12 \\
  269. % P(\;send\;|\;3.5) =& 0.03 \\
  270. % P(\;send\;|\;4.0) =& 0.01 \\
  271. % P(\;send\;|\;4.5) =& 0.00 \\
  272. % \end{tabular}
  273. % \end{center}
  274. % TODO look into computing share of the bandwidth, as described in propshare.
  275. \subsubsection{BitSwap Ledger}
  276. BitSwap nodes keep ledgers accounting the transfers with other nodes. This allows nodes to keep track of history, and to avoid tampering. When activating a connection, BitSwap nodes exchange their ledger information. If it does not match exactly, the ledger is reinitialized from scratch, loosing the accrued credit or debt. It is possible for malicious nodes to purposefully ``loose'' the Ledger, hoping the erase debts. It is unlikely that nodes will have accrued enough debt to warrant also losing the accrued trust, however the partner node is free to count it as \textit{misconduct} (discussed later).
  277. \begin{verbatim}
  278. type Ledger struct {
  279. owner NodeId
  280. partner NodeId
  281. bytes_sent int
  282. bytes_recv int
  283. timestamp Timestamp
  284. }
  285. \end{verbatim}
  286. Nodes are free to keep the ledger history, though it is not necessary for
  287. correct operation. Only the current ledger entries are useful. Nodes are
  288. also free to garbage collect ledgers as necessary, starting with the less
  289. useful ledgers: the old (peers may not exist anymore) and small.
  290. \subsubsection{BitSwap Specification}
  291. BitSwap nodes follow a simple protocol.
  292. \begin{verbatim}
  293. // Additional state kept
  294. type BitSwap struct {
  295. ledgers map[NodeId]Ledger
  296. // Ledgers known to this node, inc inactive
  297. active map[NodeId]Peer
  298. // currently open connections to other nodes
  299. need_list []Multihash
  300. // checksums of blocks this node needs
  301. have_list []Multihash
  302. // checksums of blocks this node has
  303. }
  304. type Peer struct {
  305. nodeid NodeId
  306. ledger Ledger
  307. // Ledger between the node and this peer
  308. last_seen Timestamp
  309. // timestamp of last received message
  310. want_list []Multihash
  311. // checksums of all blocks wanted by peer
  312. // includes blocks wanted by peer's peers
  313. }
  314. // Protocol interface:
  315. interface Peer {
  316. open (nodeid :NodeId, ledger :Ledger);
  317. send_want_list (want_list :WantList);
  318. send_block (block :Block) -> (complete :Bool);
  319. close (final :Bool);
  320. }
  321. \end{verbatim}
  322. Sketch of the lifetime of a peer connection:
  323. \begin{enumerate}
  324. \item Open: peers send \texttt{ledgers} until they agree.
  325. \item Sending: peers exchange \texttt{want\_lists} and \texttt{blocks}.
  326. \item Close: peers deactivate a connection.
  327. \item Ignored: (special) a peer is ignored (for the duration of a timeout)
  328. if a node's strategy avoids sending
  329. \end{enumerate}
  330. \paragraph{Peer.open(NodeId, Ledger)}
  331. When connecting, a node initializes a connection with a
  332. \texttt{Ledger}, either stored from a connection in the past or a new one
  333. zeroed out. Then, sends an Open message with the \texttt{Ledger} to the peer.
  334. Upon receiving an \texttt{Open} message, a peer chooses whether to activate
  335. the connection. If -- acording to the receiver's \texttt{Ledger} -- the sender
  336. is not a trusted agent (transmission below zero, or large outstanding debt) the
  337. receiver may opt to ignore the request. This should be done probabilistically
  338. with an \texttt{ignore\_cooldown} timeout, as to allow errors to be corrected
  339. and attackers to be thwarted.
  340. If activating the connection, the receiver initializes a Peer object, with the
  341. local version of the \texttt{Ledger}, and setting the \texttt{last\_seen}
  342. timestamp). Then, it compares the received
  343. \texttt{Ledger} with its own. If they match exactly, the connections have
  344. opened. If they do not match, the peer creates a new zeroed out
  345. \texttt{Ledger}, and sends it.
  346. \paragraph{Peer.send\_want\_list(WantList)}
  347. While the connection is open, nodes advertise their
  348. \texttt{want\_list} to all connected peers. This is done (a) upon opening the
  349. connection, (b) after a randomized periodic timeout, (c) after a change in
  350. the \texttt{want\_list} and (d) after receiving a new block.
  351. Upon receiving a \texttt{want\_list}, a node stores it. Then, it checks whether
  352. it has any of the wanted blocks. If so, it sends them according to the
  353. \textit{BitSwap Strategy} above.
  354. \paragraph{Peer.send\_block(Block)}
  355. Sending a block is straightforward. The node simply transmits the block of
  356. data. Upon receiving all the data, the receiver computes the Multihash
  357. checksum to verify it matches the expected one, and returns confirmation.
  358. Upon finalizing the correct transmission of a block, the receiver moves the
  359. block from \texttt{need\_list} to \texttt{have\_list}, and both the receiver
  360. and sender update their ledgers to reflect the additional bytes transmitted.
  361. If a transmission verfication fails, the receiver instead \textit{penalizes}
  362. the sender. Both receiver and sender should update their ledgers accordingly,
  363. though the sender is either malfunctioning or attacking the receiver. Note that
  364. BitSwap expects to operate on a reliable transmission channel, so data errors
  365. -- which could lead to incorrect penalization of an honest sender -- are
  366. expected to be caught before the data is given to BitSwap. IPFS uses the uTP
  367. protocol.
  368. \paragraph{Peer.close(Bool)}
  369. The \texttt{final} parameter to \texttt{close} signals whether the intention
  370. to tear down the connection is the sender's or not. If false, the receiver
  371. may opt to re-open the connection immediatelty. This avoids premature
  372. closes.
  373. A peer connection should be closed under two conditions:
  374. \begin{itemize}
  375. \item a \texttt{silence\_wait} timeout has expired without receiving any
  376. messages from the peer (default BitSwap uses 30 seconds).
  377. The node issues \texttt{Peer.close(false)}.
  378. \item the node is exiting and BitSwap is being shut down.
  379. In this case, the node issues \texttt{Peer.close(true)}.
  380. \end{itemize}
  381. After a \texttt{close} message, both receiver and sender tear down the
  382. connection, clearing any state stored. The \texttt{Ledger} may be stored for
  383. the future, if it is useful to do so.
  384. \paragraph{Notes}
  385. \begin{itemize}
  386. \item Non-\texttt{open} messages on an inactive connection should be ignored.
  387. In case of a \texttt{send\_block} message, the receiver may check
  388. the block to see if it is needed and correct, and if so, use it.
  389. Regardless, all such out-of-order messages trigger a
  390. \texttt{close(false)} message from the receiver, to force
  391. re-initialization of the connection.
  392. \end{itemize}
  393. % TODO: Rate Limiting / Node Silencing
  394. \subsection{Object Merkle DAG}
  395. The DHT and BitSwap allow IPFS to form a massive peer-to-peer system for storing and distributing blocks quickly and robustly to users. On top of these, IPFS builds a Merkle DAG, a directed acyclic graph where links between objects are cryptographic hashes of the targets embedded in the sources. This is a generalization of which the Git data structure is a special case, and upon which it can be built. Merkle DAGs provide IPFS many useful properties, including:
  396. \begin{enumerate}
  397. \item \textbf{Content Addressing:} all content is uniquely identified by its
  398. \texttt{multihash} checksum, \textbf{including links}.
  399. \item \textbf{Tamper resistance:} all content is verified with its checksum.
  400. If data is tampered with or corrupted, IPFS detects it.
  401. \item \textbf{Deduplication:} all objects who hold the exact same content
  402. are equal, and only stored once. This is particularly useful with
  403. index objects, such as git \texttt{trees} and \texttt{commits}, or common portions of data.
  404. \end{enumerate}
  405. The IPFS Object format is:
  406. \begin{verbatim}
  407. type IPFSLink struct {
  408. Name string
  409. // name or alias of this link
  410. Hash Multihash
  411. // cryptographic hash of target
  412. Size int
  413. // total size of target
  414. }
  415. type IPFSObject struct {
  416. links []IPFSLink
  417. // array of links
  418. data []byte
  419. // opaque content data
  420. }
  421. \end{verbatim}
  422. The IPFS Merkle DAG is an extremely flexible way to store data. The only requirements are that object references be (a) content addressed, and (b) encoded in the format above. IPFS grants applications complete control over the data field; applications can use any custom data format they chose, which IPFS may not understand. The separate in-object link table allows IPFS to:
  423. \begin{itemize}
  424. \item List all object references in an object. For example:
  425. \begin{verbatim}
  426. > ipfs ls /XLaoVHd834v62UsW56jew8Mp6FgZBXnZEeL
  427. XLMLiUaCc7jh3eGFsNR8AhvRSSFySSvTaNb 47 bam
  428. XLMCA8WXBNRBwFhzRnHgHFLwGmQzkAQELH7 6 bar
  429. XLM1ZETht3wv8vUPXMkx3JZGP5T9txAz782 6 baz
  430. <object multihash> <object size> <link name>
  431. \end{verbatim}
  432. \item Resolve string path lookups, such as \texttt{foo/bar/baz}. Given an object, IPFS resolves the first path component to a hash in the object's link table, fetching that second object, and repeats with the next component. Thus, string paths can walk the Merkle DAG no matter what the data formats are.
  433. \item Resolve all objects referenced recursively:
  434. \begin{verbatim}
  435. > ipfs refs --recursive \
  436. /XLZ1625Jjn7SubMDgEyeaynFuR84ginqvzb
  437. XLLxhdgJcXzLbtsLRL1twCHA2NrURp4H38s
  438. XLYkgq61DYaQ8NhkcqyU7rLcnSa7dSHQ16x
  439. XLHBNmRQ5sJJrdMPuu48pzeyTtRo39tNDR5
  440. XLWVQDqxo9Km9zLyquoC9gAP8CL1gWnHZ7z
  441. ...
  442. \end{verbatim}
  443. \end{itemize}
  444. A raw data field and a common link structure are the necessary components for constructing arbitrary data structures on top of IPFS. While it is easy to see how the Git object model fits on top of this DAG, consider these other potential data structures:
  445. (a) key-value stores
  446. (b) traditional relational databases
  447. (c) Linked Data triple stores
  448. (d) linked document publishing systems
  449. (e) linked communications platforms
  450. (f) cryptocurrency blockchains.
  451. These can all be modeled on top of the IPFS Merkle DAG, which allows any of these systems to use IPFS as a transport protocol for more complex applications.
  452. \subsubsection{Object-level Cryptoraphy}
  453. IPFS is equipped to handle object-level cryptographic operations. An encrypted or signed object is wrapped in a special frame that allows encryption or verification of the raw bytes.
  454. \begin{verbatim}
  455. type EncryptedObject struct {
  456. Object []bytes
  457. // raw object data encrypted
  458. Tag []bytes
  459. // optional tag for encryption groups
  460. }
  461. type SignedObject struct {
  462. Object []bytes
  463. // raw object data signed
  464. Signature []bytes
  465. // hmac signature
  466. PublicKey []multihash
  467. // multihash identifying key
  468. }
  469. \end{verbatim}
  470. Note this changes the object's hash (defining a different object, as it should). Also, IPFS automatically verifies signatures and can decrypt data with user-specified keychains.
  471. \subsection{Files}
  472. IPFS defines a set of objects to build a versioned filesystem on top of the
  473. MerkleDAG, constructing files and directories out of Objects.
  474. Files in IPFS are represented as a collection of inter-related objects, like in
  475. the version control system Git. Each object is addressed by the cryptographic
  476. hash of its contents (\texttt{Checksum}). The file objects are:
  477. \begin{enumerate}
  478. \item \texttt{block}: a variable-size block of data.
  479. \item \texttt{list}: a collection of blocks or other lists.
  480. \item \texttt{tree}: a collection of blocks, lists, or other trees.
  481. \item \texttt{commit}: a snapshot in the version history of a tree.
  482. \end{enumerate}
  483. We hoped to use the Git object formats exactly, but had to depart to introduce
  484. certain features useful in a distributed filesystem, for example fast size
  485. lookups (aggregate byte sizes have been added to objects), large file
  486. deduplication and versioning (adding a \texttt{list} object), and more.
  487. However, our objects are perfectly compatible with Git and
  488. conversion between the two does not lose any information.
  489. Notes:
  490. \begin{itemize}
  491. \item \texttt{varint} is a variable size int, as in protocol-buffers.
  492. \item objects are serialized using \texttt{capnp}.
  493. \end{itemize}
  494. \subsubsection{Block Object}
  495. The \texttt{Block} object contains an addressable unit of data, and
  496. represents a file.
  497. IPFS Blocks are like Git blobs or filesystem data blocks. They store the
  498. users' data. (The name \textit{block} is preferred over \textit{blob}, as the
  499. Git-inspired view of a \textit{blob} as a \textit{file} breaks down in IPFS.
  500. IPFS files can be represented by both \texttt{lists} and \texttt{blocks}.)
  501. Format:
  502. \begin{verbatim}
  503. block <size>
  504. <block data bytes>
  505. ...
  506. \end{verbatim}
  507. \subsubsection{List Object}
  508. The \texttt{List} object represents a large or de-duplicated file made up of
  509. several IPFS \texttt{Blocks} concatenated together. \texttt{Lists} contain
  510. an ordered sequence of \texttt{block} or \texttt{list} objects.
  511. In a sense, the IPFS \texttt{List} functions like a filesystem file with
  512. indirect blocks. Since \texttt{lists} can contain other \texttt{lists}, topologies including linked lists and balanced trees are possible. Directed graphs where the same node appears in multiple places allow in-file deduplication. Cycles are not possible (enforced by hash addessing).
  513. Format:
  514. \begin{verbatim}
  515. list <num objects> <size varint>
  516. <list or block> <checksum> <size varint>
  517. <list or block> <checksum> <size varint>
  518. ...
  519. \end{verbatim}
  520. \subsubsection{Tree Object}
  521. The \texttt{tree} object in IPFS is similar to Git trees: it represents a
  522. directory, a list of checksums and names. The checksums reference \texttt{blob}
  523. or other \texttt{tree} objects. Note that traditional path naming
  524. is implemented entirely by the \texttt{tree} objects. \texttt{Blocks} and
  525. \texttt{lists} are only addressed by their \texttt{checksums}.
  526. Format:
  527. \begin{verbatim}
  528. tree <num objects> <size varint>
  529. <tree or list or block> <checksum> <size varint> <name>
  530. <tree or list or block> <checksum> <size varint> <name>
  531. ...
  532. \end{verbatim}
  533. \subsubsection{Commit Object}
  534. The \texttt{commit} object in IPFS is similar to Git's. It represents a
  535. snapshot in the version history of a \texttt{tree}. Note that user
  536. addresses are NodeIds (the hash of the public key).
  537. \begin{verbatim}
  538. commit <size varint>
  539. parent <commit checksum>
  540. tree <tree checksum>
  541. author <author public key> <ISO UTC date>
  542. committer <committer public key> <ISO UTC date>
  543. <commit message>
  544. \end{verbatim}
  545. \subsubsection{Version control}
  546. The \texttt{commit} object represents a particular snapshot in the version
  547. history of a tree. Comparing the \texttt{trees} and children objects of two
  548. different commits reveals the differences between two versions of the
  549. filesystem. As long as a single \texttt{commit} and all the children objects
  550. it references are accessible, all preceding versions are retrievable and the
  551. full history of the filesystem changes can be accessed. This is a consequence
  552. of the \texttt{Git} object model and the graph it forms.
  553. The full power of the \texttt{Git} version control tools is available to IPFS
  554. users. The object model is compatible (though not the same). The standard
  555. \texttt{Git} tools can be used on the \texttt{IPFS} object graph after a
  556. conversion. Additionally, a fork of the tools is under development that will
  557. allow users to use them directly without conversion.
  558. \subsection{The Filesystem}
  559. \subsubsection{Filesystem Paths}
  560. IPFS exposes a slash-delimited path-based API. Paths work the same as in any
  561. traditional UNIX filesystem. Path subcomponents have different meanings per
  562. object:
  563. \begin{center}
  564. \begin{tabular}{ll}
  565. \texttt{object} & subcomponent meaning \\
  566. \hline
  567. \hline
  568. \texttt{block} & N/A (no children) \\
  569. \texttt{list} & integer index \\
  570. \texttt{tree} & string name \\
  571. \texttt{commit} & string name (in tree) \\
  572. \end{tabular}
  573. \end{center}
  574. \begin{figure}
  575. \centering
  576. \begin{tikzpicture}[->,>=stealth',auto,thick,
  577. minimum height=2em,minimum width=5em]
  578. \tikzstyle{ghost}=[rectangle,rounded corners=.8ex];
  579. \tikzstyle{block}=[rectangle,draw,fill=blue!20,rounded corners=.8ex];
  580. \tikzstyle{list}=[rectangle,draw,fill=cyan!20,rounded corners=.8ex];
  581. \tikzstyle{tree}=[rectangle,draw,fill=green!20,rounded corners=.8ex];
  582. \tikzstyle{commit}=[rectangle,draw,fill=magenta!20,rounded corners=.8ex];
  583. \tikzstyle{every path}=[draw]
  584. \node[commit] (ccc111) {ccc111};
  585. \node[tree] (ttt111) [below=3em of ccc111] {ttt111};
  586. \node[tree] (ttt222) [below left=3em and 3em of ttt111] {ttt222};
  587. \node[tree] (ttt333) [below=3em of ttt111] {ttt333};
  588. \node[ghost] (ghost1) [below right=3em and 3em of ttt111] {};
  589. \node[list] (lll111) [below=3em of ttt333] {lll111};
  590. \node[block] (bbb111) [below=3em of ttt222] {bbb111};
  591. \node[block] (bbb222) [below right=3em and 3em of ttt333] {bbb222};
  592. \node[block] (bbb333) [below left=3em and 3em of lll111] {bbb333};
  593. \node[block] (bbb444) [below=3em of lll111] {bbb444};
  594. \node[block] (bbb555) [below right=3em and 3em of lll111] {bbb555};
  595. \path[every node/.style={font=\sffamily\small}]
  596. (ccc111) edge[out=-90,in=90] (ttt111)
  597. (ttt111) edge[out=-90,in=90] (ttt222)
  598. edge[out=-90,in=90] (ttt333)
  599. to [out=-90,in=90] (ghost1)
  600. to [out=-90,in=90] (bbb222)
  601. (ttt222) edge[out=-90,in=90] (bbb111)
  602. (ttt333) edge[out=-90,in=90] (lll111)
  603. edge[out=-90,in=90] (bbb222)
  604. (lll111) edge[out=-90,in=90] (bbb333)
  605. edge[out=-90,in=90] (bbb444)
  606. edge[out=-90,in=90] (bbb555)
  607. ;
  608. \end{tikzpicture}
  609. \caption{Sample Object Graph} \label{fig:sample-object-graph}
  610. \begin{verbatim}
  611. # ccc111 contents
  612. commit 313
  613. tree ttt111
  614. author <author public key> <ISO UTC date>
  615. committer <committer public key> <ISO UTC date>
  616. # ttt111 contents
  617. tree 3 250
  618. tree ttt222 46 ttt222-name
  619. tree ttt333 166 ttt333-name
  620. block bbb222 11 bbb222-name
  621. # ttt222 contents
  622. tree 1 10
  623. block bbb111 10 bbb111-name
  624. # ttt333 contents
  625. tree 2 104
  626. list lll111 93 lll111-name
  627. block bbb222 11 bbb222-eman
  628. # lll111 contents
  629. list 3 39
  630. block bbb333 12
  631. block bbb444 13
  632. block bbb555 14
  633. # bbb111 contents # block bbb222 contents
  634. block 1 block 2
  635. 1 22
  636. # bbb333 contents # block bbb444 contents
  637. block 3 block 4
  638. 333 4444
  639. # bbb555 contents
  640. block 5
  641. 55555
  642. \end{verbatim}
  643. \caption{Sample Objects} \label{fig:sample-objects}
  644. \end{figure}
  645. For example, given the sample objects in Figures \ref{fig:sample-object-graph} and \ref{fig:sample-objects}:
  646. \begin{verbatim}
  647. # to access tree ttt333:
  648. ccc111/ttt333-name
  649. # to access block bbb222:
  650. ccc111/bbb222-name
  651. ccc111/ttt333-name/bbb222-eman
  652. # to access list lll111:
  653. ccc111/ttt333-name/lll111-name
  654. # to access block bbb555:
  655. ccc111/ttt333-name/lll111-name/2
  656. \end{verbatim}
  657. Note that:
  658. \begin{itemize}
  659. \item[(a)] blocks have no children \\
  660. \texttt{.../<block>/<child>} is impossible
  661. \item[(b)] commits implicitly access their trees \\
  662. \texttt{.../<commit>/name}
  663. looks up \texttt{"name"} in \texttt{<commit>}'s \texttt{<tree>}
  664. \item[(c)] \texttt{list} children are accessed by their index \\
  665. \texttt{.../<list>/4} looks up the fifth block.
  666. \end{itemize}
  667. \paragraph{Path Lookup Performance}
  668. Path-based access traverses the object graph. Retrieving
  669. each object requires potentially looking up its key in the DHT,
  670. connecting to peers, and retrieving its blocks. This is considerable
  671. overhead, particularly when looking up paths with many components.
  672. This is mitigated by:
  673. \begin{itemize}
  674. \item \textbf{tree caching}: since all objects are hash-addressed, they
  675. can be cached indefinitely. Additionally, \texttt{trees} tend to be
  676. small in size so IPFS prioritizes caching them over \texttt{blocks}.
  677. \item \textbf{flattened trees}: for any given \texttt{tree}, a special
  678. \texttt{flattened tree} can be constructed to list all objects
  679. reachable from the \texttt{tree}. Figure \ref{flattened-ttt111} shows
  680. an example of a flattened tree. While IPFS does not construct flattened
  681. trees by default, it provides a function for users. For example,
  682. \end{itemize}
  683. \begin{figure}
  684. \begin{verbatim}
  685. tree 5 250
  686. tree ttt222 46 ttt222-name
  687. block bbb111 10 ttt222-name/bbb111-name
  688. tree ttt333 166 ttt333-name
  689. list lll111 93 ttt222-name/lll111-name
  690. block bbb222 11 ttt333-name/bbb222-eman
  691. block bbb222 11 bbb222-name
  692. \end{verbatim}
  693. \caption{Flattened Tree for \texttt{ttt111}} \label{fig:flattened-ttt111}
  694. \end{figure}
  695. \subsubsection{Publishing Objects}
  696. IPFS is globally distributed. It is designed to allow the files of millions
  697. of users to coexist together. The \textbf{DHT} with content-hash addressing
  698. allows publishing objects in a fair, secure, and entirely distributed way.
  699. Anyone can publish an object by simply adding its key to the DHT, adding
  700. themselves as a peer, and giving other users the object's hash.
  701. Additionally, the IPFS root directory supports special functionality to
  702. allow namespacing and naming objects in a fair, secure, and distributed
  703. manner.
  704. \begin{itemize}
  705. \item[(a)] All objects are accessible by their hash. Thus, users can
  706. always reference an object (and its children) using
  707. \texttt{/<object\_hash>}.
  708. \item[(b)] \texttt{/<node\_id>} provides a self-certifying filesystem
  709. for user \texttt{node\_id}. If it exists, the object returned is a
  710. special \texttt{tree} signed by \texttt{node\_id}'s private key. Thus,
  711. a user can publish a \texttt{tree} or \texttt{commit} under their
  712. name, and others can verify it by checking the signature matches.
  713. \item[(c)] If \texttt{/<domain>} is a valid domain name, IPFS
  714. looks up key \texttt{gfs} in its \texttt{DNS TXT} record. IPFS
  715. interprets the value as either an object hash or another IPFS path:
  716. \begin{verbatim}
  717. # this DNS TXT record
  718. fs.benet.ai. TXT "gfs=/aabbccddeeffgg ..."
  719. # behaves as symlink
  720. ln -s /aabbccddeeffgg /fs.benet.ai
  721. \end{verbatim}
  722. \end{itemize}
  723. \subsection{Local Objects}
  724. IPFS clients require some \textit{local storage}, an external system
  725. on which to store and retrieve local raw data for the objects IPFS manages.
  726. The type of storage depends on the node's use case.
  727. In most cases, this is simply a portion of disk space (either managed by
  728. the native filesystem, or directly by the IPFS client). In others, non-
  729. persistent caches for example, this storage is just a portion of RAM.
  730. Ultimately, all blocks available in IPFS are in some node's
  731. \textit{local storage}. And when nodes open files with IPFS, the objects are
  732. downloaded and stored locally, at least temporarily. This provides
  733. fast lookup for some configurable amount of time thereafter.
  734. \subsubsection{Object Pinning}
  735. Nodes who wish to ensure the survival of particular objects can do so by
  736. \texttt{pinning} the objects. This ensures the objects are kept in the node's
  737. \textit{local storage}. Pinning can be done recursively, to pin down all
  738. descendent objects as well. For example, recursively pinning a \texttt{tree}
  739. or \texttt{commit} ensures \textit{all} objects pointed to are stored locally
  740. too. This is particularly useful for nodes wishing to keep all their own files.
  741. \section{Acknowledgments}
  742. IPFS is the synthesis of many great ideas and systems. It would be impossible to dare such ambitious goals without standing on the shoulders of such giants. Personal thanks to David Dalrymple, Joe Zimmerman, and Ali Yahya for long discussions on many of these ideas, in particular: exposing the general Merkle DAG (David, Joe), rolling hash blocking (David), and s/kademlia sybill protection (David, Ali). And special thanks to David Mazieres, for his ever brilliant ideas.
  743. %\bibliographystyle{abbrv}
  744. %\bibliography{gfs}
  745. %\balancecolumns
  746. %\subsection{References}
  747. \end{document}