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