ipfs-cap2pfs.tex 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971
  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 /XLZ1625Jjn7SubMDgEyeaynFuR84ginqvzb
  427. XLYkgq61DYaQ8NhkcqyU7rLcnSa7dSHQ16x 189458 less
  428. XLHBNmRQ5sJJrdMPuu48pzeyTtRo39tNDR5 19441 script
  429. XLF4hwVHsVuZ78FZK6fozf8Jj9WEURMbCX4 5286 template
  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{Paths}
  453. IPFS objects can be traversed with a string path API. Paths work as they do in traditional UNIX filesystems and the Web. The Merkle DAG links make traversing it easy. Note that full paths in IPFS are of the form:
  454. \begin{verbatim}
  455. # format
  456. /ipfs/<hash-of-object>/<name-path-to-object>
  457. # example
  458. /ipfs/XLYkgq61DYaQ8NhkcqyU7rLcnSa7dSHQ16x/foo.txt
  459. \end{verbatim}
  460. The \texttt{/ipfs} prefix allows mounting into existing systems at a standard mount point without conflict (mount point names are of course configurable). The second path component (first within IPFS) is the hash of an object. This is always the case, as there is no global root. A root object would have the impossible task of handling consistency of millions of objects in a distributed (and possibly disconnected) environment. Instead, we simulate the root with content addressing. All objects are always accessible via their hash. Note this means that given three objects in path \texttt{<foo>/bar/baz}, the last object is accessible by all:
  461. \begin{verbatim}
  462. /ipfs/<hash-of-foo>/bar/baz
  463. /ipfs/<hash-of-bar>/baz
  464. /ipfs/<hash-of-baz>
  465. \end{verbatim}
  466. \subsubsection{Publishing Objects}
  467. IPFS is globally distributed. It is designed to allow the files of millions of users to coexist together. The \textbf{DHT} with content-hash addressing allows publishing objects in a fair, secure, and entirely distributed way. Anyone can publish an object by simply adding its key to the DHT, adding themselves as a peer, and giving other users the object's path. Note that Objects are essentially immutable, just like in Git. New versions hash differently, and thus are new objects. Tracking versions is the job of additional versioning objects.
  468. \subsubsection{Object-level Cryptography}
  469. 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.
  470. \begin{verbatim}
  471. type EncryptedObject struct {
  472. Object []bytes
  473. // raw object data encrypted
  474. Tag []bytes
  475. // optional tag for encryption groups
  476. }
  477. type SignedObject struct {
  478. Object []bytes
  479. // raw object data signed
  480. Signature []bytes
  481. // hmac signature
  482. PublicKey []multihash
  483. // multihash identifying key
  484. }
  485. \end{verbatim}
  486. Cryptographic operations change the object's hash (defining a different object, as it should). IPFS automatically verifies signatures, and can decrypt data with user-specified keychains. Links of encrypted objects are protected as well, making traversal impossible without a decryption key. It is possible to have a parent object encrypted under one key, and a child under another or not at all. This allows securing links to shared objects.
  487. \subsection{Local Objects}
  488. IPFS clients require some \textit{local storage}, an external system
  489. on which to store and retrieve local raw data for the objects IPFS manages.
  490. The type of storage depends on the node's use case.
  491. In most cases, this is simply a portion of disk space (either managed by
  492. the native filesystem, by a key-value store such as leveldb \cite{leveldb}, or
  493. directly by the IPFS client). In others, non-persistent caches for example,
  494. this storage is just a portion of RAM.
  495. Ultimately, all blocks available in IPFS are in some node's
  496. \textit{local storage}. When users request objects, they are
  497. found, downloaded, and stored locally, at least temporarily. This provides
  498. fast lookup for some configurable amount of time thereafter.
  499. \subsubsection{Object Pinning}
  500. Nodes who wish to ensure the survival of particular objects can do so by
  501. \texttt{pinning} the objects. This ensures the objects are kept in the node's
  502. \textit{local storage}. Pinning can be done recursively, to pin down all
  503. linked descendent objects as well. All objects pointed to are then stored
  504. locally. This is particularly useful for nodes wishing to keep all their own
  505. files, or backup references to others. This also makes IPFS a Web where links
  506. are \textit{permanent}, and Objects can ensure the survival of others they
  507. point to.
  508. \subsection{Files}
  509. IPFS also defines a set of objects for modeling a versioned filesystem on top of the Merkle DAG. This object model is similar to Git's:
  510. \begin{enumerate}
  511. \item \texttt{block}: a variable-size block of data.
  512. \item \texttt{list}: a collection of blocks or other lists.
  513. \item \texttt{tree}: a collection of blocks, lists, or other trees.
  514. \item \texttt{commit}: a snapshot in the version history of a tree.
  515. \end{enumerate}
  516. I hoped to use the Git object formats exactly, but had to depart to introduce certain features useful in a distributed filesystem, namely (a) fast size lookups (aggregate byte sizes have been added to objects), (b) large file deduplication (adding a \texttt{list} object), and (c) embedding of \texttt{commits} into \texttt{trees}. However, IPFS File objects are close enough to Git that conversion between is possible. Also, a set of Git objects can be introduced to convert between the two without losing any information (unix file permissions, etc).
  517. Notation: File object formats below use JSON. Note that this structure is actually binary encoded using protobufs. Though, ipfs includes import/export to JSON.
  518. \subsubsection{File Object: \texttt{blob}}
  519. The \texttt{blob} object contains an addressable unit of data, and
  520. represents a file. IPFS Blocks are like Git blobs or filesystem data blocks. They store the users' data. Note that IPFS files can be represented by both \texttt{lists} and \texttt{blobs}. Blobs have no links.
  521. \begin{verbatim}
  522. {
  523. "data": "some data here",
  524. // blobs have no links
  525. }
  526. \end{verbatim}
  527. \subsubsection{File Object: \texttt{list}}
  528. The \texttt{list} object represents a large or de-duplicated file made up of
  529. several IPFS \texttt{blobs} concatenated together. \texttt{lists} contain
  530. an ordered sequence of \texttt{blob} or \texttt{list} objects.
  531. In a sense, the IPFS \texttt{list} functions like a filesystem file with
  532. 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. Of course, cycles are not possible, as enforced by hash addessing.
  533. \begin{verbatim}
  534. {
  535. "data": ["blob", "list", "blob"],
  536. // lists have an array of object types as data
  537. "links": [
  538. { "hash": "XLYkgq61DYaQ8NhkcqyU7rLcnSa7dSHQ16x",
  539. "size": 189458 },
  540. { "hash": "XLHBNmRQ5sJJrdMPuu48pzeyTtRo39tNDR5",
  541. "size": 19441 },
  542. { "hash": "XLWVQDqxo9Km9zLyquoC9gAP8CL1gWnHZ7z",
  543. "size": 5286 }
  544. // lists have no names in links
  545. ]
  546. }
  547. \end{verbatim}
  548. \begin{figure}
  549. \centering
  550. \begin{tikzpicture}[->,>=stealth',auto,thick,
  551. minimum height=2em,minimum width=5em]
  552. \tikzstyle{ghost}=[rectangle,rounded corners=.8ex];
  553. \tikzstyle{block}=[rectangle,draw,fill=blue!20,rounded corners=.8ex];
  554. \tikzstyle{list}=[rectangle,draw,fill=cyan!20,rounded corners=.8ex];
  555. \tikzstyle{tree}=[rectangle,draw,fill=green!20,rounded corners=.8ex];
  556. \tikzstyle{commit}=[rectangle,draw,fill=magenta!20,rounded corners=.8ex];
  557. \tikzstyle{every path}=[draw]
  558. \node[commit] (ccc111) {ccc111};
  559. \node[tree] (ttt111) [below=3em of ccc111] {ttt111};
  560. \node[tree] (ttt222) [below left=3em and 3em of ttt111] {ttt222};
  561. \node[tree] (ttt333) [below=3em of ttt111] {ttt333};
  562. \node[ghost] (ghost1) [below right=3em and 3em of ttt111] {};
  563. \node[list] (lll111) [below=3em of ttt333] {lll111};
  564. \node[block] (bbb111) [below=3em of ttt222] {bbb111};
  565. \node[block] (bbb222) [below right=3em and 3em of ttt333] {bbb222};
  566. \node[block] (bbb333) [below left=3em and 3em of lll111] {bbb333};
  567. \node[block] (bbb444) [below=3em of lll111] {bbb444};
  568. \node[block] (bbb555) [below right=3em and 3em of lll111] {bbb555};
  569. \path[every node/.style={font=\sffamily\small}]
  570. (ccc111) edge[out=-90,in=90] (ttt111)
  571. (ttt111) edge[out=-90,in=90] (ttt222)
  572. edge[out=-90,in=90] (ttt333)
  573. to [out=-90,in=90] (ghost1)
  574. to [out=-90,in=90] (bbb222)
  575. (ttt222) edge[out=-90,in=90] (bbb111)
  576. (ttt333) edge[out=-90,in=90] (lll111)
  577. edge[out=-90,in=90] (bbb222)
  578. (lll111) edge[out=-90,in=90] (bbb333)
  579. edge[out=-90,in=90] (bbb444)
  580. edge[out=-90,in=90] (bbb555)
  581. ;
  582. \end{tikzpicture}
  583. \caption{Sample Object Graph} \label{fig:sample-object-graph}
  584. \begin{verbatim}
  585. > ipfs file-cat <ccc111-hash> --json
  586. {
  587. "data": {
  588. "type": "tree",
  589. "date": "2014-09-20 12:44:06Z",
  590. "message": "This is a commit message."
  591. },
  592. "links": [
  593. { "hash": "<ccc000-hash>",
  594. "name": "parent", "size": 25309 },
  595. { "hash": "<ttt111-hash>",
  596. "name": "object", "size": 5198 },
  597. { "hash": "<aaa111-hash>",
  598. "name": "author", "size": 109 }
  599. ]
  600. }
  601. > ipfs file-cat <ttt111-hash> --json
  602. {
  603. "data": ["tree", "tree", "blob"],
  604. "links": [
  605. { "hash": "<ttt222-hash>",
  606. "name": "ttt222-name", "size": 1234 },
  607. { "hash": "<ttt333-hash>",
  608. "name": "ttt333-name", "size": 3456 },
  609. { "hash": "<bbb222-hash>",
  610. "name": "bbb222-name", "size": 22 }
  611. ]
  612. }
  613. > ipfs file-cat <bbb222-hash> --json
  614. {
  615. "data": "blob222 data",
  616. "links": []
  617. }
  618. \end{verbatim}
  619. \caption{Sample Objects} \label{fig:sample-objects}
  620. \end{figure}
  621. \subsubsection{File Object: \texttt{tree}}
  622. The \texttt{tree} object in IPFS is similar to Git trees: it represents a
  623. directory, a map of names to hashes. The hashes reference \texttt{blobs}, \texttt{lists}, other \texttt{trees}, or \texttt{commits}. Note that traditional path naming is already implemented by the Merkle DAG. Though, collapsing \texttt{commits} and \texttt{lists}, and representing only \texttt{trees} as directories is achieved by a special mounting application which exposes the objects through a different file system interface.
  624. \begin{verbatim}
  625. {
  626. "data": ["blob", "list", "blob"],
  627. // trees have an array of object types as data
  628. "links": [
  629. { "hash": "XLYkgq61DYaQ8NhkcqyU7rLcnSa7dSHQ16x",
  630. "name": "less", "size": 189458 },
  631. { "hash": "XLHBNmRQ5sJJrdMPuu48pzeyTtRo39tNDR5",
  632. "name": "script", "size": 19441 },
  633. { "hash": "XLWVQDqxo9Km9zLyquoC9gAP8CL1gWnHZ7z",
  634. "name": "template", "size": 5286 }
  635. // trees do have names
  636. ]
  637. }
  638. \end{verbatim}
  639. \subsubsection{File Object: \texttt{commit}}
  640. The \texttt{commit} object in IPFS represents a snapshot in the version history of any object. It is similar to Git's, but can reference any type of object. It also links to author objects.
  641. \begin{verbatim}
  642. {
  643. "data": {
  644. "type": "tree",
  645. "date": "2014-09-20 12:44:06Z",
  646. "message": "This is a commit message."
  647. },
  648. "links": [
  649. { "hash": "XLa1qMBKiSEEDhojb9FFZ4tEvLf7FEQdhdU",
  650. "name": "parent", "size": 25309 },
  651. { "hash": "XLGw74KAy9junbh28x7ccWov9inu1Vo7pnX",
  652. "name": "object", "size": 5198 },
  653. { "hash": "XLF2ipQ4jD3UdeX5xp1KBgeHRhemUtaA8Vm",
  654. "name": "author", "size": 109 }
  655. ]
  656. }
  657. \end{verbatim}
  658. \subsubsection{Version control}
  659. The \texttt{commit} object represents a particular snapshot in the version
  660. history of an object. Comparing the object (and children) of two
  661. different commits reveals the differences between two versions of the
  662. filesystem. As long as a single \texttt{commit} and all the children objects
  663. it references are accessible, all preceding versions are retrievable and the
  664. full history of the filesystem changes can be accessed. This is a consequence
  665. of the Merkle DAG object model.
  666. The full power of the \texttt{Git} version control tools is available to IPFS users. The object model is compatible, though not the same. It is possible to (a) build a version of the \texttt{Git} tools modified to use the \texttt{IPFS} object graph, (b) build a mounted FUSE filesystem that mounts an IPFS \texttt{tree} as a Git repo, translating Git filesystem read/writes to the IPFS formats.
  667. \subsubsection{Filesystem Paths}
  668. As we saw in the Merkle DAG section, IPFS objects can be traversed with a string path API. The IPFS File Objects are designed to make mounting IPFS onto a UNIX filesystem simpler. They restrict \texttt{trees} to have no data, in order to represent them as directories, and \texttt{commits} can either be represented as directories too, or hidden from the filesystem entirely.
  669. \paragraph{Path Lookup Performance}
  670. Path-based access traverses the object graph. Retrieving
  671. each object requires potentially looking up its key in the DHT,
  672. connecting to peers, and retrieving its blocks. This is considerable
  673. overhead, particularly when looking up paths with many components.
  674. This is mitigated by:
  675. \begin{itemize}
  676. \item \textbf{tree caching}: since all objects are hash-addressed, they
  677. can be cached indefinitely. Additionally, \texttt{trees} tend to be
  678. small in size so IPFS prioritizes caching them over \texttt{blobs}.
  679. \item \textbf{flattened trees}: for any given \texttt{tree}, a special
  680. \texttt{flattened tree} can be constructed to list all objects
  681. reachable from the \texttt{tree}. Names in the \texttt{flattened tree}
  682. would really be paths parting from the original tree, with slashes.
  683. \end{itemize}
  684. For example, \texttt{flattened tree} for \texttt{ttt111} above:
  685. \begin{verbatim}
  686. {
  687. "data":
  688. ["tree", "blob", tree", "list", "blob" "blob"],
  689. "links": [
  690. { "hash": "<ttt222-hash>", "size": 1234
  691. "name": "ttt222-name" },
  692. { "hash": "<bbb111-hash>", "size": 123,
  693. "name": "ttt222-name/bbb111-name" },
  694. { "hash": "<ttt333-hash>", "size": 3456,
  695. "name": "ttt333-name" },
  696. { "hash": "<lll111-hash>", "size": 587,
  697. "name": "ttt333-name/lll111-name"},
  698. { "hash": "<bbb222-hash>", "size": 22,
  699. "name": "ttt333-name/lll111-name/bbb222-name" },
  700. { "hash": "<bbb222-hash>", "size": 22
  701. "name": "bbb222-name" }
  702. ] }
  703. \end{verbatim}
  704. \subsection{Naming}
  705. Additionally, the IPFS root directory supports special functionality to
  706. allow namespacing and naming objects in a fair, secure, and distributed
  707. manner.
  708. \begin{itemize}
  709. \item[(a)] All objects are accessible by their hash. Thus, users can
  710. always reference an object (and its children) using
  711. \texttt{/<object\_hash>}.
  712. \item[(b)] \texttt{/<node\_id>} provides a self-certifying filesystem
  713. for user \texttt{node\_id}. If it exists, the object returned is a
  714. special \texttt{tree} signed by \texttt{node\_id}'s private key. Thus,
  715. a user can publish a \texttt{tree} or \texttt{commit} under their
  716. name, and others can verify it by checking the signature matches.
  717. \item[(c)] If \texttt{/<domain>} is a valid domain name, IPFS
  718. looks up key \texttt{gfs} in its \texttt{DNS TXT} record. IPFS
  719. interprets the value as either an object hash or another IPFS path:
  720. \begin{verbatim}
  721. # this DNS TXT record
  722. fs.benet.ai. TXT "gfs=/aabbccddeeffgg ..."
  723. # behaves as symlink
  724. ln -s /aabbccddeeffgg /fs.benet.ai
  725. \end{verbatim}
  726. \end{itemize}
  727. \section{Acknowledgments}
  728. 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.
  729. %\bibliographystyle{abbrv}
  730. %\bibliography{gfs}
  731. %\balancecolumns
  732. %\subsection{References}
  733. \end{document}