aboutsummaryrefslogtreecommitdiff
path: root/doc/gnunet-c-tutorial.tex
diff options
context:
space:
mode:
authorng0 <ng0@infotropique.org>2017-08-24 13:20:39 +0000
committerng0 <ng0@infotropique.org>2017-08-24 13:20:39 +0000
commit834f1ec8209254fb66dc2908d39852761f015c8f (patch)
treee2cab1f02106812a3c46d19fb9cd775b49d0ded1 /doc/gnunet-c-tutorial.tex
parent4c4d52c50cca5ff22ec12839ba6c629f705fef00 (diff)
downloadgnunet-834f1ec8209254fb66dc2908d39852761f015c8f.tar.gz
gnunet-834f1ec8209254fb66dc2908d39852761f015c8f.zip
doc: Start of half-manual conversion from LaTeX to Texinfo for gnunet-c-tutorial.
Diffstat (limited to 'doc/gnunet-c-tutorial.tex')
-rw-r--r--doc/gnunet-c-tutorial.tex1529
1 files changed, 0 insertions, 1529 deletions
diff --git a/doc/gnunet-c-tutorial.tex b/doc/gnunet-c-tutorial.tex
deleted file mode 100644
index 13c975567..000000000
--- a/doc/gnunet-c-tutorial.tex
+++ /dev/null
@@ -1,1529 +0,0 @@
1\documentclass[10pt]{article}
2\usepackage[ansinew]{inputenc}
3\usepackage{makeidx,amsmath,amssymb,exscale,multicol,epsfig,graphics,verbatim,ulem}
4\usepackage{epsfig,geometry,url,listings,subcaption}
5\usepackage{boxedminipage}
6\usepackage[T1]{fontenc}%required
7\usepackage{textcomp}
8\geometry{headsep=3ex,hscale=0.9}
9\usepackage{hyperref}
10\usepackage{color}
11\hypersetup{pdftitle={GNUnet C Tutorial},
12 pdfsubject={GNUnet},
13 pdfauthor={Christian Grothoff <christian@grothoff.org>},
14 pdfkeywords={p2p,search,gnunet,tutorial}
15 %,pdfpagemode={FullScreen}
16 }
17
18
19\lstset{
20language=bash,
21basicstyle=\ttfamily,
22upquote=true,
23columns=fullflexible,
24literate={*}{{\char42}}1
25 {-}{{\char45}}1
26}
27
28\newcommand{\exercise}[1]{\noindent\begin{boxedminipage}{\textwidth}{\bf Exercise:} #1 \end{boxedminipage}}
29
30\begin{document}
31
32\lstset{ %
33language=C, % choose the language of the code
34basicstyle=\footnotesize, % the size of the fonts that are used for the code
35numbers=left, % where to put the line-numbers
36numberstyle=\footnotesize, % the size of the fonts that are used for the line-numbers
37stepnumber=1, % the step between two line-numbers. If it is 1 each line will be numbered
38numbersep=5pt, % how far the line-numbers are from the code
39backgroundcolor=\color{white}, % choose the background color. You must add \usepackage{color}
40showspaces=false, % show spaces adding particular underscores
41showstringspaces=false, % underline spaces within strings
42showtabs=false, % show tabs within strings adding particular underscores
43frame=single, % adds a frame around the code
44tabsize=2, % sets default tabsize to 2 spaces
45captionpos=b, % sets the caption-position to bottom
46breaklines=true, % sets automatic line breaking
47breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace
48escapeinside={\%*}{*)} % if you want to add a comment within your code
49}
50
51
52\begin{center}
53\large {A Tutorial for GNUnet 0.10.x (C version)}
54
55Christian Grothoff $\qquad$ Bart Polot $\qquad$ Matthias Wachs
56
57\today
58\end{center}
59This tutorials explains how to install GNUnet on a GNU/Linux system and gives an introduction on how
60GNUnet can be used to develop a Peer-to-Peer application. Detailed installation instructions for
61various operating systems and a detailed list of all dependencies can be found on our website at
62\url{https://gnunet.org/installation}.
63
64\textbf{Please read this tutorial carefully since every single step is
65 important and do not hesitate to contact the GNUnet team if you have
66 any questions or problems! Check here how to contact the GNUnet
67 team: \url{https://gnunet.org/contact_information}}
68
69
70\section{Installing GNUnet}
71
72First of all you have to install a current version of GNUnet. You can download a
73tarball of a stable version from GNU FTP mirrors or obtain the latest development
74version from our Git repository.
75
76Most of the time you should prefer to download the stable version since with the
77latest development version things can be broken, functionality can be changed or tests
78can fail. You should only use the development version if you know that you require a
79certain feature or a certain issue has been fixed since the last release.
80
81\subsection{Obtaining a stable version}
82
83You can download the latest stable version of GNUnet from GNU FTP mirrors:
84\begin{center}
85\url{ftp://ftp.gnu.org/gnu/gnunet/gnunet-0.10.x.tar.gz}
86\end{center}
87You should also download the signature file and verify the integrity of the tarball.
88\begin{center}
89\url{ftp://ftp.gnu.org/gnu/gnunet/gnunet-0.10.x.tar.gz.sig}
90\end{center}
91To verify the signature you should first import the GPG key used to sign the tarball
92\lstset{language=bash}
93\begin{lstlisting}
94$ gpg --keyserver keys.gnupg.net --recv-keys 48426C7E
95\end{lstlisting}
96And use this key to verify the tarball's signature
97\lstset{language=bash}
98\begin{lstlisting}
99$ gpg --verify gnunet-0.10.x.tar.gz.sig gnunet-0.10.x.tar.gz
100\end{lstlisting}
101After successfully verifying the integrity you can extract the tarball using
102\lstset{language=bash}
103\begin{lstlisting}
104$ tar xvzf gnunet-0.10.x.tar.gz
105$ mv gnunet-0.10.x gnunet # we will use the directory "gnunet" in the remainder of this document
106$ cd gnunet
107\end{lstlisting}
108
109However, please note that stable versions can be very outdated, as a developer
110you are strongly encouraged to use the version from \url{https://gnunet.org/git/}.
111
112\subsection{Installing Build Tool Chain and Dependencies}
113
114To successfully compile GNUnet you need the tools to build GNUnet and the required dependencies.
115Please have a look at \url{https://gnunet.org/dependencies} for a list of required dependencies
116and \url{https://gnunet.org/generic_installation} for specific instructions for your operating system.
117
118Please check the notes at the end of the configure process about required dependencies.
119
120For GNUnet bootstrapping support and the http(s) plugin you should install \texttt{libgnurl}.
121For the filesharing service you should install at least one of the datastore backends \texttt{mysql},
122\texttt{sqlite} or \texttt{postgresql}.
123
124\subsection{Obtaining the latest version from Git}
125
126The latest development version can obtained from our Git repository. To obtain
127the code you need Git installed and checkout the repository using:
128\lstset{language=bash}
129\begin{lstlisting}
130$ git clone https://gnunet.org/git/gnunet
131\end{lstlisting}
132After cloning the repository you have to execute
133\lstset{language=bash}
134\begin{lstlisting}
135$ cd gnunet
136$ ./bootstrap
137\end{lstlisting}
138
139The remainder of this tutorial assumes that you have Git Master checked out.
140
141
142\subsection{Compiling and Installing GNUnet}
143
144First, you need to install at least {\tt libgnupgerror} version
1451.27\footnote{\url{ftp://ftp.gnupg.org/gcrypt/libgpg-error/libgpg-error-1.27.tar.bz2}}
146and {\tt libgcrypt} version
1471.7.6\footnote{\url{ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.7.6.tar.bz2}}.
148
149\lstset{language=bash}
150\begin{lstlisting}
151$ wget ftp://ftp.gnupg.org/gcrypt/libgpg-error/libgpg-error-1.27.tar.bz2
152$ tar xf libgpg-error-1.27.tar.bz2
153$ cd libgpg-error-1.27
154$ ./configure
155$ sudo make install
156$ cd ..
157\end{lstlisting}
158
159\lstset{language=bash}
160\begin{lstlisting}
161$ wget ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.7.6.tar.bz2
162$ tar xf libgcrypt-1.7.6.tar.bz2
163$ cd libgcrypt-1.7.6
164$ ./configure
165$ sudo make install
166$ cd ..
167\end{lstlisting}
168
169\label{sub:install}
170Assuming all dependencies are installed, the following commands will
171compile and install GNUnet in your home directory. You can specify the
172directory where GNUnet will be installed by changing the
173\lstinline|--prefix| value when calling \lstinline|./configure|. If
174you do not specifiy a prefix, GNUnet is installed in the directory
175\lstinline|/usr/local|. When developing new applications you may want
176to enable verbose logging by adding
177\lstinline|--enable-logging=verbose|:
178
179\lstset{language=bash}
180\begin{lstlisting}
181$ ./configure --prefix=$PREFIX --enable-logging
182$ make
183$ make install
184\end{lstlisting}
185
186After installing GNUnet you have to add your GNUnet installation to your path
187environmental variable. In addition you have to create the \lstinline|.config|
188directory in your home directory where GNUnet stores its data and an empty
189GNUnet configuration file:
190
191\lstset{language=bash}
192\begin{lstlisting}
193$ export PATH=$PATH:$PREFIX/bin
194$ echo export PATH=$PREFIX/bin:\\$PATH >> ~/.bashrc
195$ mkdir ~/.config/
196$ touch ~/.config/gnunet.conf
197\end{lstlisting}
198% $
199
200\subsection{Common Issues - Check your GNUnet installation}
201
202You should check your installation to ensure that installing GNUnet
203was successful up to this point. You should be able to access GNUnet's
204binaries and run GNUnet's self check.
205\lstset{language=bash}
206\begin{lstlisting}
207$ which gnunet-arm
208\end{lstlisting}
209should return \lstinline|$PREFIX/bin/gnunet-arm|. It should be
210located in your GNUnet installation and the output should not be
211empty. If you see an output like:
212\lstset{language=bash}
213\begin{lstlisting}
214$ which gnunet-arm
215$
216\end{lstlisting}
217check your {\tt PATH} variable to ensure GNUnet's {\tt bin} directory is included.
218
219GNUnet provides tests for all of its subcomponents. Run
220\lstset{language=bash}
221\begin{lstlisting}
222$ make check
223\end{lstlisting}
224to execute tests for all components. {\tt make check} traverses all subdirectories in {\tt src}.
225For every subdirectory you should get a message like this:
226
227\begin{verbatim}
228make[2]: Entering directory `/home/$USER/gnunet/contrib'
229PASS: test_gnunet_prefix
230=============
2311 test passed
232=============
233\end{verbatim}
234
235
236\section{Background: GNUnet Architecture}
237
238GNUnet is organized in layers and services. Each service is composed of a
239main service implementation and a client library for other programs to use
240the service's functionality, described by an API. This approach is shown in
241figure~\ref{fig:service}. Some services provide an additional command line
242tool to enable the user to interact with the service.
243
244Very often it is other GNUnet services that will use these APIs to build the
245higher layers of GNUnet on top of the lower ones. Each layer expands or extends
246the functionality of the service below (for instance, to build a mesh on top of
247a DHT). See figure ~\ref{fig:interaction} for an illustration of this approach.
248
249\begin{figure}[!h]
250 \begin{center}
251% \begin{subfigure}
252 \begin{subfigure}[b]{0.3\textwidth}
253 \centering
254 \includegraphics[width=\textwidth]{figs/Service.pdf}
255 \caption{Service with API and network protocol}
256 \label{fig:service}
257 \end{subfigure}
258 ~~~~~~~~~~
259 \begin{subfigure}[b]{0.3\textwidth}
260 \centering
261 \includegraphics[width=\textwidth]{figs/System.pdf}
262 \caption{Service interaction}
263 \label{fig:interaction}
264 \end{subfigure}
265 \end{center}
266 \caption{GNUnet's layered system architecture}
267\end{figure}
268
269The main service implementation runs as a standalone process in the operating
270system and the client code runs as part of the client program, so crashes of a
271client do not affect the service process or other clients. The service and the
272clients communicate via a message protocol to be defined and implemented by
273the programmer.
274
275
276\section{First Steps with GNUnet}
277
278\subsection{Configure your peer}
279
280First of all we need to configure your peer. Each peer is started with a configuration containing settings for GNUnet itself and its services. This configuration is based on the default configuration shipped with GNUnet and can be modified. The default configuration is located in the {\tt \$PREFIX/share/gnunet/config.d} directory. When starting a peer, you can specify a customized configuration using the the {\tt$-c$} command line switch when starting the ARM service and all other services. When using a modified configuration the default values are loaded and only values specified in the configuration file will replace the default values.
281
282Since we want to start additional peers later, we need
283some modifications from the default configuration. We need to create a separate service home and a file containing our modifications for this peer:
284\lstset{language=bash}
285\begin{lstlisting}
286$ mkdir ~/gnunet1/
287$ touch peer1.conf
288\end{lstlisting}
289
290Now add the following lines to peer1.conf to use this directory. For
291simplified usage we want to prevent the peer to connect to the GNUnet
292network since this could lead to confusing output. This modifications
293will replace the default settings:
294\begin{verbatim}
295[PATHS]
296GNUNET_HOME = ~/gnunet1/ # Use this directory to store GNUnet data
297[hostlist]
298SERVERS = # prevent bootstrapping
299\end{verbatim}
300
301
302\subsection{Start a peer}
303Each GNUnet instance (called peer) has an identity (\textit{peer ID}) based on a
304cryptographic public private key pair. The peer ID is the printable hash of the
305public key.
306
307GNUnet services are controlled by a master service the so called \textit{Automatic Restart Manager} (ARM).
308ARM starts, stops and even restarts services automatically or on demand when a client connects.
309You interact with the ARM service using the \lstinline|gnunet-arm| tool.
310GNUnet can then be started with \lstinline|gnunet-arm -s| and stopped with
311\lstinline|gnunet-arm -e|. An additional service not automatically started
312can be started using \lstinline|gnunet-arm -i <service name>| and stopped
313using \lstinline|gnunet-arm -k <servicename>|.
314
315Once you have started your peer, you can use many other GNUnet commands
316to interact with it. For example, you can run:
317\lstset{language=bash}
318\begin{lstlisting}
319$ gnunet-peerinfo -s
320\end{lstlisting}
321to obtain the public key of your peer.
322You should see an output containing the peer ID similar to:
323\lstset{language=bash}
324\begin{lstlisting}
325I am peer `0PA02UVRKQTS2C .. JL5Q78F6H0B1ACPV1CJI59MEQUMQCC5G'.
326\end{lstlisting}
327
328
329\subsection{Monitor a peer}
330
331In this section, we will monitor the behaviour of our peer's DHT service with respect to a
332specific key. First we will start GNUnet and then start the DHT service and use the DHT monitor tool
333to monitor the PUT and GET commands we issue ussing the \lstinline|gnunet-dht-put| and
334\lstinline|gnunet-dht-get| commands. Using the ``monitor'' line given below, you can observe the behavior of
335your own peer's DHT with respect to the specified KEY:
336
337\lstset{language=bash}
338\begin{lstlisting}
339$ gnunet-arm -c ~/peer1.conf -s # start gnunet with all default services
340$ gnunet-arm -c ~/peer1.conf -i dht # start DHT service
341$ cd ~/gnunet/src/dht;
342$ ./gnunet-dht-monitor -c ~/peer1.conf -k KEY
343\end{lstlisting}
344Now open a separate terminal and change again to the \lstinline|gnunet/src/dht| directory:
345\lstset{language=bash}
346\begin{lstlisting}
347$ cd ~/gnunet/src/dht
348$ ./gnunet-dht-put -c ~/peer1.conf -k KEY -d VALUE # put VALUE under KEY in the DHT
349$ ./gnunet/src/dht/gnunet-dht-get -c ~/peer1.conf -k KEY # get key KEY from the DHT
350$ gnunet-statistics -c ~/peer1.conf # print statistics about current GNUnet state
351$ gnunet-statistics -c ~/peer1.conf -s dht # print statistics about DHT service
352\end{lstlisting}
353% $
354
355
356\subsection{Starting Two Peers by Hand}
357
358This section describes how to start two peers on the same machine by hand.
359The process is rather painful, but the description is somewhat instructive.
360In practice, you might prefer the automated method described in
361Section~\ref{sec:testbed}.
362
363\subsubsection{Setup a second peer}
364We will now start a second peer on your machine.
365For the second peer, you will need to manually create a modified
366configuration file to avoid conflicts with ports and directories.
367A peers configuration file is by default located in {\tt ~/.gnunet/gnunet.conf}.
368This file is typically very short or even empty as only the differences to the
369defaults need to be specified. The defaults are located in
370many files in the {\tt \$PREFIX/share/gnunet/config.d} directory.
371
372To configure the second peer, use the files {\tt
373 \$PREFIX/share/gnunet/config.d} as a template for your main
374configuration file:
375%
376\lstset{language=bash}
377\lstset{language=bash}
378\begin{lstlisting}
379$ cat $PREFIX/share/gnunet/config.d/*.conf > peer2.conf
380\end{lstlisting}
381Now you have to edit {\tt peer2.conf} and change:
382\begin{itemize}
383 \itemsep0em
384 \item{\texttt{GNUNET\_TEST\_HOME} under \texttt{PATHS}}
385 \item{Every (uncommented) value for ``\texttt{PORT}'' (add 10000) in any
386 section (the option may be commented out if \texttt{PORT} is
387 prefixed by "\#", in this case, UNIX domain sockets are used
388 and the PORT option does not need to be touched) }
389 \item{Every value for ``\texttt{UNIXPATH}'' in any section (e.g. by adding a "-p2" suffix)}
390\end{itemize}
391to a fresh, unique value. Make sure that the \texttt{PORT} numbers stay
392below 65536. From now on, whenever you interact with the second
393peer, you need to specify {\tt -c peer2.conf} as an additional
394command line argument.
395
396Now, generate the 2nd peer's private key:
397
398\lstset{language=bash}
399\begin{lstlisting}
400$ gnunet-peerinfo -s -c peer2.conf
401\end{lstlisting}
402% $
403
404This may take a while, generate entropy using your keyboard or mouse
405as needed. Also, make sure the output is different from the {\tt
406 gnunet-peerinfo} output for the first peer (otherwise you made an
407error in the configuration).
408
409\subsubsection{Start the second peer and connect the peers}
410
411Then, you can start a second peer using:
412\lstset{language=bash}
413\begin{lstlisting}
414$ gnunet-arm -c peer2.conf -s
415$ gnunet-arm -c peer2.conf -i dht
416$ ~/gnunet/src/dht/gnunet-dht-put -c peer2.conf -k KEY -d VALUE
417$ ~/gnunet/src/dht/gnunet-dht-get -c peer2.conf -k KEY
418\end{lstlisting}
419If you want the two peers to connect, you have multiple options:
420\begin{itemize}
421\itemsep0em
422 \item UDP neighbour discovery (automatic)
423 \item Setup a bootstrap server
424 \item Connect manually
425\end{itemize}
426To setup peer 1 as bootstrapping server change the configuration of
427the first one to be a hostlist server by adding the following lines to
428\texttt{peer1.conf} to enable bootstrapping server:
429 \begin{verbatim}
430[hostlist]
431OPTIONS = -p
432\end{verbatim}
433
434Then change {\tt peer2.conf} and replace the ``\texttt{SERVERS}'' line in the ``\texttt{[hostlist]}'' section with
435``\texttt{http://localhost:8080/}''. Restart both peers using:
436\begin{lstlisting}
437$ gnunet-arm -c peer1.conf -e # stop first peer
438$ gnunet-arm -c peer1.conf -s # start first peer
439$ gnunet-arm -c peer2.conf -s # start second peer
440\end{lstlisting}
441
442Note that if you start your peers without changing these settings, they
443will use the ``global'' hostlist servers of the GNUnet P2P network and
444likely connect to those peers. At that point, debugging might become
445tricky as you're going to be connected to many more peers and would
446likely observe traffic and behaviors that are not explicitly controlled
447by you.
448
449\subsubsection{How to connect manually}
450
451If you want to use the \texttt{peerinfo} tool to connect your peers, you should:
452\begin{itemize}
453\itemsep0em
454 \item{Set {\tt FORCESTART = NO} in section {\tt hostlist} (to not connect to the global GNUnet)}
455 \item{Start both peers running {\tt gnunet-arm -c peer1.conf -s} and {\tt gnunet-arm -c peer2.conf -s}}
456 \item{Get \texttt{HELLO} message of the first peer running {\tt gnunet-peerinfo -c peer1.conf -g}}
457 \item{Give the output to the second peer by running {\tt gnunet-peerinfo -c peer2.conf -p '<output>'}}
458\end{itemize}
459
460Check that they are connected using {\tt gnunet-core -c peer1.conf}, which should give you the other peer's
461peer identity:
462\lstset{language=bash}
463\begin{lstlisting}
464$ gnunet-core -c peer1.conf
465Peer `9TVUCS8P5A7ILLBGO6 [...shortened...] 1KNBJ4NGCHP3JPVULDG'
466\end{lstlisting}
467
468\subsection{Starting Peers Using the Testbed Service} \label{sec:testbed}
469
470GNUnet's testbed service is used for testing scenarios where a number of peers
471are to be started. The testbed can manage peers on a single host or on multiple
472hosts in a distributed fashion. On a single affordable computer, it should be
473possible to run around tens of peers without drastically increasing the load on the
474system.
475
476The testbed service can be access through its API
477\texttt{include/gnunet\_testbed\_service.h}. The API provides many routines for
478managing a group of peers. It also provides a helper function
479\texttt{GNUNET\_TESTBED\_test\_run()} to quickly setup a minimalistic testing
480environment on a single host.
481
482This function takes a configuration file which will be used as a template
483configuration for the peers. The testbed takes care of modifying relevant
484options in the peers' configuration such as SERVICEHOME, PORT, UNIXPATH to
485unique values so that peers run without running into conflicts. It also checks
486and assigns the ports in configurations only if they are free.
487
488Additionally, the testbed service also reads its options from the same
489configuration file. Various available options and details about them can be
490found in the testbed default configuration file \texttt{src/testbed/testbed.conf}.
491
492With the testbed API, a sample test case can be structured as follows:
493% <lynX> Is there a way to pick a more readable font for this include?
494\lstset{language=C}
495\lstinputlisting{testbed_test.c}
496The source code for the above listing can be found at
497\url{https://gnunet.org/git/gnunet.git/tree/doc/testbed_test.c}
498or in the {\tt doc/} folder of your repository check-out.
499After installing GNUnet, the above source code can be compiled as:
500\lstset{language=bash}
501\begin{lstlisting}
502$ export CPPFLAGS="-I/path/to/gnunet/headers"
503$ export LDFLAGS="-L/path/to/gnunet/libraries"
504$ gcc $CPPFLAGS $LDFLAGS -o testbed-test testbed_test.c -lgnunettestbed -lgnunetdht -lgnunetutil
505$ touch template.conf # Generate (empty) configuration
506$ ./testbed-test # run it (press CTRL-C to stop)
507\end{lstlisting}
508The \texttt{CPPFLAGS} and \texttt{LDFLAGS} are necessary if GNUnet is installed
509into a different directory other than \texttt{/usr/local}.
510
511All of testbed API's peer management functions treat management actions as
512operations and return operation handles. It is expected that the operations
513begin immediately, but they may get delayed (to balance out load on the system).
514The program using the API then has to take care of marking the operation as
515``done'' so that its associated resources can be freed immediately and other
516waiting operations can be executed. Operations will be canceled if they are
517marked as ``done'' before their completion.
518
519An operation is treated as completed when it succeeds or fails. Completion of
520an operation is either conveyed as events through \textit{controller event
521 callback} or through respective operation completion callbacks. In functions
522which support completion notification through both controller event callback and
523operation completion callback, first the controller event callback will be
524called. If the operation is not marked as done in that callback or if the
525callback is given as NULL when creating the operation, the operation completion
526callback will be called. The API documentation shows which event are to be
527expected in the controller event notifications. It also documents any
528exceptional behaviour.
529
530Once the peers are started, test cases often need to connect some of the peers'
531services. Normally, opening a connect to a peer's service requires the peer's
532configuration. While using testbed, the testbed automatically generates
533per-peer configuration. Accessing those configurations directly through file
534system is discouraged as their locations are dynamically created and will be
535different among various runs of testbed. To make access to these configurations
536easy, testbed API provides the function
537\texttt{GNUNET\_TESTBED\_service\_connect()}. This function fetches the
538configuration of a given peer and calls the \textit{Connect Adapter}.
539In the example code, it is the \texttt{dht\_ca}. A connect adapter is expected
540to open the connection to the needed service by using the provided configuration
541and return the created service connection handle. Successful connection to the
542needed service is signaled through \texttt{service\_connect\_comp\_cb}.
543
544A dual to connect adapter is the \textit{Disconnect Adapter}. This callback is
545called after the connect adapter has been called when the operation from
546\texttt{GNUNET\_TESTBED\_service\_connect()} is marked as ``done''. It has to
547disconnect from the service with the provided service handle (\texttt{op\_result}).
548
549\exercise{Find out how many peers you can run on your system.}
550
551\exercise{Find out how to create a 2D torus topology by changing the
552 options in the configuration file.\footnote{See \url{https://gnunet.org/supported-topologies}}
553 Then use the DHT API to store and retrieve values in the
554 network.}
555
556
557\section{Developing Applications}
558
559\subsection{gnunet-ext}
560To develop a new peer-to-peer application or to extend GNUnet we provide
561a template build system for writing GNUnet extensions in C. It can be
562obtained as follows:
563
564\lstset{language=bash}
565\begin{lstlisting}
566$ git clone https://gnunet.org/git/gnunet-ext
567$ cd gnunet-ext/
568$ ./bootstrap
569$ ./configure --prefix=$PREFIX --with-gnunet=$PREFIX
570$ make
571$ make install
572$ make check
573\end{lstlisting}
574% $
575
576The GNUnet ext template includes examples and a working buildsystem for a new GNUnet service.
577A common GNUnet service consists of the following parts which will be discussed in detail in the
578remainder of this document. The functionality of a GNUnet service is implemented in:
579
580\begin{itemize}
581\itemsep0em
582 \item the GNUnet service (\lstinline|gnunet-ext/src/ext/gnunet-service-ext.c|)
583 \item the client API (\lstinline|gnunet-ext/src/ext/ext_api.c|)
584 \item the client application using the service API (\lstinline|gnunet-ext/src/ext/gnunet-ext.c|)
585
586
587\end{itemize}
588
589The interfaces for these entities are defined in:
590\begin{itemize}
591\itemsep0em
592 \item client API interface (\lstinline|gnunet-ext/src/ext/ext.h|)
593 \item the service interface (\lstinline|gnunet-ext/src/include/gnunet_service_SERVICE.h|)
594 \item the P2P protocol (\lstinline|gnunet-ext/src/include/gnunet_protocols_ext.h|)
595\end{itemize}
596
597
598In addition the \texttt{ext} systems provides:
599\begin{itemize}
600\itemsep0em
601 \item a test testing the API (\lstinline|gnunet-ext/src/ext/test_ext_api.c|)
602 \item a configuration template for the service (\lstinline|gnunet-ext/src/ext/ext.conf.in|)
603\end{itemize}
604
605
606\subsection{Adapting the Template}
607
608The first step for writing any extension with a new service is to
609ensure that the {\tt ext.conf.in} file contains entries for the
610\texttt{UNIXPATH}, \texttt{PORT} and \texttt{BINARY} for the service in a section named after
611the service.
612
613If you want to adapt the template rename the {\tt ext.conf.in} to match your
614services name, you have to modify the \texttt{AC\_OUTPUT} section in {\tt configure.ac}
615in the \texttt{gnunet-ext} root.
616
617\section{Writing a Client Application}
618
619When writing any client application (for example, a command-line
620tool), the basic structure is to start with the {\tt
621 GNUNET\_PROGRAM\_run} function. This function will parse
622command-line options, setup the scheduler and then invoke the {\tt
623 run} function (with the remaining non-option arguments) and a handle
624to the parsed configuration (and the configuration file name that was
625used, which is typically not needed):
626
627\lstset{language=C}
628\begin{lstlisting}
629#include <gnunet/platform.h>
630#include <gnunet/gnunet_util_lib.h>
631
632static int ret;
633
634static void
635run (void *cls,
636 char *const *args,
637 const char *cfgfile,
638 const struct GNUNET_CONFIGURATION_Handle *cfg)
639{
640 // main code here
641 ret = 0;
642}
643
644int
645main (int argc, char *const *argv)
646{
647 struct GNUNET_GETOPT_CommandLineOption options[] = {
648 GNUNET_GETOPT_OPTION_END
649 };
650 return (GNUNET_OK ==
651 GNUNET_PROGRAM_run (argc,
652 argv,
653 "binary-name",
654 gettext_noop ("binary description text"),
655 options, &run, NULL)) ? ret : 1;
656}
657\end{lstlisting}
658
659\subsection{Handling command-line options}
660
661Options can then be added easily by adding global variables and
662expanding the {\tt options} array. For example, the following would
663add a string-option and a binary flag (defaulting to {\tt NULL} and
664{\tt GNUNET\_NO} respectively):
665
666\lstset{language=C}
667\begin{lstlisting}
668static char *string_option;
669static int a_flag;
670
671// ...
672 struct GNUNET_GETOPT_CommandLineOption options[] = {
673 GNUNET_GETOPT_option_string ('s', "name", "SOMESTRING",
674 gettext_noop ("text describing the string_option NAME"),
675 &string_option},
676 GNUNET_GETOPT_option_flag ('f', "flag",
677 gettext_noop ("text describing the flag option"),
678 &a_flag),
679 GNUNET_GETOPT_OPTION_END
680 };
681 string_option = NULL;
682 a_flag = GNUNET_SYSERR;
683// ...
684\end{lstlisting}
685
686Issues such as displaying some helpful text describing options using
687the {\tt --help} argument and error handling are taken care of when
688using this approach. Other {\tt GNUNET\_GETOPT\_}-functions can be used
689to obtain integer value options, increment counters, etc. You can
690even write custom option parsers for special circumstances not covered
691by the available handlers. To check if an argument was specified by the
692user you initialize the variable with a specific value (e.g. NULL for
693a string and GNUNET\_SYSERR for a integer) and check after parsing
694happened if the values were modified.
695
696Inside the {\tt run} method, the program would perform the
697application-specific logic, which typically involves initializing and
698using some client library to interact with the service. The client
699library is supposed to implement the IPC whereas the service provides
700more persistent P2P functions.
701
702\exercise{Add a few command-line options and print them inside
703of {\tt run}. What happens if the user gives invalid arguments?}
704
705\subsection{Writing a Client Library}
706
707The first and most important step in writing a client library is to
708decide on an API for the library. Typical API calls include
709connecting to the service, performing application-specific requests
710and cleaning up. Many examples for such service APIs can be found
711in the {\tt gnunet/src/include/gnunet\_*\_service.h} files.
712
713Then, a client-service protocol needs to be designed. This typically
714involves defining various message formats in a header that will be
715included by both the service and the client library (but is otherwise
716not shared and hence located within the service's directory and not
717installed by {\tt make install}). Each message must start with a {\tt
718 struct GNUNET\_MessageHeader} and must be shorter than 64k. By
719convention, all fields in IPC (and P2P) messages must be in big-endian
720format (and thus should be read using {\tt ntohl} and similar
721functions and written using {\tt htonl} and similar functions).
722Unique message types must be defined for each message struct in the
723{\tt gnunet\_protocols.h} header (or an extension-specific include
724file).
725
726\subsubsection{Connecting to the Service}
727
728Before a client library can implement the application-specific protocol
729with the service, a connection must be created:
730
731\lstset{language=C}
732\begin{lstlisting}
733 struct GNUNET_MQ_MessageHandlers handlers[] = {
734 // ...
735 GNUNET_MQ_handler_end ()
736 };
737 struct GNUNET_MQ_Handle *mq;
738
739 mq = GNUNET_CLIENT_connect (cfg, "service-name", handlers, &error_cb, NULL);
740\end{lstlisting}
741
742As a result a {\tt GNUNET\_MQ\_Handle} is returned
743which can to used henceforth to transmit messages to
744the service.
745The complete MQ API can be found in {\tt gnunet\_mq\_lib.h}.
746The {\tt hanlders} array in the example above is incomplete.
747Here is where you will define which messages you expect to
748receive from the service, and which functions handle them.
749The {\tt error\_cb} is a function that is to be called whenever
750there are errors communicating with the service.
751
752\subsubsection{Sending messages}
753
754In GNUnet, messages are always sent beginning with a {\tt struct GNUNET\_MessageHeader}
755in big endian format. This header defines the size and the type of the
756message, the payload follows after this header.
757
758\lstset{language=C}
759\begin{lstlisting}
760struct GNUNET_MessageHeader
761{
762 uint16_t size GNUNET_PACKED;
763 uint16_t type GNUNET_PACKED;
764};
765\end{lstlisting}
766
767Existing message types are defined in {\tt gnunet\_protocols.h}\\
768A common way to create a message is with an envelope:
769
770\lstset{language=C}
771\begin{lstlisting}
772struct GNUNET_MQ_Envelope *env;
773struct GNUNET_MessageHeader *msg;
774
775env = GNUNET_MQ_msg_extra (msg, payload_size, GNUNET_MY_MESSAGE_TYPE);
776memcpy (&msg[1], &payload, payload_size);
777// Send message via message queue 'mq'
778GNUNET_mq_send (mq, env);
779\end{lstlisting}
780
781\exercise{Define a message struct that includes a 32-bit
782unsigned integer in addition to the standard GNUnet MessageHeader.
783Add a C struct and define a fresh protocol number for your message.
784(Protocol numbers in gnunet-ext are defined in \lstinline|gnunet-ext/src/include/gnunet_protocols_ext.h|)}
785
786\exercise{Find out how you can determine the number of messages in a message queue.}
787
788\exercise{Find out how you can determine when a message you have queued was actually transmitted.}
789
790\exercise{Define a helper function to transmit a 32-bit
791unsigned integer (as payload) to a service using some given client
792handle.}
793
794
795\subsubsection{Receiving Replies from the Service}
796
797Clients can receive messages from the service using the handlers
798specified in the {\tt handlers} array we specified when connecting
799to the service. Entries in the the array are usually created using
800one of two macros, depending on whether the message is fixed size
801or variable size. Variable size messages are managed using two
802callbacks, one to check that the message is well-formed, the other
803to actually process the message. Fixed size messages are fully
804checked by the MQ-logic, and thus only need to provide the handler
805to process the message. Note that the prefixes {\tt check\_}
806and {\tt handle\_} are mandatory.
807
808\lstset{language=c}
809\begin{lstlisting}
810static void
811handle_fix (void *cls, const struct MyMessage *msg)
812{
813 // process 'msg'
814}
815
816static int
817check_var (void *cls, const struct MyVarMessage *msg)
818{
819 // check 'msg' is well-formed
820 return GNUNET_OK;
821}
822
823static void
824handle_var (void *cls, const struct MyVarMessage *msg)
825{
826 // process 'msg'
827}
828
829struct GNUNET_MQ_MessageHandler handlers[] = {
830 GNUNET_MQ_hd_fixed_size (fix,
831 GNUNET_MESSAGE_TYPE_MY_FIX,
832 struct MyMessage,
833 NULL),
834 GNUNET_MQ_hd_fixed_size (var,
835 GNUNET_MESSAGE_TYPE_MY_VAR,
836 struct MyVarMessage,
837 NULL),
838
839 GNUNET_MQ_handler_end ()
840};
841\end{lstlisting}
842
843\exercise{Expand your helper function to receive a response message
844 (for example, containing just the {\tt struct GNUnet MessageHeader}
845 without any payload). Upon receiving the service's response, you
846 should call a callback provided to your helper function's API.}
847
848\exercise{Figure out where you can pass values to the closures ({\tt cls}).}
849
850
851\subsection{Writing a user interface}
852
853Given a client library, all it takes to access a service now is to
854combine calls to the client library with parsing command-line
855options.
856
857\exercise{Call your client API from your {\tt run()} method in your
858 client application to send a request to the service. For example,
859 send a 32-bit integer value based on a number given at the
860 command-line to the service.}
861
862
863
864\section{Writing a Service}
865
866Before you can test the client you've written so far, you'll need to also
867implement the corresponding service.
868
869
870\subsection{Code Placement}
871
872New services are placed in their own subdirectory under {\tt gnunet/src}.
873This subdirectory should contain the API implementation file {\tt SERVICE\_api.c},
874the description of the client-service protocol {\tt SERVICE.h} and P2P protocol
875{\tt SERVICE\_protocol.h}, the implementation of the service itself
876{\tt gnunet-service-SERVICE.h} and several files for tests, including test code
877and configuration files.
878
879\subsection{Starting a Service}
880
881The key API definition for creating a service is the {\tt GNUNET\_SERVICE\_MAIN} macro:
882\lstset{language=C}
883\begin{lstlisting}
884GNUNET_SERVICE_MAIN
885("service-name",
886 GNUNET_SERVICE_OPTION_NONE,
887 &run,
888 &client_connect_cb,
889 &client_disconnect_cb,
890 NULL,
891 GNUNET_MQ_hd_fixed_size (...),
892 GNUNET_MQ_hd_var_size (...),
893 GNUNET_MQ_handler_end ());
894\end{lstlisting}
895
896In addition to the service name and flags, the macro takes three
897functions, typically called {\tt run}, {\tt client\_connect\_cb} and
898{\tt client\_disconnect\_cb} as well as an array of message handlers
899that will be called for incoming messages from clients.
900
901A minimal version of the three central service funtions would look
902like this:
903
904\lstset{language=c}
905\begin{lstlisting}
906static void
907run (void *cls,
908 const struct GNUNET_CONFIGURATION_Handle *c,
909 struct GNUNET_SERVICE_Handle *service)
910{
911}
912
913static void *
914client_connect_cb (void *cls,
915 struct GNUNET_SERVICE_Client *c,
916 struct GNUNET_MQ_Handle *mq)
917{
918 return c;
919}
920
921static void
922client_disconnect_cb (void *cls,
923 struct GNUNET_SERVICE_Client *c,
924 void *internal_cls)
925{
926 GNUNET_assert (c == internal_cls);
927}
928\end{lstlisting}
929
930\exercise{Write a stub service that processes no messages at all
931 in your code. Create a default configuration for it, integrate it
932 with the build system and start the service from {\tt
933 gnunet-service-arm} using {\tt gnunet-arm -i NAME}.}
934
935\exercise{Figure out how to set the closure ({\tt cls}) for handlers
936 of a service.}
937
938\exercise{Figure out how to send messages from the service back to the
939 client.}
940
941Each handler function in the service {\bf must} eventually (possibly in some
942asynchronous continuation) call {\tt GNUNET\_SERVICE\_client\_continue()}.
943Only after this call additional messages from the same client may
944be processed. This way, the service can throttle processing messages
945from the same client.
946
947\exercise{Change the service to ``handle'' the message from your
948 client (for now, by printing a message). What happens if you
949 forget to call {\tt GNUNET\_SERVICE\_client\_continue()}?}
950
951
952\section{Interacting directly with other Peers using the CORE Service}
953
954FIXME: This section still needs to be updated to the lastest API!
955
956One of the most important services in GNUnet is the \texttt{CORE} service
957managing connections between peers and handling encryption between peers.
958
959One of the first things any service that extends the P2P protocol typically does
960is connect to the \texttt{CORE} service using:
961
962\lstset{language=C}
963\begin{lstlisting}
964#include <gnunet/gnunet_core_service.h>
965
966struct GNUNET_CORE_Handle *
967GNUNET_CORE_connect (const struct GNUNET_CONFIGURATION_Handle *cfg,
968 void *cls,
969 GNUNET_CORE_StartupCallback init,
970 GNUNET_CORE_ConnectEventHandler connects,
971 GNUNET_CORE_DisconnectEventHandler disconnects,
972 const struct GNUNET_MQ_MessageHandler *handlers);
973\end{lstlisting}
974
975\subsection{New P2P connections}
976
977Before any traffic with a different peer can be exchanged, the peer must be
978known to the service. This is notified by the \texttt{CORE} {\tt connects} callback,
979which communicates the identity of the new peer to the service:
980
981\lstset{language=C}
982\begin{lstlisting}
983void *
984connects (void *cls,
985 const struct GNUNET_PeerIdentity *peer,
986 struct GNUNET_MQ_Handle *mq)
987{
988 return mq;
989}
990\end{lstlisting}
991
992Note that whatever you return from {\tt connects} is given as the
993{\it cls} argument to the message handlers for messages from
994the respective peer.
995
996\exercise{Create a service that connects to the \texttt{CORE}. Then
997start (and connect) two peers and print a message once your connect
998callback is invoked.}
999
1000\subsection{Receiving P2P Messages}
1001
1002To receive messages from \texttt{CORE}, you pass the desired
1003{\em handlers} to the {\tt GNUNET\_CORE\_connect()} function,
1004just as we showed for services.
1005
1006It is your responsibility to process messages fast enough or
1007to implement flow control. If an application does not process
1008CORE messages fast enough, CORE will randomly drop messages
1009to not keep a very long queue in memory.
1010
1011\exercise{Start one peer with a new service that has a message
1012handler and start a second peer that only has your ``old'' service
1013without message handlers. Which ``connect'' handlers are invoked when
1014the two peers are connected? Why?}
1015
1016
1017\subsection{Sending P2P Messages}
1018
1019You can transmit messages to other peers using the {\it mq} you were
1020given during the {\tt connect} callback. Note that the {\it mq}
1021automatically is released upon {\tt disconnect} and that you must
1022not use it afterwards.
1023
1024It is your responsibility to not over-fill the message queue, GNUnet
1025will send the messages roughly in the order given as soon as possible.
1026
1027\exercise{Write a service that upon connect sends messages as
1028fast as possible to the other peer (the other peer should run a
1029service that ``processes'' those messages). How fast is the
1030transmission? Count using the STATISTICS service on both ends. Are
1031messages lost? How can you transmit messages faster? What happens if
1032you stop the peer that is receiving your messages?}
1033
1034
1035\subsection{End of P2P connections}
1036
1037If a message handler returns {\tt GNUNET\_SYSERR}, the remote peer shuts down or
1038there is an unrecoverable network disconnection, CORE notifies the service that
1039the peer disconnected. After this notification no more messages will be received
1040from the peer and the service is no longer allowed to send messages to the peer.
1041The disconnect callback looks like the following:
1042
1043\lstset{language=C}
1044\begin{lstlisting}
1045void
1046disconnects (void *cls,
1047 const struct GNUNET_PeerIdentity * peer)
1048{
1049 /* Remove peer's identity from known peers */
1050 /* Make sure no messages are sent to peer from now on */
1051}
1052\end{lstlisting}
1053
1054\exercise{Fix your service to handle peer disconnects.}
1055
1056\section{Storing peer-specific data using the PEERSTORE service}
1057
1058GNUnet's PEERSTORE service offers a persistorage for arbitrary peer-specific data.
1059Other GNUnet services can use the PEERSTORE to store, retrieve and monitor data records.
1060Each data record stored with PEERSTORE contains the following fields:
1061
1062\begin{itemize}
1063\itemsep0em
1064 \item subsystem: Name of the subsystem responsible for the record.
1065 \item peerid: Identity of the peer this record is related to.
1066 \item key: a key string identifying the record.
1067 \item value: binary record value.
1068 \item expiry: record expiry date.
1069\end{itemize}
1070
1071The first step is to start a connection to the PEERSTORE service:
1072\begin{lstlisting}
1073#include "gnunet_peerstore_service.h"
1074
1075peerstore_handle = GNUNET_PEERSTORE_connect (cfg);
1076\end{lstlisting}
1077The service handle \lstinline|peerstore_handle| will be needed for all subsequent
1078PEERSTORE operations.
1079
1080\subsection{Storing records}
1081
1082To store a new record, use the following function:
1083\begin{lstlisting}
1084struct GNUNET_PEERSTORE_StoreContext *
1085GNUNET_PEERSTORE_store (struct GNUNET_PEERSTORE_Handle *h,
1086 const char *sub_system,
1087 const struct GNUNET_PeerIdentity *peer,
1088 const char *key,
1089 const void *value,
1090 size_t size,
1091 struct GNUNET_TIME_Absolute expiry,
1092 enum GNUNET_PEERSTORE_StoreOption options,
1093 GNUNET_PEERSTORE_Continuation cont,
1094 void *cont_cls);
1095\end{lstlisting}
1096
1097The \lstinline|options| parameter can either be \lstinline|GNUNET_PEERSTORE_STOREOPTION_MULTIPLE|
1098which means that multiple values can be stored under the same key combination (subsystem, peerid, key),
1099or \lstinline|GNUNET_PEERSTORE_STOREOPTION_REPLACE| which means that PEERSTORE will replace any
1100existing values under the given key combination (subsystem, peerid, key) with the new given value.
1101
1102The continuation function \lstinline|cont| will be called after the store request is successfully
1103sent to the PEERSTORE service. This does not guarantee that the record is successfully stored, only
1104that it was received by the service.
1105
1106The \lstinline|GNUNET_PEERSTORE_store| function returns a handle to the store operation. This handle
1107can be used to cancel the store operation only before the continuation function is called:
1108\begin{lstlisting}
1109void
1110GNUNET_PEERSTORE_store_cancel (struct GNUNET_PEERSTORE_StoreContext *sc);
1111\end{lstlisting}
1112
1113\subsection{Retrieving records}
1114
1115To retrieve stored records, use the following function:
1116\begin{lstlisting}
1117struct GNUNET_PEERSTORE_IterateContext *
1118GNUNET_PEERSTORE_iterate (struct GNUNET_PEERSTORE_Handle *h,
1119 const char *sub_system,
1120 const struct GNUNET_PeerIdentity *peer,
1121 const char *key,
1122 struct GNUNET_TIME_Relative timeout,
1123 GNUNET_PEERSTORE_Processor callback,
1124 void *callback_cls);
1125\end{lstlisting}
1126The values of \lstinline|peer| and \lstinline|key| can be \lstinline|NULL|. This allows the
1127iteration over values stored under any of the following key combinations:
1128\begin{itemize}
1129\itemsep0em
1130 \item (subsystem)
1131 \item (subsystem, peerid)
1132 \item (subsystem, key)
1133 \item (subsystem, peerid, key)
1134\end{itemize}
1135
1136The \lstinline|callback| function will be called once with each retrieved record and once
1137more with a \lstinline|NULL| record to signal the end of results.
1138
1139The \lstinline|GNUNET_PEERSTORE_iterate| function returns a handle to the iterate operation. This
1140handle can be used to cancel the iterate operation only before the callback function is called with
1141a \lstinline|NULL| record.
1142
1143\subsection{Monitoring records}
1144
1145PEERSTORE offers the functionality of monitoring for new records stored under a specific key
1146combination (subsystem, peerid, key). To start the monitoring, use the following function:
1147\begin{lstlisting}
1148struct GNUNET_PEERSTORE_WatchContext *
1149GNUNET_PEERSTORE_watch (struct GNUNET_PEERSTORE_Handle *h,
1150 const char *sub_system,
1151 const struct GNUNET_PeerIdentity *peer,
1152 const char *key,
1153 GNUNET_PEERSTORE_Processor callback,
1154 void *callback_cls);
1155\end{lstlisting}
1156
1157Whenever a new record is stored under the given key combination, the \lstinline|callback| function
1158will be called with this new record. This will continue until the connection to the PEERSTORE service
1159is broken or the watch operation is canceled:
1160\begin{lstlisting}
1161void
1162GNUNET_PEERSTORE_watch_cancel (struct GNUNET_PEERSTORE_WatchContext *wc);
1163\end{lstlisting}
1164
1165\subsection{Disconnecting from PEERSTORE}
1166
1167When the connection to the PEERSTORE service is no longer needed, disconnect using the following
1168function:
1169\begin{lstlisting}
1170void
1171GNUNET_PEERSTORE_disconnect (struct GNUNET_PEERSTORE_Handle *h, int sync_first);
1172\end{lstlisting}
1173
1174If the \lstinline|sync_first| flag is set to \lstinline|GNUNET_YES|, the API will delay the
1175disconnection until all store requests are received by the PEERSTORE service. Otherwise,
1176it will disconnect immediately.
1177
1178
1179\section{Using the DHT}
1180
1181The DHT allows to store data so other peers in the P2P network can
1182access it and retrieve data stored by any peers in the network.
1183This section will explain how to use the DHT. Of course, the first
1184thing to do is to connect to the DHT service:
1185\lstset{language=C}
1186\begin{lstlisting}
1187dht_handle = GNUNET_DHT_connect (cfg, parallel_requests);
1188\end{lstlisting}
1189The second parameter indicates how many requests in parallel to expect.
1190It is not a hard limit, but a good approximation will make the DHT more
1191efficient.
1192
1193\subsection{Storing data in the DHT}
1194Since the DHT is a dynamic environment (peers join and leave frequently)
1195the data that we put in the DHT does not stay there indefinitely. It is
1196important to ``refresh'' the data periodically by simply storing it again,
1197in order to make sure other peers can access it.
1198
1199The put API call offers a callback to signal that the PUT request has been
1200sent. This does not guarantee that the data is accessible to others peers,
1201or even that is has been stored, only that the service has requested to
1202a neighboring peer the retransmission of the PUT request towards its final
1203destination. Currently there is no feedback about whether or not the data
1204has been sucessfully stored or where it has been stored. In order to improve
1205the availablilty of the data and to compensate for possible errors, peers leaving
1206and other unfavorable events, just make several PUT requests!
1207
1208\lstset{language=C}
1209\begin{lstlisting}
1210static void
1211message_sent_cont (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1212{
1213 // Request has left local node
1214}
1215
1216struct GNUNET_DHT_PutHandle *
1217GNUNET_DHT_put (struct GNUNET_DHT_Handle *handle,
1218 const struct GNUNET_HashCode *key,
1219 uint32_t desired_replication_level,
1220 enum GNUNET_DHT_RouteOption options,
1221 enum GNUNET_BLOCK_Type type, size_t size, const void *data,
1222 struct GNUNET_TIME_Absolute exp,
1223 struct GNUNET_TIME_Relative timeout,
1224 GNUNET_DHT_PutContinuation cont, void *cont_cls)
1225\end{lstlisting}
1226
1227\exercise{Store a value in the DHT periodically to make sure it is available
1228over time. You might consider using the function GNUNET\_SCHEDULER\_add\_delayed and
1229call GNUNET\_DHT\_put from inside a helper function.}
1230
1231
1232\subsection{Obtaining data from the DHT}
1233As we saw in the previous example, the DHT works in an asynchronous mode.
1234Each request to the DHT is executed ``in the background'' and the API
1235calls return immediately. In order to receive results from the DHT, the
1236API provides a callback. Once started, the request runs in the service,
1237the service will try to get as many results as possible (filtering out
1238duplicates) until the timeout expires or we explicitly stop the request.
1239It is possible to give a ``forever'' timeout with
1240{\tt GNUNET\_TIME\_UNIT\_FOREVER\_REL}.
1241
1242If we give a route option {\tt GNUNET\_DHT\_RO\_RECORD\_ROUTE} the callback
1243will get a list of all the peers the data has travelled, both on the PUT
1244path and on the GET path.
1245\lstset{language=C}
1246\begin{lstlisting}
1247static void
1248get_result_iterator (void *cls, struct GNUNET_TIME_Absolute expiration,
1249 const struct GNUNET_HashCode *key,
1250 const struct GNUNET_PeerIdentity *get_path,
1251 unsigned int get_path_length,
1252 const struct GNUNET_PeerIdentity *put_path,
1253 unsigned int put_path_length,
1254 enum GNUNET_BLOCK_Type type, size_t size, const void *data)
1255{
1256 // Optionally:
1257 GNUNET_DHT_get_stop (get_handle);
1258}
1259
1260get_handle =
1261 GNUNET_DHT_get_start (dht_handle,
1262 block_type,
1263 &key,
1264 replication,
1265 GNUNET_DHT_RO_NONE,
1266 NULL,
1267 0,
1268 &get_result_iterator,
1269 cls)
1270\end{lstlisting}
1271
1272\exercise{Store a value in the DHT and after a while retrieve it. Show the IDs of all
1273the peers the requests have gone through. In order to convert a peer ID to a string, use
1274the function GNUNET\_i2s. Pay attention to the route option parameters in both calls!}
1275
1276\subsection{Implementing a block plugin}
1277
1278In order to store data in the DHT, it is necessary to provide a block
1279plugin. The DHT uses the block plugin to ensure that only well-formed
1280requests and replies are transmitted over the network.
1281
1282The block plugin should be put in a file {\tt
1283 plugin\_block\_SERVICE.c} in the service's respective directory. The
1284mandatory functions that need to be implemented for a block plugin are
1285described in the following sections.
1286
1287\subsubsection{Validating requests and replies}
1288
1289The evaluate function should validate a reply or a request. It returns
1290a {\tt GNUNET\_BLOCK\_EvaluationResult}, which is an enumeration. All
1291possible answers are in {\tt gnunet\_block\_lib.h}. The function will
1292be called with a {\tt reply\_block} argument of {\tt NULL} for
1293requests. Note that depending on how {\tt evaluate} is called, only
1294some of the possible return values are valid. The specific meaning of
1295the {\tt xquery} argument is application-specific. Applications that
1296do not use an extended query should check that the {\tt xquery\_size}
1297is zero. The block group is typically used to filter duplicate
1298replies.
1299
1300\lstset{language=C}
1301\begin{lstlisting}
1302static enum GNUNET_BLOCK_EvaluationResult
1303block_plugin_SERVICE_evaluate (void *cls,
1304 enum GNUNET_BLOCK_Type type,
1305 struct GNUNET_BlockGroup *bg,
1306 const GNUNET_HashCode *query,
1307 const void *xquery,
1308 size_t xquery_size,
1309 const void *reply_block,
1310 size_t reply_block_size)
1311{
1312 // Verify type, block and bg
1313}
1314\end{lstlisting}
1315
1316Note that it is mandatory to detect duplicate replies in this function
1317and return the respective status code. Duplicate detection is
1318typically done using the Bloom filter block group provided by {\tt
1319 libgnunetblockgroup.so}. Failure to do so may cause replies to
1320circle in the network.
1321
1322\subsubsection{Deriving a key from a reply}
1323
1324The DHT can operate more efficiently if it is possible to derive a key
1325from the value of the corresponding block. The {\tt get\_key}
1326function is used to obtain the key of a block --- for example, by
1327means of hashing. If deriving the key is not possible, the function
1328should simply return {\tt GNUNET\_SYSERR} (the DHT will still work
1329just fine with such blocks).
1330
1331\lstset{language=C}
1332\begin{lstlisting}
1333static int
1334block_plugin_SERVICE_get_key (void *cls, enum GNUNET_BLOCK_Type type,
1335 const void *block, size_t block_size,
1336 struct GNUNET_HashCode *key)
1337{
1338 // Store the key in the key argument, return GNUNET_OK on success.
1339}
1340\end{lstlisting}
1341
1342\subsubsection{Initialization of the plugin}
1343
1344The plugin is realized as a shared C library. The library must export
1345an initialization function which should initialize the plugin. The
1346initialization function specifies what block types the plugin cares
1347about and returns a struct with the functions that are to be used for
1348validation and obtaining keys (the ones just defined above).
1349
1350\lstset{language=C}
1351\begin{lstlisting}
1352void *
1353libgnunet_plugin_block_SERVICE_init (void *cls)
1354{
1355 static enum GNUNET_BLOCK_Type types[] =
1356 {
1357 GNUNET_BLOCK_TYPE_SERVICE_BLOCKYPE,
1358 GNUNET_BLOCK_TYPE_ANY
1359 };
1360 struct GNUNET_BLOCK_PluginFunctions *api;
1361
1362 api = GNUNET_new (struct GNUNET_BLOCK_PluginFunctions);
1363 api->evaluate = &block_plugin_SERICE_evaluate;
1364 api->get_key = &block_plugin_SERVICE_get_key;
1365 api->types = types;
1366 return api;
1367}
1368\end{lstlisting}
1369
1370\subsubsection{Shutdown of the plugin}
1371
1372Following GNUnet's general plugin API concept, the plugin must
1373export a second function for cleaning up. It usually does very
1374little.
1375
1376\lstset{language=C}
1377\begin{lstlisting}
1378void *
1379libgnunet_plugin_block_SERVICE_done (void *cls)
1380{
1381 struct GNUNET_TRANSPORT_PluginFunctions *api = cls;
1382
1383 GNUNET_free (api);
1384 return NULL;
1385}
1386\end{lstlisting}
1387
1388
1389\subsubsection{Integration of the plugin with the build system}
1390
1391In order to compile the plugin, the {\tt Makefile.am} file for the
1392service \texttt{SERVICE} should contain a rule similar to this:
1393
1394\lstset{language=make}
1395\begin{lstlisting}
1396 plugindir = $(libdir)/gnunet
1397
1398 plugin_LTLIBRARIES = \
1399 libgnunet_plugin_block_ext.la
1400 libgnunet_plugin_block_ext_la_SOURCES = \
1401 plugin_block_ext.c
1402 libgnunet_plugin_block_ext_la_LIBADD = \
1403 $(prefix)/lib/libgnunethello.la \
1404 $(prefix)/lib/libgnunetblock.la \
1405 $(prefix)/lib/libgnunetutil.la
1406 libgnunet_plugin_block_ext_la_LDFLAGS = \
1407 $(GN_PLUGIN_LDFLAGS)
1408 libgnunet_plugin_block_ext_la_DEPENDENCIES = \
1409 $(prefix)/lib/libgnunetblock.la
1410\end{lstlisting}
1411% $
1412
1413
1414\exercise{Write a block plugin that accepts all queries
1415and all replies but prints information about queries and replies
1416when the respective validation hooks are called.}
1417
1418
1419
1420\subsection{Monitoring the DHT}
1421It is possible to monitor the functioning of the local DHT service. When monitoring
1422the DHT, the service will alert the monitoring program of any events,
1423both started locally or received for routing from another peer. The are three different
1424types of events possible: a GET request, a PUT request or a response (a reply to
1425a GET).
1426
1427Since the different events have different associated data, the API gets 3
1428different callbacks (one for each message type) and optional type and key parameters,
1429to allow for filtering of messages. When an event happens, the appropiate callback
1430is called with all the information about the event.
1431\lstset{language=C}
1432\begin{lstlisting}
1433static void
1434get_callback (void *cls,
1435 enum GNUNET_DHT_RouteOption options,
1436 enum GNUNET_BLOCK_Type type,
1437 uint32_t hop_count,
1438 uint32_t desired_replication_level,
1439 unsigned int path_length,
1440 const struct GNUNET_PeerIdentity *path,
1441 const struct GNUNET_HashCode * key)
1442{
1443}
1444
1445
1446static void
1447get_resp_callback (void *cls,
1448 enum GNUNET_BLOCK_Type type,
1449 const struct GNUNET_PeerIdentity *get_path,
1450 unsigned int get_path_length,
1451 const struct GNUNET_PeerIdentity *put_path,
1452 unsigned int put_path_length,
1453 struct GNUNET_TIME_Absolute exp,
1454 const struct GNUNET_HashCode * key,
1455 const void *data,
1456 size_t size)
1457{
1458}
1459
1460
1461static void
1462put_callback (void *cls,
1463 enum GNUNET_DHT_RouteOption options,
1464 enum GNUNET_BLOCK_Type type,
1465 uint32_t hop_count,
1466 uint32_t desired_replication_level,
1467 unsigned int path_length,
1468 const struct GNUNET_PeerIdentity *path,
1469 struct GNUNET_TIME_Absolute exp,
1470 const struct GNUNET_HashCode * key,
1471 const void *data,
1472 size_t size)
1473{
1474}
1475
1476
1477monitor_handle = GNUNET_DHT_monitor_start (dht_handle,
1478 block_type,
1479 key,
1480 &get_callback,
1481 &get_resp_callback,
1482 &put_callback,
1483 cls);
1484\end{lstlisting}
1485
1486
1487\section{Debugging with {\tt gnunet-arm}}
1488
1489Even if services are managed by {\tt gnunet-arm}, you can start them with
1490{\tt gdb} or {\tt valgrind}. For example, you could add the following lines
1491to your configuration file to start the DHT service in a {\tt gdb} session in a
1492fresh {\tt xterm}:
1493
1494\begin{verbatim}
1495[dht]
1496PREFIX=xterm -e gdb --args
1497\end{verbatim}
1498
1499Alternatively, you can stop a service that was started via ARM and run it manually:
1500
1501\lstset{language=bash}
1502\begin{lstlisting}
1503$ gnunet-arm -k dht
1504$ gdb --args gnunet-service-dht -L DEBUG
1505$ valgrind gnunet-service-dht -L DEBUG
1506\end{lstlisting}
1507% $
1508
1509Assuming other services are well-written, they will automatically re-integrate the
1510restarted service with the peer.
1511
1512GNUnet provides a powerful logging mechanism providing log levels \texttt{ERROR},
1513\texttt{WARNING}, \texttt{INFO} and \texttt{DEBUG}. The current log level is
1514configured using the \lstinline|$GNUNET_FORCE_LOG| environmental variable.
1515The \texttt{DEBUG} level is only available if \lstinline|--enable-logging=verbose| was used when
1516running \texttt{configure}. More details about logging can be found under
1517\url{https://gnunet.org/logging}.
1518
1519You should also probably enable the creation of core files, by setting
1520{\tt ulimit}, and echo'ing 1 into {\tt /proc/sys/kernel/core\_uses\_pid}.
1521Then you can investigate the core dumps with {\tt gdb}, which is often
1522the fastest method to find simple errors.
1523
1524\exercise{Add a memory leak to your service and obtain a trace
1525pointing to the leak using {\tt valgrind} while running the service
1526from {\tt gnunet-service-arm}.}
1527
1528
1529\end{document}