f0f7a8c232b174e0967bb2d02e5bd5c4f8936b9e
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
18      Boston, MA 02110-1301, USA.
19 */
20
21 /**
22  * @file rps/gnunet-service-rps.c
23  * @brief rps service implementation
24  * @author Julius Bünger
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_cadet_service.h"
29 #include "gnunet_peerinfo_service.h"
30 #include "gnunet_nse_service.h"
31 #include "rps.h"
32 #include "rps-test_util.h"
33
34 #include "gnunet-service-rps_sampler.h"
35
36 #include <math.h>
37 #include <inttypes.h>
38
39 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
40
41 // TODO modify @brief in every file
42
43 // TODO check for overflows
44
45 // TODO align message structs
46
47 // TODO connect to friends
48
49 // TODO store peers somewhere persistent
50
51 // TODO blacklist? (-> mal peer detection on top of brahms)
52
53 // TODO API request_cancel
54
55 // hist_size_init, hist_size_max
56
57 /**
58  * Our configuration.
59  */
60 static const struct GNUNET_CONFIGURATION_Handle *cfg;
61
62 /**
63  * Our own identity.
64  */
65 static struct GNUNET_PeerIdentity own_identity;
66
67
68   struct GNUNET_PeerIdentity *
69 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list, unsigned int size,
70                            const struct GNUNET_PeerIdentity *ignore_list, unsigned int ignore_size);
71
72
73 /***********************************************************************
74  * Housekeeping with peers
75 ***********************************************************************/
76
77 /**
78  * Struct used to store the context of a connected client.
79  */
80 struct ClientContext
81 {
82   /**
83    * The message queue to communicate with the client.
84    */
85   struct GNUNET_MQ_Handle *mq;
86 };
87
88 /**
89  * Used to keep track in what lists single peerIDs are.
90  */
91 enum PeerFlags
92 {
93   PULL_REPLY_PENDING   = 0x01,
94   IN_OTHER_GOSSIP_LIST = 0x02, // unneeded?
95   IN_OWN_SAMPLER_LIST  = 0x04, // unneeded?
96   IN_OWN_GOSSIP_LIST   = 0x08, // unneeded?
97
98   /**
99    * We set this bit when we can be sure the other peer is/was live.
100    */
101   VALID                = 0x10,
102
103   /**
104    * We set this bit when we are going to destroy the channel to this peer.
105    * When cleanup_channel is called, we know that we wanted to destroy it.
106    * Otherwise the channel to the other peer was destroyed.
107    */
108   TO_DESTROY           = 0x20,
109 };
110
111
112 /**
113  * Functions of this type can be used to be stored at a peer for later execution.
114  */
115 typedef void (* PeerOp) (void *cls, const struct GNUNET_PeerIdentity *peer);
116
117 /**
118  * Outstanding operation on peer consisting of callback and closure
119  */
120 struct PeerOutstandingOp
121 {
122   /**
123    * Callback
124    */
125   PeerOp op;
126
127   /**
128    * Closure
129    */
130   void *op_cls;
131 };
132
133
134 /**
135  * Struct used to keep track of other peer's status
136  *
137  * This is stored in a multipeermap.
138  */
139 struct PeerContext
140 {
141   /**
142    * Flags indicating status of peer
143    */
144   uint32_t peer_flags;
145
146   /**
147    * Message queue open to client
148    */
149   struct GNUNET_MQ_Handle *mq;
150
151   /**
152    * Channel open to client.
153    */
154   struct GNUNET_CADET_Channel *send_channel;
155
156   /**
157    * Channel open from client.
158    */
159   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
160
161   /**
162    * Array of outstanding operations on this peer.
163    */
164   struct PeerOutstandingOp *outstanding_ops;
165
166   /**
167    * Number of outstanding operations.
168    */
169   unsigned int num_outstanding_ops;
170   //size_t num_outstanding_ops;
171
172   /**
173    * Handle to the callback given to cadet_ntfy_tmt_rdy()
174    *
175    * To be canceled on shutdown.
176    */
177   struct GNUNET_CADET_TransmitHandle *is_live_task;
178
179   /**
180    * Identity of the peer
181    */
182   struct GNUNET_PeerIdentity peer_id;
183
184   /**
185    * This is pobably followed by 'statistical' data (when we first saw
186    * him, how did we get his ID, how many pushes (in a timeinterval),
187    * ...)
188    */
189 };
190
191 /***********************************************************************
192  * /Housekeeping with peers
193 ***********************************************************************/
194
195
196
197
198
199 /***********************************************************************
200  * Globals
201 ***********************************************************************/
202
203 /**
204  * Sampler used for the Brahms protocol itself.
205  */
206 static struct RPS_Sampler *prot_sampler;
207
208 /**
209  * Sampler used for the clients.
210  */
211 static struct RPS_Sampler *client_sampler;
212
213 /**
214  * Set of all peers to keep track of them.
215  */
216 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
217
218
219 /**
220  * Name to log view to
221  */
222 static char *file_name_view_log;
223
224 /**
225  * The "local view" containing peers we learned from gossip and history
226  */
227 static struct GNUNET_CONTAINER_MultiPeerMap *view;
228
229 /**
230  * An array containing the peers of the local view.
231  *
232  * This is created every time we send a pull reply if it has changed since the
233  * last pull reply we sent.
234  */
235 static struct GNUNET_PeerIdentity *view_array;
236
237
238 /**
239  * The size of sampler we need to be able to satisfy the client's need of
240  * random peers.
241  */
242 static unsigned int sampler_size_client_need;
243
244 /**
245  * The size of sampler we need to be able to satisfy the Brahms protocol's
246  * need of random peers.
247  *
248  * This is one minimum size the sampler grows to.
249  */
250 static unsigned int sampler_size_est_need;
251
252
253 /**
254  * Percentage of total peer number in the view
255  * to send random PUSHes to
256  */
257 static float alpha;
258
259 /**
260  * Percentage of total peer number in the view
261  * to send random PULLs to
262  */
263 static float beta;
264
265 /**
266  * The percentage gamma of history updates.
267  * Simply 1 - alpha - beta
268  */
269
270
271 /**
272  * Identifier for the main task that runs periodically.
273  */
274 static struct GNUNET_SCHEDULER_Task *do_round_task;
275
276 /**
277  * Time inverval the do_round task runs in.
278  */
279 static struct GNUNET_TIME_Relative round_interval;
280
281
282
283 /**
284  * List to store peers received through pushes temporary.
285  *
286  * TODO -> multipeermap
287  */
288 static struct GNUNET_PeerIdentity *push_list;
289
290 /**
291  * Size of the push_list;
292  */
293 static unsigned int push_list_size;
294 //size_t push_list_size;
295
296 /**
297  * List to store peers received through pulls temporary.
298  *
299  * TODO -> multipeermap
300  */
301 static struct GNUNET_PeerIdentity *pull_list;
302
303 /**
304  * Size of the pull_list;
305  */
306 static unsigned int pull_list_size;
307 //size_t pull_list_size;
308
309
310 /**
311  * Handler to NSE.
312  */
313 static struct GNUNET_NSE_Handle *nse;
314
315 /**
316  * Handler to CADET.
317  */
318 static struct GNUNET_CADET_Handle *cadet_handle;
319
320 /**
321  * Handler to PEERINFO.
322  */
323 static struct GNUNET_PEERINFO_Handle *peerinfo_handle;
324
325 /**
326  * Handle for cancellation of iteration over peers.
327  */
328 struct GNUNET_PEERINFO_NotifyContext *peerinfo_notify_handle;
329
330
331 /**
332  * Request counter.
333  *
334  * Only needed in the beginning to check how many of the 64 deltas
335  * we already have
336  */
337 static unsigned int req_counter;
338
339 /**
340  * Time of the last request we received.
341  *
342  * Used to compute the expected request rate.
343  */
344 static struct GNUNET_TIME_Absolute last_request;
345
346 /**
347  * Size of #request_deltas.
348  */
349 #define REQUEST_DELTAS_SIZE 64
350 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
351
352 /**
353  * Last 64 deltas between requests
354  */
355 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
356
357 /**
358  * The prediction of the rate of requests
359  */
360 static struct GNUNET_TIME_Relative  request_rate;
361
362
363 /**
364  * Number of history update tasks.
365  */
366 uint32_t num_hist_update_tasks;
367
368
369 /**
370  * Closure used to pass the client and the id to the callback
371  * that replies to a client's request
372  */
373 struct ReplyCls
374 {
375   /**
376    * The identifier of the request
377    */
378   uint32_t id;
379
380   /**
381    * The client handle to send the reply to
382    */
383   struct GNUNET_SERVER_Client *client;
384 };
385
386
387 #ifdef ENABLE_MALICIOUS
388 /**
389  * Type of malicious peer
390  *
391  * 0 Don't act malicious at all - Default
392  * 1 Try to maximise representation
393  * 2 Try to partition the network
394  * 3 Combined attack
395  */
396 uint32_t mal_type = 0;
397
398 /**
399  * Other malicious peers
400  */
401 static struct GNUNET_PeerIdentity *mal_peers = NULL;
402
403 /**
404  * Hashmap of malicious peers used as set.
405  * Used to more efficiently check whether we know that peer.
406  */
407 static struct GNUNET_CONTAINER_MultiPeerMap *mal_peer_set = NULL;
408
409 /**
410  * Number of other malicious peers
411  */
412 static uint32_t num_mal_peers = 0;
413
414
415 /**
416  * If type is 2 This struct is used to store the attacked peers in a DLL
417  */
418 struct AttackedPeer
419 {
420   /**
421    * DLL
422    */
423   struct AttackedPeer *next;
424   struct AttackedPeer *prev;
425
426   /**
427    * PeerID
428    */
429   struct GNUNET_PeerIdentity peer_id;
430 };
431
432 /**
433  * If type is 2 this is the DLL of attacked peers
434  */
435 static struct AttackedPeer *att_peers_head = NULL;
436 static struct AttackedPeer *att_peers_tail = NULL;
437
438 /**
439  * This index is used to point to an attacked peer to
440  * implement the round-robin-ish way to select attacked peers.
441  */
442 static struct AttackedPeer *att_peer_index = NULL;
443
444 /**
445  * Hashmap of attacked peers used as set.
446  * Used to more efficiently check whether we know that peer.
447  */
448 static struct GNUNET_CONTAINER_MultiPeerMap *att_peer_set = NULL;
449
450 /**
451  * Number of attacked peers
452  */
453 static uint32_t num_attacked_peers = 0;
454
455
456 /**
457  * If type is 1 this is the attacked peer
458  */
459 static struct GNUNET_PeerIdentity attacked_peer;
460
461 /**
462  * The limit of PUSHes we can send in one round.
463  * This is an assumption of the Brahms protocol and either implemented
464  * via proof of work
465  * or
466  * assumend to be the bandwidth limitation.
467  */
468 static uint32_t push_limit = 10000;
469 #endif /* ENABLE_MALICIOUS */
470
471
472 /***********************************************************************
473  * /Globals
474 ***********************************************************************/
475
476
477
478
479
480
481 /***********************************************************************
482  * Util functions
483 ***********************************************************************/
484
485 /**
486  * Set a peer flag of given peer context.
487  */
488 #define set_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags |= mask)
489
490 /**
491  * Get peer flag of given peer context.
492  */
493 #define get_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags & mask ? GNUNET_YES : GNUNET_NO)
494
495 /**
496  * Unset flag of given peer context.
497  */
498 #define unset_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags &= (~mask))
499
500 /**
501  * Clean the send channel of a peer
502  */
503 void
504 peer_clean (const struct GNUNET_PeerIdentity *peer);
505
506
507 /**
508  * Check if peer is already in peer array.
509  */
510   int
511 in_arr (const struct GNUNET_PeerIdentity *array,
512         unsigned int arr_size,
513         const struct GNUNET_PeerIdentity *peer)
514 {
515   GNUNET_assert (NULL != peer);
516
517   if (0 == arr_size)
518     return GNUNET_NO;
519
520   GNUNET_assert (NULL != array);
521
522   unsigned int i;
523
524   for (i = 0; i < arr_size ; i++)
525     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer))
526       return GNUNET_YES;
527   return GNUNET_NO;
528 }
529
530
531 /**
532  * Print peerlist to log.
533  */
534 void
535 print_peer_list (struct GNUNET_PeerIdentity *list, unsigned int len)
536 {
537   unsigned int i;
538
539   LOG (GNUNET_ERROR_TYPE_DEBUG,
540        "Printing peer list of length %u at %p:\n",
541        len,
542        list);
543   for (i = 0 ; i < len ; i++)
544   {
545     LOG (GNUNET_ERROR_TYPE_DEBUG,
546          "%u. peer: %s\n",
547          i, GNUNET_i2s (&list[i]));
548   }
549 }
550
551
552 /**
553  * Remove peer from list.
554  */
555   void
556 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
557                unsigned int *list_size,
558                const struct GNUNET_PeerIdentity *peer)
559 {
560   unsigned int i;
561   struct GNUNET_PeerIdentity *tmp;
562
563   tmp = *peer_list;
564
565   LOG (GNUNET_ERROR_TYPE_DEBUG,
566        "Removing peer %s from list at %p\n",
567        GNUNET_i2s (peer),
568        tmp);
569
570   for ( i = 0 ; i < *list_size ; i++ )
571   {
572     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
573     {
574       if (i < *list_size -1)
575       { /* Not at the last entry -- shift peers left */
576         memcpy (&tmp[i], &tmp[i +1],
577                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
578       }
579       /* Remove last entry (should be now useless PeerID) */
580       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
581     }
582   }
583   *peer_list = tmp;
584 }
585
586 /**
587  * Get random peer from the given list but don't return one from the @a ignore_list.
588  */
589   struct GNUNET_PeerIdentity *
590 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
591                            uint32_t list_size,
592                            const struct GNUNET_PeerIdentity *ignore_list,
593                            uint32_t ignore_size)
594 {
595   uint32_t r_index;
596   uint32_t tmp_size;
597   struct GNUNET_PeerIdentity *tmp_peer_list;
598   struct GNUNET_PeerIdentity *peer;
599
600   GNUNET_assert (NULL != peer_list);
601   if (0 == list_size)
602     return NULL;
603
604   tmp_size = 0;
605   tmp_peer_list = NULL;
606   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
607   memcpy (tmp_peer_list,
608           peer_list,
609           list_size * sizeof (struct GNUNET_PeerIdentity));
610   peer = GNUNET_new (struct GNUNET_PeerIdentity);
611
612   /**;
613    * Choose the r_index of the peer we want to return
614    * at random from the interval of the view
615    */
616   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
617                                       tmp_size);
618   *peer = tmp_peer_list[r_index];
619
620   while (in_arr (ignore_list, ignore_size, peer))
621   {
622     rem_from_list (&tmp_peer_list, &tmp_size, peer);
623
624     print_peer_list (tmp_peer_list, tmp_size);
625
626     if (0 == tmp_size)
627     {
628       GNUNET_free (peer);
629       return NULL;
630     }
631
632     /**;
633      * Choose the r_index of the peer we want to return
634      * at random from the interval of the view
635      */
636     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
637                                         tmp_size);
638     *peer = tmp_peer_list[r_index];
639   }
640
641
642   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
643
644   return peer;
645 }
646
647
648 /**
649  * Get the context of a peer. If not existing, create.
650  */
651   struct PeerContext *
652 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
653               const struct GNUNET_PeerIdentity *peer)
654 {
655   struct PeerContext *ctx;
656
657   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
658   {
659     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
660   }
661   else
662   {
663     ctx = GNUNET_new (struct PeerContext);
664     ctx->peer_flags = 0;
665     ctx->mq = NULL;
666     ctx->send_channel = NULL;
667     ctx->recv_channel = NULL;
668     ctx->outstanding_ops = NULL;
669     ctx->num_outstanding_ops = 0;
670     ctx->is_live_task = NULL;
671     ctx->peer_id = *peer;
672     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
673                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
674   }
675   return ctx;
676 }
677
678
679 /**
680  * Put random peer from sampler into the view as history update.
681  */
682   void
683 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
684 {
685   unsigned int i;
686
687   for (i = 0; i < GNUNET_MIN (
688        sampler_size_est_need - GNUNET_CONTAINER_multipeermap_size (view),
689        num_peers); i++)
690   {
691     if (GNUNET_OK != GNUNET_CONTAINER_multipeermap_put (view,
692           &ids[i],
693           NULL,
694           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
695         {
696           LOG (GNUNET_ERROR_TYPE_WARNING,
697                "Failed to put peer in peermap. (hist_update)\n");
698         }
699
700     /* Might want to check that we really updated the view */
701     if (NULL != view_array)
702     {
703       GNUNET_free (view_array);
704       view_array = NULL;
705     }
706
707     to_file (file_name_view_log,
708              "+%s\t(hist)",
709              GNUNET_i2s_full (ids));
710   }
711
712   if (0 < num_hist_update_tasks)
713     num_hist_update_tasks--;
714 }
715
716
717 /**
718  * Set the peer flag to living and call the outstanding operations on this peer.
719  */
720 static size_t
721 peer_is_live (struct PeerContext *peer_ctx)
722 {
723   struct GNUNET_PeerIdentity *peer;
724
725   /* Cancle is_live_task if still scheduled */
726   if (NULL != peer_ctx->is_live_task)
727   {
728     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
729     peer_ctx->is_live_task = NULL;
730   }
731
732   peer = &peer_ctx->peer_id;
733   set_peer_flag (peer_ctx, VALID);
734
735   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
736
737   if (0 < peer_ctx->num_outstanding_ops)
738   { /* Call outstanding operations */
739     unsigned int i;
740
741     for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
742       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
743     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
744   }
745
746   return 0;
747 }
748
749
750 /**
751  * Callback that is called when a channel was effectively established.
752  * This is given to ntfy_tmt_rdy and called when the channel was
753  * successfully established.
754  */
755 static size_t
756 cadet_ntfy_tmt_rdy_cb (void *cls, size_t size, void *buf)
757 {
758   struct PeerContext *peer_ctx = (struct PeerContext *) cls;
759
760   peer_ctx->is_live_task = NULL;
761   LOG (GNUNET_ERROR_TYPE_DEBUG,
762        "Set ->is_live_task = NULL for peer %s\n",
763        GNUNET_i2s (&peer_ctx->peer_id));
764
765   if (NULL != buf
766       && 0 != size)
767   {
768     peer_is_live (peer_ctx);
769   }
770   else
771   {
772     LOG (GNUNET_ERROR_TYPE_WARNING,
773          "Problems establishing a connection to peer %s in order to check liveliness\n",
774          GNUNET_i2s (&peer_ctx->peer_id));
775     // TODO reschedule? cleanup?
776   }
777
778   //if (NULL != peer_ctx->is_live_task)
779   //{
780   //  LOG (GNUNET_ERROR_TYPE_DEBUG,
781   //       "Trying to cancle is_live_task for peer %s\n",
782   //       GNUNET_i2s (&peer_ctx->peer_id));
783   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
784   //  peer_ctx->is_live_task = NULL;
785   //}
786
787   return 0;
788 }
789
790
791 /**
792  * Get the channel of a peer. If not existing, create.
793  */
794   struct GNUNET_CADET_Channel *
795 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
796              const struct GNUNET_PeerIdentity *peer)
797 {
798   struct PeerContext *peer_ctx;
799
800   peer_ctx = get_peer_ctx (peer_map, peer);
801
802   if (NULL == peer_ctx->send_channel)
803   {
804     LOG (GNUNET_ERROR_TYPE_DEBUG,
805          "Trying to establish channel to peer %s\n",
806          GNUNET_i2s (peer));
807
808     peer_ctx->send_channel =
809       GNUNET_CADET_channel_create (cadet_handle,
810                                    NULL,
811                                    peer,
812                                    GNUNET_RPS_CADET_PORT,
813                                    GNUNET_CADET_OPTION_RELIABLE);
814
815   }
816   return peer_ctx->send_channel;
817 }
818
819
820 /**
821  * Get the message queue of a specific peer.
822  *
823  * If we already have a message queue open to this client,
824  * simply return it, otherways create one.
825  */
826   struct GNUNET_MQ_Handle *
827 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
828         const struct GNUNET_PeerIdentity *peer_id)
829 {
830   struct PeerContext *peer_ctx;
831
832   peer_ctx = get_peer_ctx (peer_map, peer_id);
833
834   GNUNET_assert (NULL == peer_ctx->is_live_task);
835
836   if (NULL == peer_ctx->mq)
837   {
838     (void) get_channel (peer_map, peer_id);
839     peer_ctx->mq = GNUNET_CADET_mq_create (peer_ctx->send_channel);
840     //do I have to explicitly put it in the peer_map?
841     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, peer_ctx,
842                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
843   }
844   return peer_ctx->mq;
845 }
846
847
848 /**
849  * Issue check whether peer is live
850  *
851  * @param peer_ctx the context of the peer
852  */
853 void
854 check_peer_live (struct PeerContext *peer_ctx)
855 {
856   (void) get_channel (peer_map, &peer_ctx->peer_id);
857   LOG (GNUNET_ERROR_TYPE_DEBUG,
858        "Get informed about peer %s getting live\n",
859        GNUNET_i2s (&peer_ctx->peer_id));
860   if (NULL == peer_ctx->is_live_task)
861   {
862     peer_ctx->is_live_task =
863         GNUNET_CADET_notify_transmit_ready (peer_ctx->send_channel,
864                                             GNUNET_NO,
865                                             GNUNET_TIME_UNIT_FOREVER_REL,
866                                             sizeof (struct GNUNET_MessageHeader),
867                                             cadet_ntfy_tmt_rdy_cb,
868                                             peer_ctx);
869   }
870   else
871   {
872     LOG (GNUNET_ERROR_TYPE_DEBUG,
873          "Already waiting for notification\n");
874   }
875 }
876
877
878 /**
879  * Sum all time relatives of an array.
880   */
881   struct GNUNET_TIME_Relative
882 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
883 {
884   struct GNUNET_TIME_Relative sum;
885   uint32_t i;
886
887   sum = GNUNET_TIME_UNIT_ZERO;
888   for ( i = 0 ; i < arr_size ; i++ )
889   {
890     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
891   }
892   return sum;
893 }
894
895
896 /**
897  * Compute the average of given time relatives.
898  */
899   struct GNUNET_TIME_Relative
900 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
901 {
902   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
903 }
904
905
906 /**
907  * Insert PeerID in #pull_list
908  *
909  * Called once we know a peer is live.
910  */
911   void
912 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
913 {
914   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
915     GNUNET_array_append (pull_list, pull_list_size, *peer);
916 }
917
918 /**
919  * Check whether #insert_in_pull_list was already scheduled
920  */
921   int
922 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
923 {
924   unsigned int i;
925
926   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
927     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
928       return GNUNET_YES;
929   return GNUNET_NO;
930 }
931
932
933 /**
934  * Insert PeerID in #view
935  *
936  * Called once we know a peer is live.
937  */
938   void
939 insert_in_view (void *cls, const struct GNUNET_PeerIdentity *peer)
940 {
941   if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_put (view,
942         peer,
943         NULL,
944         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
945   {
946     LOG (GNUNET_ERROR_TYPE_WARNING,
947         "Failed to put peer into view. (insert_in_view)\n");
948   }
949
950   /* Might want to check whether we really modified the view */
951   if (NULL != view_array)
952   {
953     GNUNET_free (view_array);
954     view_array = NULL;
955   }
956
957   (void) get_channel (peer_map, peer);
958 }
959
960 /**
961  * Check whether #insert_in_view was already scheduled
962  */
963   int
964 insert_in_view_scheduled (const struct PeerContext *peer_ctx)
965 {
966   unsigned int i;
967
968   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
969     if (insert_in_view == peer_ctx->outstanding_ops[i].op)
970       return GNUNET_YES;
971   return GNUNET_NO;
972 }
973
974
975 /**
976  * Update sampler with given PeerID.
977  */
978   void
979 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
980 {
981   LOG (GNUNET_ERROR_TYPE_DEBUG,
982        "Updating samplers with peer %s from insert_in_sampler()\n",
983        GNUNET_i2s (peer));
984   RPS_sampler_update (prot_sampler,   peer);
985   RPS_sampler_update (client_sampler, peer);
986 }
987
988
989 /**
990  * Check whether #insert_in_sampler was already scheduled
991  */
992 static int
993 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
994 {
995   unsigned int i;
996
997   for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
998     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
999       return GNUNET_YES;
1000   return GNUNET_NO;
1001 }
1002
1003
1004 /**
1005  * Wrapper around #RPS_sampler_resize()
1006  *
1007  * If we do not have enough sampler elements, double current sampler size
1008  * If we have more than enough sampler elements, halv current sampler size
1009  */
1010 static void
1011 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
1012 {
1013   unsigned int sampler_size;
1014
1015   // TODO statistics
1016   // TODO respect the min, max
1017   sampler_size = RPS_sampler_get_size (sampler);
1018   if (sampler_size > new_size * 4)
1019   { /* Shrinking */
1020     RPS_sampler_resize (sampler, sampler_size / 2);
1021   }
1022   else if (sampler_size < new_size)
1023   { /* Growing */
1024     RPS_sampler_resize (sampler, sampler_size * 2);
1025   }
1026   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
1027 }
1028
1029
1030 /**
1031  * Wrapper around #RPS_sampler_resize() resizing the client sampler
1032  */
1033 static void
1034 client_resize_wrapper ()
1035 {
1036   uint32_t bigger_size;
1037   unsigned int sampler_size;
1038
1039   // TODO statistics
1040
1041   sampler_size = RPS_sampler_get_size (client_sampler);
1042
1043   if (sampler_size_est_need > sampler_size_client_need)
1044     bigger_size = sampler_size_est_need;
1045   else
1046     bigger_size = sampler_size_client_need;
1047
1048   // TODO respect the min, max
1049   resize_wrapper (client_sampler, bigger_size);
1050   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
1051 }
1052
1053
1054 /**
1055  * Estimate request rate
1056  *
1057  * Called every time we receive a request from the client.
1058  */
1059   void
1060 est_request_rate()
1061 {
1062   struct GNUNET_TIME_Relative max_round_duration;
1063
1064   if (request_deltas_size > req_counter)
1065     req_counter++;
1066   if ( 1 < req_counter)
1067   {
1068     /* Shift last request deltas to the right */
1069     memcpy (&request_deltas[1],
1070         request_deltas,
1071         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
1072
1073     /* Add current delta to beginning */
1074     request_deltas[0] =
1075         GNUNET_TIME_absolute_get_difference (last_request,
1076                                              GNUNET_TIME_absolute_get ());
1077     request_rate = T_relative_avg (request_deltas, req_counter);
1078
1079     /* Compute the duration a round will maximally take */
1080     max_round_duration =
1081         GNUNET_TIME_relative_add (round_interval,
1082                                   GNUNET_TIME_relative_divide (round_interval, 2));
1083
1084     /* Set the estimated size the sampler has to have to
1085      * satisfy the current client request rate */
1086     sampler_size_client_need =
1087         max_round_duration.rel_value_us / request_rate.rel_value_us;
1088
1089     /* Resize the sampler */
1090     client_resize_wrapper ();
1091   }
1092   last_request = GNUNET_TIME_absolute_get ();
1093 }
1094
1095
1096 /**
1097  * Add all peers in @a peer_array to @a peer_map used as set.
1098  *
1099  * @param peer_array array containing the peers
1100  * @param num_peers number of peers in @peer_array
1101  * @param peer_map the peermap to use as set
1102  */
1103 static void
1104 add_peer_array_to_set (const struct GNUNET_PeerIdentity *peer_array,
1105                        unsigned int num_peers,
1106                        struct GNUNET_CONTAINER_MultiPeerMap *peer_map)
1107 {
1108   unsigned int i;
1109   if (NULL == peer_map)
1110   {
1111     LOG (GNUNET_ERROR_TYPE_WARNING,
1112          "Trying to add peers to an empty peermap.\n");
1113     return;
1114   }
1115
1116   for (i = 0; i < num_peers; i++)
1117   {
1118     GNUNET_CONTAINER_multipeermap_put (peer_map,
1119                                        &peer_array[i],
1120                                        NULL,
1121                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1122   }
1123 }
1124
1125
1126 /**
1127  * Send a PULL REPLY to @a peer_id
1128  *
1129  * @param peer_id the peer to send the reply to.
1130  * @param peer_ids the peers to send to @a peer_id
1131  * @param num_peer_ids the number of peers to send to @a peer_id
1132  */
1133 static void
1134 send_pull_reply (const struct GNUNET_PeerIdentity *peer_id,
1135                  const struct GNUNET_PeerIdentity *peer_ids,
1136                  unsigned int num_peer_ids)
1137 {
1138   uint32_t send_size;
1139   struct GNUNET_MQ_Handle *mq;
1140   struct GNUNET_MQ_Envelope *ev;
1141   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1142
1143   /* Compute actual size */
1144   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1145               num_peer_ids * sizeof (struct GNUNET_PeerIdentity);
1146
1147   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1148     /* Compute number of peers to send
1149      * If too long, simply truncate */
1150     // TODO select random ones via permutation
1151     //      or even better: do good protocol design
1152     send_size =
1153       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1154        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1155        sizeof (struct GNUNET_PeerIdentity);
1156   else
1157     send_size = num_peer_ids;
1158
1159   LOG (GNUNET_ERROR_TYPE_DEBUG,
1160       "PULL REQUEST from peer %s received, going to send %u peers\n",
1161       GNUNET_i2s (peer_id), send_size);
1162
1163   mq = get_mq (peer_map, peer_id);
1164
1165   ev = GNUNET_MQ_msg_extra (out_msg,
1166                             send_size * sizeof (struct GNUNET_PeerIdentity),
1167                             GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1168   out_msg->num_peers = htonl (send_size);
1169   memcpy (&out_msg[1], peer_ids,
1170          send_size * sizeof (struct GNUNET_PeerIdentity));
1171
1172   GNUNET_MQ_send (mq, ev);
1173 }
1174
1175
1176 /**
1177  * This function is called on new peer_ids from 'external' sources
1178  * (client seed, cadet get_peers(), ...)
1179  *
1180  * @param peer_id the new peer_id
1181  */
1182 static void
1183 new_peer_id (const struct GNUNET_PeerIdentity *peer_id)
1184 {
1185   struct PeerOutstandingOp out_op;
1186   struct PeerContext *peer_ctx;
1187
1188   if (NULL != peer_id &&
1189       0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer_id))
1190   {
1191     LOG (GNUNET_ERROR_TYPE_DEBUG,
1192         "Got peer_id %s (at %p, view size: %u)\n",
1193         GNUNET_i2s (peer_id),
1194         peer_id,
1195         GNUNET_CONTAINER_multipeermap_size (view));
1196
1197     peer_ctx = get_peer_ctx (peer_map, peer_id);
1198     if (GNUNET_YES != get_peer_flag (peer_ctx, VALID))
1199     {
1200       if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1201       {
1202         out_op.op = insert_in_sampler;
1203         out_op.op_cls = NULL;
1204         GNUNET_array_append (peer_ctx->outstanding_ops,
1205                              peer_ctx->num_outstanding_ops,
1206                              out_op);
1207       }
1208
1209       if (GNUNET_NO == insert_in_view_scheduled (peer_ctx))
1210       {
1211         out_op.op = insert_in_view;
1212         out_op.op_cls = NULL;
1213         GNUNET_array_append (peer_ctx->outstanding_ops,
1214                              peer_ctx->num_outstanding_ops,
1215                              out_op);
1216       }
1217
1218       /* Trigger livelyness test on peer */
1219       check_peer_live (peer_ctx);
1220     }
1221     // else...?
1222
1223     // send push/pull to each of those peers?
1224   }
1225 }
1226
1227
1228 /***********************************************************************
1229  * /Util functions
1230 ***********************************************************************/
1231
1232
1233
1234
1235
1236 /**
1237  * Function called by NSE.
1238  *
1239  * Updates sizes of sampler list and view and adapt those lists
1240  * accordingly.
1241  */
1242   void
1243 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
1244               double logestimate, double std_dev)
1245 {
1246   double estimate;
1247   //double scale; // TODO this might go gloabal/config
1248
1249   LOG (GNUNET_ERROR_TYPE_DEBUG,
1250        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
1251        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
1252   //scale = .01;
1253   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
1254   // GNUNET_NSE_log_estimate_to_n (logestimate);
1255   estimate = pow (estimate, 1.0 / 3);
1256   // TODO add if std_dev is a number
1257   // estimate += (std_dev * scale);
1258   if (2 < ceil (estimate))
1259   {
1260     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
1261     sampler_size_est_need = estimate;
1262   } else
1263     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
1264
1265   /* If the NSE has changed adapt the lists accordingly */
1266   resize_wrapper (prot_sampler, sampler_size_est_need);
1267   client_resize_wrapper ();
1268 }
1269
1270
1271 /**
1272  * Callback called once the requested PeerIDs are ready.
1273  *
1274  * Sends those to the requesting client.
1275  */
1276 void client_respond (void *cls,
1277     struct GNUNET_PeerIdentity *peer_ids, uint32_t num_peers)
1278 {
1279   struct GNUNET_MQ_Envelope *ev;
1280   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1281   struct ReplyCls *reply_cls = (struct ReplyCls *) cls;
1282   uint32_t size_needed;
1283   struct ClientContext *cli_ctx;
1284
1285   LOG (GNUNET_ERROR_TYPE_DEBUG,
1286        "sampler returned %" PRIu32 " peers\n",
1287        num_peers);
1288
1289   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1290                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1291
1292   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1293
1294   ev = GNUNET_MQ_msg_extra (out_msg,
1295                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1296                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1297   out_msg->num_peers = htonl (num_peers);
1298   out_msg->id = htonl (reply_cls->id);
1299
1300   memcpy (&out_msg[1],
1301           peer_ids,
1302           num_peers * sizeof (struct GNUNET_PeerIdentity));
1303   GNUNET_free (peer_ids);
1304
1305   cli_ctx = GNUNET_SERVER_client_get_user_context (reply_cls->client, struct ClientContext);
1306   if (NULL == cli_ctx) {
1307     cli_ctx = GNUNET_new (struct ClientContext);
1308     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (reply_cls->client);
1309     GNUNET_SERVER_client_set_user_context (reply_cls->client, cli_ctx);
1310   }
1311
1312   GNUNET_free (reply_cls);
1313
1314   GNUNET_MQ_send (cli_ctx->mq, ev);
1315 }
1316
1317
1318 /**
1319  * Handle RPS request from the client.
1320  *
1321  * @param cls closure
1322  * @param client identification of the client
1323  * @param message the actual message
1324  */
1325 static void
1326 handle_client_request (void *cls,
1327                        struct GNUNET_SERVER_Client *client,
1328                        const struct GNUNET_MessageHeader *message)
1329 {
1330   struct GNUNET_RPS_CS_RequestMessage *msg;
1331   uint32_t num_peers;
1332   uint32_t size_needed;
1333   struct ReplyCls *reply_cls;
1334   uint32_t i;
1335
1336   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1337
1338   num_peers = ntohl (msg->num_peers);
1339   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1340                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1341
1342   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1343   {
1344     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1345     return;
1346   }
1347
1348   for (i = 0 ; i < num_peers ; i++)
1349     est_request_rate();
1350
1351   LOG (GNUNET_ERROR_TYPE_DEBUG,
1352        "Client requested %" PRIu32 " random peer(s).\n",
1353        num_peers);
1354
1355   reply_cls = GNUNET_new (struct ReplyCls);
1356   reply_cls->id = ntohl (msg->id);
1357   reply_cls->client = client;
1358
1359   RPS_sampler_get_n_rand_peers (client_sampler,
1360                                 client_respond,
1361                                 reply_cls,
1362                                 num_peers);
1363
1364   GNUNET_SERVER_receive_done (client,
1365                               GNUNET_OK);
1366 }
1367
1368
1369 /**
1370  * Handle seed from the client.
1371  *
1372  * @param cls closure
1373  * @param client identification of the client
1374  * @param message the actual message
1375  */
1376   static void
1377 handle_client_seed (void *cls,
1378                     struct GNUNET_SERVER_Client *client,
1379                     const struct GNUNET_MessageHeader *message)
1380 {
1381   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1382   struct GNUNET_PeerIdentity *peers;
1383   uint32_t num_peers;
1384   uint32_t i;
1385
1386   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1387   {
1388     GNUNET_break_op (0);
1389     GNUNET_SERVER_receive_done (client,
1390                                 GNUNET_SYSERR);
1391   }
1392
1393   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1394   num_peers = ntohl (in_msg->num_peers);
1395   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1396   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1397   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1398
1399   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1400       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1401   {
1402     GNUNET_break_op (0);
1403     GNUNET_SERVER_receive_done (client,
1404                                 GNUNET_SYSERR);
1405   }
1406
1407   LOG (GNUNET_ERROR_TYPE_DEBUG,
1408        "Client seeded peers:\n");
1409   print_peer_list (peers, num_peers);
1410
1411   for (i = 0 ; i < num_peers ; i++)
1412   {
1413     LOG (GNUNET_ERROR_TYPE_DEBUG,
1414          "Updating samplers with seed %" PRIu32 ": %s\n",
1415          i,
1416          GNUNET_i2s (&peers[i]));
1417
1418     new_peer_id (&peers[i]);
1419
1420     //RPS_sampler_update (prot_sampler,   &peers[i]);
1421     //RPS_sampler_update (client_sampler, &peers[i]);
1422   }
1423
1424   ////GNUNET_free (peers);
1425
1426   GNUNET_SERVER_receive_done (client,
1427                                                 GNUNET_OK);
1428 }
1429
1430
1431 /**
1432  * Handle a PUSH message from another peer.
1433  *
1434  * Check the proof of work and store the PeerID
1435  * in the temporary list for pushed PeerIDs.
1436  *
1437  * @param cls Closure
1438  * @param channel The channel the PUSH was received over
1439  * @param channel_ctx The context associated with this channel
1440  * @param msg The message header
1441  */
1442 static int
1443 handle_peer_push (void *cls,
1444     struct GNUNET_CADET_Channel *channel,
1445     void **channel_ctx,
1446     const struct GNUNET_MessageHeader *msg)
1447 {
1448   const struct GNUNET_PeerIdentity *peer;
1449
1450   // (check the proof of work)
1451
1452   peer = (const struct GNUNET_PeerIdentity *)
1453     GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1454   // FIXME wait for cadet to change this function
1455
1456   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1457
1458   #ifdef ENABLE_MALICIOUS
1459   struct AttackedPeer *tmp_att_peer;
1460
1461   tmp_att_peer = GNUNET_new (struct AttackedPeer);
1462   memcpy (&tmp_att_peer->peer_id, peer, sizeof (struct GNUNET_PeerIdentity));
1463   if (1 == mal_type
1464       || 3 == mal_type)
1465   { /* Try to maximise representation */
1466     if (NULL == att_peer_set)
1467       att_peer_set = GNUNET_CONTAINER_multipeermap_create (1, GNUNET_NO);
1468     if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1469                                                              peer))
1470     {
1471       GNUNET_CONTAINER_DLL_insert (att_peers_head,
1472                                    att_peers_tail,
1473                                    tmp_att_peer);
1474       add_peer_array_to_set (peer, 1, att_peer_set);
1475     }
1476     return GNUNET_OK;
1477   }
1478
1479
1480   else if (2 == mal_type)
1481   { /* We attack one single well-known peer - simply ignore */
1482     return GNUNET_OK;
1483   }
1484   else
1485   {
1486     GNUNET_free (tmp_att_peer);
1487   }
1488
1489   #endif /* ENABLE_MALICIOUS */
1490
1491   /* Add the sending peer to the push_list */
1492   if (GNUNET_NO == in_arr (push_list, push_list_size, peer))
1493     GNUNET_array_append (push_list, push_list_size, *peer);
1494
1495   return GNUNET_OK;
1496 }
1497
1498
1499 /**
1500  * Iterator over hash map entries.
1501  * Called from #generate_view_array and writes every peer id into #view_array.
1502  *
1503  * @param cls closure - the pointer to the counter
1504  * @param key current public key
1505  * @param value value in the hash map
1506  * @return #GNUNET_YES if we should continue to
1507  * iterate,
1508  * #GNUNET_NO if not.
1509  */
1510 static int
1511 dump_id_to_view_array (void *cls,
1512                        const struct GNUNET_PeerIdentity *key,
1513                        void *value)
1514 {
1515   unsigned int *i = (unsigned int *) cls;
1516
1517   view_array[(*i)++] = *key;
1518   return GNUNET_YES;
1519 }
1520
1521
1522 /**
1523  * Makes sure the view_array is filled with the peer ids currently in #view.
1524  * Called from within #do_round before sending pushes and pulls and from
1525  * #handle_peer_pull_request when a reply is sent.
1526  */
1527 static void
1528 generate_view_array (unsigned int view_size)
1529 {
1530   unsigned int *i;
1531   int ret;
1532
1533   if (NULL == view_array)
1534   {
1535     view_array = GNUNET_new_array (view_size,
1536                                    struct GNUNET_PeerIdentity);
1537     i = GNUNET_new (unsigned int);
1538     *i = 0;
1539
1540     ret = GNUNET_CONTAINER_multipeermap_iterate (view,
1541                                                  dump_id_to_view_array,
1542                                                  i);
1543     GNUNET_assert (view_size == ret);
1544     GNUNET_assert (view_size == *i);
1545
1546     GNUNET_free (i);
1547   }
1548 }
1549
1550
1551 /**
1552  * Handle PULL REQUEST request message from another peer.
1553  *
1554  * Reply with the view of PeerIDs.
1555  *
1556  * @param cls Closure
1557  * @param channel The channel the PUSH was received over
1558  * @param channel_ctx The context associated with this channel
1559  * @param msg The message header
1560  */
1561 static int
1562 handle_peer_pull_request (void *cls,
1563     struct GNUNET_CADET_Channel *channel,
1564     void **channel_ctx,
1565     const struct GNUNET_MessageHeader *msg)
1566 {
1567   struct GNUNET_PeerIdentity *peer;
1568   unsigned int view_size;
1569
1570   peer = (struct GNUNET_PeerIdentity *)
1571     GNUNET_CADET_channel_get_info (channel,
1572                                    GNUNET_CADET_OPTION_PEER);
1573   // FIXME wait for cadet to change this function
1574
1575   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REQUEST received (%s)\n", GNUNET_i2s (peer));
1576
1577   #ifdef ENABLE_MALICIOUS
1578   if (1 == mal_type
1579       || 3 == mal_type)
1580   { /* Try to maximise representation */
1581     send_pull_reply (peer, mal_peers, num_mal_peers);
1582     return GNUNET_OK;
1583   }
1584
1585   else if (2 == mal_type)
1586   { /* Try to partition network */
1587     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&attacked_peer, peer))
1588     {
1589       send_pull_reply (peer, mal_peers, num_mal_peers);
1590     }
1591     return GNUNET_OK;
1592   }
1593   #endif /* ENABLE_MALICIOUS */
1594
1595   view_size = GNUNET_CONTAINER_multipeermap_size (view);
1596   generate_view_array (view_size);
1597
1598   send_pull_reply (peer, view_array, view_size);
1599
1600   return GNUNET_OK;
1601 }
1602
1603
1604 /**
1605  * Handle PULL REPLY message from another peer.
1606  *
1607  * Check whether we sent a corresponding request and
1608  * whether this reply is the first one.
1609  *
1610  * @param cls Closure
1611  * @param channel The channel the PUSH was received over
1612  * @param channel_ctx The context associated with this channel
1613  * @param msg The message header
1614  */
1615   static int
1616 handle_peer_pull_reply (void *cls,
1617                         struct GNUNET_CADET_Channel *channel,
1618                         void **channel_ctx,
1619                         const struct GNUNET_MessageHeader *msg)
1620 {
1621   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1622   struct GNUNET_PeerIdentity *peers;
1623   struct PeerContext *peer_ctx;
1624   struct GNUNET_PeerIdentity *sender;
1625   struct PeerContext *sender_ctx;
1626   struct PeerOutstandingOp out_op;
1627   uint32_t i;
1628 #ifdef ENABLE_MALICIOUS
1629   struct AttackedPeer *tmp_att_peer;
1630 #endif /* ENABLE_MALICIOUS */
1631
1632   /* Check for protocol violation */
1633   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1634   {
1635     GNUNET_break_op (0);
1636     return GNUNET_SYSERR;
1637   }
1638
1639   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1640   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1641       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1642   {
1643     LOG (GNUNET_ERROR_TYPE_ERROR,
1644         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1645         ntohl (in_msg->num_peers),
1646         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1647             sizeof (struct GNUNET_PeerIdentity));
1648     GNUNET_break_op (0);
1649     return GNUNET_SYSERR;
1650   }
1651
1652   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1653       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1654        // Guess simply casting isn't the nicest way...
1655        // FIXME wait for cadet to change this function
1656   sender_ctx = get_peer_ctx (peer_map, sender);
1657
1658   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received (%s)\n", GNUNET_i2s (sender));
1659
1660   if (GNUNET_YES != get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1661   {
1662     LOG (GNUNET_ERROR_TYPE_WARNING,
1663         "Received a pull reply from a peer we didn't request one from!\n");
1664     GNUNET_break_op (0);
1665     return GNUNET_OK;
1666   }
1667
1668
1669   #ifdef ENABLE_MALICIOUS
1670   // We shouldn't even receive pull replies as we're not sending
1671   if (2 == mal_type)
1672     return GNUNET_OK;
1673   #endif /* ENABLE_MALICIOUS */
1674
1675   /* Do actual logic */
1676   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1677
1678   LOG (GNUNET_ERROR_TYPE_DEBUG,
1679        "PULL REPLY received, got following %u peers:\n",
1680        ntohl (in_msg->num_peers));
1681
1682   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1683   {
1684     LOG (GNUNET_ERROR_TYPE_DEBUG,
1685          "%u. %s\n",
1686          i,
1687          GNUNET_i2s (&peers[i]));
1688
1689     #ifdef ENABLE_MALICIOUS
1690     if (1 == mal_type
1691         || 3 == mal_type)
1692     { /* Add attacked peer to local list */
1693       // TODO check if we sent a request and this was the first reply
1694       if (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (att_peer_set,
1695                                                                &peers[i])
1696           && GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (mal_peer_set,
1697                                                                   &peers[i])
1698           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&peers[i],
1699                                                    &own_identity))
1700       {
1701         tmp_att_peer = GNUNET_new (struct AttackedPeer);
1702         tmp_att_peer->peer_id = peers[i];
1703         GNUNET_CONTAINER_DLL_insert (att_peers_head,
1704                                      att_peers_tail,
1705                                      tmp_att_peer);
1706         add_peer_array_to_set (&peers[i], 1, att_peer_set);
1707       }
1708       continue;
1709     }
1710     #endif /* ENABLE_MALICIOUS */
1711     if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity,
1712                                               &peers[i]))
1713     {
1714       peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1715       if (GNUNET_YES == get_peer_flag (peer_ctx, VALID))
1716       {
1717         if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i]))
1718           GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1719       }
1720       else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1721       {
1722         out_op.op = insert_in_pull_list;
1723         out_op.op_cls = NULL;
1724         GNUNET_array_append (peer_ctx->outstanding_ops,
1725                              peer_ctx->num_outstanding_ops,
1726                              out_op);
1727         check_peer_live (peer_ctx);
1728       }
1729     }
1730   }
1731
1732   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1733
1734   return GNUNET_OK;
1735 }
1736
1737
1738 /**
1739  * Compute a random delay.
1740  * A uniformly distributed value between mean + spread and mean - spread.
1741  *
1742  * For example for mean 4 min and spread 2 the minimum is (4 min - (1/2 * 4 min))
1743  * It would return a random value between 2 and 6 min.
1744  *
1745  * @param mean the mean
1746  * @param spread the inverse amount of deviation from the mean
1747  */
1748 static struct GNUNET_TIME_Relative
1749 compute_rand_delay (struct GNUNET_TIME_Relative mean, unsigned int spread)
1750 {
1751   struct GNUNET_TIME_Relative half_interval;
1752   struct GNUNET_TIME_Relative ret;
1753   unsigned int rand_delay;
1754   unsigned int max_rand_delay;
1755
1756   if (0 == spread)
1757   {
1758     LOG (GNUNET_ERROR_TYPE_WARNING,
1759          "Not accepting spread of 0\n");
1760     GNUNET_break (0);
1761   }
1762
1763   /* Compute random time value between spread * mean and spread * mean */
1764   half_interval = GNUNET_TIME_relative_divide (mean, spread);
1765
1766   max_rand_delay = GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us / mean.rel_value_us * (2/spread);
1767   /**
1768    * Compute random value between (0 and 1) * round_interval
1769    * via multiplying round_interval with a 'fraction' (0 to value)/value
1770    */
1771   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, max_rand_delay);
1772   ret = GNUNET_TIME_relative_multiply (mean,  rand_delay);
1773   ret = GNUNET_TIME_relative_divide   (ret, max_rand_delay);
1774   ret = GNUNET_TIME_relative_add      (ret, half_interval);
1775
1776   if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == ret.rel_value_us)
1777     LOG (GNUNET_ERROR_TYPE_WARNING,
1778          "Returning FOREVER_REL\n");
1779
1780   return ret;
1781 }
1782
1783
1784 /**
1785  * Send single pull request
1786  *
1787  * @param peer_id the peer to send the pull request to.
1788  */
1789 static void
1790 send_pull_request (struct GNUNET_PeerIdentity *peer_id)
1791 {
1792   struct GNUNET_MQ_Envelope *ev;
1793   struct GNUNET_MQ_Handle *mq;
1794   struct PeerContext *peer_ctx;
1795
1796   peer_ctx = get_peer_ctx (peer_map, peer_id);
1797   GNUNET_assert (GNUNET_NO == get_peer_flag (peer_ctx, PULL_REPLY_PENDING));
1798   set_peer_flag (peer_ctx, PULL_REPLY_PENDING);
1799
1800   LOG (GNUNET_ERROR_TYPE_DEBUG,
1801        "Sending PULL request to peer %s of view.\n",
1802        GNUNET_i2s (peer_id));
1803
1804   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1805   mq = get_mq (peer_map, peer_id);
1806   GNUNET_MQ_send (mq, ev);
1807 }
1808
1809
1810 /**
1811  * Send single push
1812  *
1813  * @param peer_id the peer to send the push to.
1814  */
1815 static void
1816 send_push (struct GNUNET_PeerIdentity *peer_id)
1817 {
1818   struct GNUNET_MQ_Envelope *ev;
1819   struct GNUNET_MQ_Handle *mq;
1820
1821   LOG (GNUNET_ERROR_TYPE_DEBUG,
1822        "Sending PUSH to peer %s of view.\n",
1823        GNUNET_i2s (peer_id));
1824
1825   ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1826   mq = get_mq (peer_map, peer_id);
1827   GNUNET_MQ_send (mq, ev);
1828 }
1829
1830
1831 static void
1832 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1833
1834 static void
1835 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
1836
1837
1838 #ifdef ENABLE_MALICIOUS
1839 /**
1840  * Turn RPS service to act malicious.
1841  *
1842  * @param cls Closure
1843  * @param channel The channel the PUSH was received over
1844  * @param channel_ctx The context associated with this channel
1845  * @param msg The message header
1846  */
1847   static void
1848 handle_client_act_malicious (void *cls,
1849                              struct GNUNET_SERVER_Client *client,
1850                              const struct GNUNET_MessageHeader *msg)
1851 {
1852   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
1853   struct GNUNET_PeerIdentity *peers;
1854   uint32_t num_mal_peers_sent;
1855   uint32_t num_mal_peers_old;
1856
1857   /* Check for protocol violation */
1858   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
1859   {
1860     GNUNET_break_op (0);
1861   }
1862
1863   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
1864   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1865       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1866   {
1867     LOG (GNUNET_ERROR_TYPE_ERROR,
1868         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1869         ntohl (in_msg->num_peers),
1870         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1871             sizeof (struct GNUNET_PeerIdentity));
1872     GNUNET_break_op (0);
1873   }
1874
1875
1876   /* Do actual logic */
1877   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1878   mal_type = ntohl (in_msg->type);
1879
1880   LOG (GNUNET_ERROR_TYPE_DEBUG,
1881        "Now acting malicious type %" PRIu32 "\n",
1882        mal_type);
1883
1884   if (1 == mal_type)
1885   { /* Try to maximise representation */
1886     /* Add other malicious peers to those we already know */
1887
1888     num_mal_peers_sent = ntohl (in_msg->num_peers);
1889     num_mal_peers_old = num_mal_peers;
1890     GNUNET_array_grow (mal_peers,
1891                        num_mal_peers,
1892                        num_mal_peers + num_mal_peers_sent);
1893     memcpy (&mal_peers[num_mal_peers_old],
1894             peers,
1895             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1896
1897     /* Add all mal peers to mal_peer_set */
1898     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
1899                            num_mal_peers_sent,
1900                            mal_peer_set);
1901
1902     /* Substitute do_round () with do_mal_round () */
1903     GNUNET_SCHEDULER_cancel (do_round_task);
1904     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1905   }
1906
1907   else if (2 == mal_type
1908            || 3 == mal_type)
1909   { /* Try to partition the network */
1910     /* Add other malicious peers to those we already know */
1911     num_mal_peers_sent = ntohl (in_msg->num_peers) - 1;
1912     num_mal_peers_old = num_mal_peers;
1913     GNUNET_array_grow (mal_peers,
1914                        num_mal_peers,
1915                        num_mal_peers + num_mal_peers_sent);
1916     memcpy (&mal_peers[num_mal_peers_old],
1917             peers,
1918             num_mal_peers_sent * sizeof (struct GNUNET_PeerIdentity));
1919
1920     /* Add all mal peers to mal_peer_set */
1921     add_peer_array_to_set (&mal_peers[num_mal_peers_old],
1922                            num_mal_peers_sent,
1923                            mal_peer_set);
1924
1925     /* Store the one attacked peer */
1926     memcpy (&attacked_peer,
1927             &in_msg->attacked_peer,
1928             sizeof (struct GNUNET_PeerIdentity));
1929
1930     LOG (GNUNET_ERROR_TYPE_DEBUG,
1931          "Attacked peer is %s\n",
1932          GNUNET_i2s (&attacked_peer));
1933
1934     /* Substitute do_round () with do_mal_round () */
1935     GNUNET_SCHEDULER_cancel (do_round_task);
1936     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1937   }
1938   else if (0 == mal_type)
1939   { /* Stop acting malicious */
1940     GNUNET_array_grow (mal_peers, num_mal_peers, 0);
1941
1942     /* Substitute do_mal_round () with do_round () */
1943     GNUNET_SCHEDULER_cancel (do_round_task);
1944     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1945   }
1946   else
1947   {
1948     GNUNET_break (0);
1949   }
1950
1951   GNUNET_SERVER_receive_done (client,   GNUNET_OK);
1952 }
1953
1954
1955 /**
1956  * Send out PUSHes and PULLs maliciously.
1957  *
1958  * This is executed regylary.
1959  */
1960 static void
1961 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1962 {
1963   uint32_t num_pushes;
1964   uint32_t i;
1965   struct GNUNET_TIME_Relative time_next_round;
1966   struct AttackedPeer *tmp_att_peer;
1967   struct PeerContext *peer_ctx;
1968
1969   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously type %" PRIu32 ".\n",
1970       mal_type);
1971
1972   /* Do malicious actions */
1973   if (1 == mal_type)
1974   { /* Try to maximise representation */
1975
1976     /* The maximum of pushes we're going to send this round */
1977     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit,
1978                                          num_attacked_peers),
1979                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
1980
1981     LOG (GNUNET_ERROR_TYPE_DEBUG,
1982          "Going to send %" PRIu32 " pushes\n",
1983          num_pushes);
1984
1985     /* Send PUSHes to attacked peers */
1986     for (i = 0 ; i < num_pushes ; i++)
1987     {
1988       if (att_peers_tail == att_peer_index)
1989         att_peer_index = att_peers_head;
1990       else
1991         att_peer_index = att_peer_index->next;
1992
1993       send_push (&att_peer_index->peer_id);
1994     }
1995
1996     /* Send PULLs to some peers to learn about additional peers to attack */
1997     tmp_att_peer = att_peer_index;
1998     for (i = 0 ; i < num_pushes * alpha ; i++)
1999     {
2000       if (att_peers_tail == tmp_att_peer)
2001         tmp_att_peer = att_peers_head;
2002       else
2003         att_peer_index = tmp_att_peer->next;
2004
2005       send_pull_request (&tmp_att_peer->peer_id);
2006     }
2007   }
2008
2009
2010   else if (2 == mal_type)
2011   { /**
2012      * Try to partition the network
2013      * Send as many pushes to the attacked peer as possible
2014      * That is one push per round as it will ignore more.
2015      */
2016       send_push (&attacked_peer);
2017   }
2018
2019
2020   if (3 == mal_type)
2021   { /* Combined attack */
2022
2023     /* Send PUSH to attacked peers */
2024     peer_ctx = get_peer_ctx (peer_map, &attacked_peer);
2025     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID))
2026     {
2027       LOG (GNUNET_ERROR_TYPE_DEBUG,
2028           "Goding to send push to attacked peer (%s)\n",
2029           GNUNET_i2s (&attacked_peer));
2030       send_push (&attacked_peer);
2031     }
2032     else
2033       check_peer_live (peer_ctx);
2034
2035     /* The maximum of pushes we're going to send this round */
2036     num_pushes = GNUNET_MIN (GNUNET_MIN (push_limit - 1,
2037                                          num_attacked_peers),
2038                              GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE);
2039
2040     LOG (GNUNET_ERROR_TYPE_DEBUG,
2041          "Going to send %" PRIu32 " pushes\n",
2042          num_pushes);
2043
2044     for (i = 0 ; i < num_pushes ; i++)
2045     {
2046       if (att_peers_tail == att_peer_index)
2047         att_peer_index = att_peers_head;
2048       else
2049         att_peer_index = att_peer_index->next;
2050
2051       send_push (&att_peer_index->peer_id);
2052     }
2053
2054     /* Send PULLs to some peers to learn about additional peers to attack */
2055     tmp_att_peer = att_peer_index;
2056     for (i = 0 ; i < num_pushes * alpha ; i++)
2057     {
2058       if (att_peers_tail == tmp_att_peer)
2059         tmp_att_peer = att_peers_head;
2060       else
2061         att_peer_index = tmp_att_peer->next;
2062
2063       send_pull_request (&tmp_att_peer->peer_id);
2064     }
2065   }
2066
2067   /* Schedule next round */
2068   time_next_round = compute_rand_delay (round_interval, 2);
2069
2070   //do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round, NULL);
2071   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_mal_round, NULL);
2072   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
2073 }
2074 #endif /* ENABLE_MALICIOUS */
2075
2076
2077 /**
2078  * Send out PUSHes and PULLs, possibly update #view, samplers.
2079  *
2080  * This is executed regylary.
2081  */
2082 static void
2083 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
2084 {
2085   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
2086
2087   uint32_t i;
2088   unsigned int view_size;
2089   unsigned int *permut;
2090   unsigned int a_peers; /* Number of peers we send pushes to */
2091   unsigned int b_peers; /* Number of peers we send pull requests to */
2092   uint32_t first_border;
2093   uint32_t second_border;
2094   struct GNUNET_PeerIdentity peer;
2095   struct PeerContext *peer_ctx;
2096
2097   LOG (GNUNET_ERROR_TYPE_DEBUG,
2098        "Printing view:\n");
2099   to_file (file_name_view_log,
2100            "___ new round ___");
2101   view_size = GNUNET_CONTAINER_multipeermap_size (view);
2102   generate_view_array (view_size);
2103   for (i = 0 ; i < view_size ; i++)
2104   {
2105     LOG (GNUNET_ERROR_TYPE_DEBUG,
2106          "\t%s\n", GNUNET_i2s (&view_array[i]));
2107     to_file (file_name_view_log,
2108              "=%s\t(do round)",
2109              GNUNET_i2s_full (&view_array[i]));
2110   }
2111
2112
2113   /* Send pushes and pull requests */
2114   if (0 < view_size)
2115   {
2116     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2117                                            (unsigned int) view_size);
2118
2119     /* Send PUSHes */
2120     a_peers = ceil (alpha * view_size);
2121
2122     LOG (GNUNET_ERROR_TYPE_DEBUG,
2123          "Going to send pushes to %u (ceil (%f * %u)) peers.\n",
2124          a_peers, alpha, view_size);
2125     for (i = 0; i < a_peers; i++)
2126     {
2127       peer = view_array[permut[i]];
2128       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
2129       { // FIXME if this fails schedule/loop this for later
2130         send_push (&peer);
2131       }
2132     }
2133
2134     /* Send PULL requests */
2135     b_peers = ceil (beta * view_size);
2136     first_border = a_peers;
2137     second_border = a_peers + b_peers;
2138     if (second_border > view_size)
2139     {
2140       first_border = view_size - b_peers;
2141       second_border = view_size;
2142     }
2143     LOG (GNUNET_ERROR_TYPE_DEBUG,
2144         "Going to send pulls to %u (ceil (%f * %u)) peers.\n",
2145         b_peers, beta, view_size);
2146     for (i = first_border; i < second_border; i++)
2147     {
2148       peer = view_array[permut[i]];
2149       peer_ctx = get_peer_ctx (peer_map, &peer);
2150       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer) &&
2151           GNUNET_NO == get_peer_flag (peer_ctx, PULL_REPLY_PENDING)) // TODO
2152       { // FIXME if this fails schedule/loop this for later
2153         send_pull_request (&peer);
2154       }
2155     }
2156
2157     GNUNET_free (permut);
2158     permut = NULL;
2159   }
2160
2161
2162   /* Update view */
2163   /* TODO see how many peers are in push-/pull- list! */
2164
2165   if (push_list_size <= alpha * view_size &&
2166       0 < push_list_size &&
2167       0 < pull_list_size)
2168   {
2169     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the view.\n");
2170
2171     uint32_t final_size;
2172     uint32_t peers_to_clean_size;
2173     struct GNUNET_PeerIdentity *peers_to_clean;
2174
2175     peers_to_clean = NULL;
2176     peers_to_clean_size = 0;
2177     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, view_size);
2178     memcpy (peers_to_clean,
2179             view_array,
2180             view_size * sizeof (struct GNUNET_PeerIdentity));
2181
2182     /* Seems like recreating is the easiest way of emptying the peermap */
2183     GNUNET_CONTAINER_multipeermap_destroy (view);
2184     view = GNUNET_CONTAINER_multipeermap_create (view_size, GNUNET_NO);
2185     to_file (file_name_view_log,
2186              "--- emptied ---");
2187
2188     first_border  = GNUNET_MIN (ceil (alpha * sampler_size_est_need),
2189                                 push_list_size);
2190     second_border = first_border +
2191                     GNUNET_MIN (floor (beta  * sampler_size_est_need),
2192                                 pull_list_size);
2193     final_size    = second_border +
2194       ceil ((1 - (alpha + beta)) * sampler_size_est_need);
2195
2196     GNUNET_array_grow (view_array, view_size, second_border);
2197
2198     /* Update view with peers received through PUSHes */
2199     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2200                                            push_list_size);
2201     for (i = 0; i < first_border; i++)
2202     {
2203       view_array[i] = push_list[permut[i]];
2204       GNUNET_CONTAINER_multipeermap_put (view, &push_list[permut[i]], NULL,
2205           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2206
2207       to_file (file_name_view_log,
2208                "+%s\t(push list)",
2209                GNUNET_i2s_full (&view_array[i]));
2210       // TODO change the peer_flags accordingly
2211     }
2212     GNUNET_free (permut);
2213     permut = NULL;
2214
2215     /* Update view with peers received through PULLs */
2216     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
2217                                            pull_list_size);
2218     for (i = first_border; i < second_border; i++)
2219     {
2220       view_array[i] = pull_list[permut[i]];
2221       GNUNET_CONTAINER_multipeermap_put (view, &pull_list[permut[i]], NULL,
2222           GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
2223
2224       to_file (file_name_view_log,
2225                "+%s\t(pull list)",
2226                GNUNET_i2s_full (&view_array[i]));
2227       // TODO change the peer_flags accordingly
2228     }
2229     GNUNET_free (permut);
2230     permut = NULL;
2231
2232     /* Update view with peers from history */
2233     RPS_sampler_get_n_rand_peers (prot_sampler,
2234                                   hist_update,
2235                                   NULL,
2236                                   final_size - second_border);
2237     num_hist_update_tasks = final_size - second_border;
2238     // TODO change the peer_flags accordingly
2239
2240     for (i = 0; i < view_size; i++)
2241       rem_from_list (&peers_to_clean, &peers_to_clean_size, &view_array[i]);
2242
2243     /* Clean peers that were removed from the view */
2244     for (i = 0; i < peers_to_clean_size; i++)
2245     {
2246       peer_clean (&peers_to_clean[i]);
2247       to_file (file_name_view_log,
2248                "-%s",
2249                GNUNET_i2s_full (&peers_to_clean[i]));
2250     }
2251
2252     GNUNET_free (peers_to_clean);
2253     peers_to_clean = NULL;
2254   }
2255   else
2256   {
2257     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the view.\n");
2258   }
2259   // TODO independent of that also get some peers from CADET_get_peers()?
2260
2261   LOG (GNUNET_ERROR_TYPE_DEBUG,
2262        "Received %u pushes and %u pulls last round (alpha (%.2f) * view_size (%u) = %.2f)\n",
2263        push_list_size,
2264        pull_list_size,
2265        alpha,
2266        view_size,
2267        alpha * view_size);
2268
2269   /* Update samplers */
2270   for (i = 0; i < push_list_size; i++)
2271   {
2272     LOG (GNUNET_ERROR_TYPE_DEBUG,
2273          "Updating with peer %s from push list\n",
2274          GNUNET_i2s (&push_list[i]));
2275     RPS_sampler_update (prot_sampler,   &push_list[i]);
2276     RPS_sampler_update (client_sampler, &push_list[i]);
2277     // TODO set in_flag?
2278   }
2279
2280   for (i = 0; i < pull_list_size; i++)
2281   {
2282     LOG (GNUNET_ERROR_TYPE_DEBUG,
2283          "Updating with peer %s from pull list\n",
2284          GNUNET_i2s (&pull_list[i]));
2285     RPS_sampler_update (prot_sampler,   &pull_list[i]);
2286     RPS_sampler_update (client_sampler, &pull_list[i]);
2287     // TODO set in_flag?
2288   }
2289
2290
2291   /* Empty push/pull lists */
2292   GNUNET_array_grow (push_list, push_list_size, 0);
2293   GNUNET_array_grow (pull_list, pull_list_size, 0);
2294
2295   struct GNUNET_TIME_Relative time_next_round;
2296
2297   time_next_round = compute_rand_delay (round_interval, 2);
2298
2299   /* Schedule next round */
2300   do_round_task = GNUNET_SCHEDULER_add_delayed (time_next_round, &do_round, NULL);
2301   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
2302 }
2303
2304
2305 static void
2306 rps_start (struct GNUNET_SERVER_Handle *server);
2307
2308
2309 /**
2310  * This is called from GNUNET_CADET_get_peers().
2311  *
2312  * It is called on every peer(ID) that cadet somehow has contact with.
2313  * We use those to initialise the sampler.
2314  */
2315 void
2316 init_peer_cb (void *cls,
2317               const struct GNUNET_PeerIdentity *peer,
2318               int tunnel, // "Do we have a tunnel towards this peer?"
2319               unsigned int n_paths, // "Number of known paths towards this peer"
2320               unsigned int best_path) // "How long is the best path?
2321                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
2322 {
2323   if (NULL != peer)
2324   {
2325     LOG (GNUNET_ERROR_TYPE_DEBUG,
2326          "Got peer_id %s from cadet\n",
2327          GNUNET_i2s (peer));
2328     new_peer_id (peer);
2329   }
2330 }
2331
2332
2333 /**
2334  * Iterator over peers from peerinfo.
2335  *
2336  * @param cls closure
2337  * @param peer id of the peer, NULL for last call
2338  * @param hello hello message for the peer (can be NULL)
2339  * @param error message
2340  */
2341 void
2342 process_peerinfo_peers (void *cls,
2343                         const struct GNUNET_PeerIdentity *peer,
2344                         const struct GNUNET_HELLO_Message *hello,
2345                         const char *err_msg)
2346 {
2347   if (NULL != peer)
2348   {
2349     LOG (GNUNET_ERROR_TYPE_DEBUG,
2350          "Got peer_id %s from peerinfo\n",
2351          GNUNET_i2s (peer));
2352     new_peer_id (peer);
2353   }
2354 }
2355
2356
2357 /**
2358  * Callback used to remove peers from the multipeermap.
2359  */
2360   int
2361 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
2362 {
2363   struct PeerContext *peer_ctx;
2364   const struct GNUNET_CADET_Channel *channel =
2365     (const struct GNUNET_CADET_Channel *) cls;
2366
2367   peer_ctx = (struct PeerContext *) value;
2368   set_peer_flag (peer_ctx, TO_DESTROY);
2369
2370   LOG (GNUNET_ERROR_TYPE_DEBUG,
2371        "Going to clean peer %s\n",
2372        GNUNET_i2s (&peer_ctx->peer_id));
2373
2374   /* If operations are still scheduled for this peer cancel those */
2375   if (0 != peer_ctx->num_outstanding_ops)
2376   {
2377     GNUNET_array_grow (peer_ctx->outstanding_ops,
2378                        peer_ctx->num_outstanding_ops,
2379                        0);
2380   }
2381
2382   /* If we are still waiting for notification whether this peer is live
2383    * cancel the according task */
2384   if (NULL != peer_ctx->is_live_task)
2385   {
2386     LOG (GNUNET_ERROR_TYPE_DEBUG,
2387          "Trying to cancle is_live_task for peer %s\n",
2388          GNUNET_i2s (key));
2389     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
2390     peer_ctx->is_live_task = NULL;
2391   }
2392
2393   unset_peer_flag (peer_ctx, PULL_REPLY_PENDING);
2394
2395   to_file (file_name_view_log,
2396            "-%s\t(cleanup channel, other peer)",
2397            GNUNET_i2s_full (key));
2398   GNUNET_CONTAINER_multipeermap_remove_all (view, key);
2399
2400   /* If there is still a mq destroy it */
2401   if (NULL != peer_ctx->mq)
2402   {
2403     GNUNET_MQ_destroy (peer_ctx->mq);
2404     peer_ctx->mq = NULL;
2405   }
2406
2407
2408   /* Remove the send_channel
2409    * This function should be called again from #cleanup_channel (callback
2410    * called on the destruction of channels) and clean up the rest. */
2411   if (NULL != peer_ctx->send_channel &&
2412       channel != peer_ctx->send_channel)
2413   {
2414     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
2415     peer_ctx->send_channel = NULL;
2416   }
2417
2418   /* Remove the recv_channel
2419    * This function should be called again from #cleanup_channel (callback
2420    * called on the destruction of channels) and clean up the rest. */
2421   if (NULL != peer_ctx->recv_channel &&
2422       channel != peer_ctx->recv_channel)
2423   {
2424     GNUNET_CADET_channel_destroy (peer_ctx->recv_channel);
2425     peer_ctx->recv_channel = NULL;
2426   }
2427
2428   /* If there is no channel we have to remove the context now */
2429   if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
2430     LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
2431
2432   GNUNET_free (peer_ctx);
2433
2434   return GNUNET_YES;
2435 }
2436
2437
2438 /**
2439  * Clean the send channel of a peer
2440  * If there is also no channel to receive messages from that peer, remove it
2441  * from the peermap.
2442  */
2443 void
2444 peer_clean (const struct GNUNET_PeerIdentity *peer)
2445 {
2446   struct PeerContext *peer_ctx;
2447   /* struct GNUNET_CADET_Channel *channel; */
2448
2449   if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_contains (view, peer) &&
2450       GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2451   {
2452     peer_ctx = get_peer_ctx (peer_map, peer);
2453     GNUNET_CADET_channel_destroy (peer_ctx->send_channel);
2454     peer_ctx->send_channel = NULL;
2455
2456     if (NULL == peer_ctx->recv_channel)
2457     {
2458       peer_remove_cb (NULL, peer, peer_ctx);
2459     }
2460   }
2461 }
2462
2463
2464 /**
2465  * Task run during shutdown.
2466  *
2467  * @param cls unused
2468  * @param tc unused
2469  */
2470 static void
2471 shutdown_task (void *cls,
2472                      const struct GNUNET_SCHEDULER_TaskContext *tc)
2473 {
2474
2475   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
2476
2477   GNUNET_PEERINFO_notify_cancel (peerinfo_notify_handle);
2478   GNUNET_PEERINFO_disconnect (peerinfo_handle);
2479
2480   if (NULL != do_round_task)
2481   {
2482     GNUNET_SCHEDULER_cancel (do_round_task);
2483     do_round_task = NULL;
2484   }
2485
2486   {
2487   if (GNUNET_SYSERR ==
2488         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
2489     LOG (GNUNET_ERROR_TYPE_WARNING,
2490         "Iterating over peers to disconnect from them was cancelled\n");
2491   }
2492
2493   GNUNET_NSE_disconnect (nse);
2494   RPS_sampler_destroy (prot_sampler);
2495   RPS_sampler_destroy (client_sampler);
2496   LOG (GNUNET_ERROR_TYPE_DEBUG,
2497        "Size of the peermap: %u\n",
2498        GNUNET_CONTAINER_multipeermap_size (peer_map));
2499   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
2500   GNUNET_CADET_disconnect (cadet_handle);
2501   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2502   GNUNET_CONTAINER_multipeermap_destroy (view);
2503   view = NULL;
2504   GNUNET_array_grow (push_list, push_list_size, 0);
2505   GNUNET_array_grow (pull_list, pull_list_size, 0);
2506   #ifdef ENABLE_MALICIOUS
2507   struct AttackedPeer *tmp_att_peer;
2508   GNUNET_array_grow (mal_peers, num_mal_peers, 0);
2509   if (NULL != mal_peer_set)
2510     GNUNET_CONTAINER_multipeermap_destroy (mal_peer_set);
2511   if (NULL != att_peer_set)
2512     GNUNET_CONTAINER_multipeermap_destroy (att_peer_set);
2513   while (NULL != att_peers_head)
2514   {
2515     tmp_att_peer = att_peers_head;
2516     GNUNET_CONTAINER_DLL_remove (att_peers_head, att_peers_tail, tmp_att_peer);
2517   }
2518   #endif /* ENABLE_MALICIOUS */
2519 }
2520
2521
2522 /**
2523  * A client disconnected.  Remove all of its data structure entries.
2524  *
2525  * @param cls closure, NULL
2526  * @param client identification of the client
2527  */
2528 static void
2529 handle_client_disconnect (void *cls,
2530                           struct GNUNET_SERVER_Client * client)
2531 {
2532 }
2533
2534
2535 /**
2536  * Handle the channel a peer opens to us.
2537  *
2538  * @param cls The closure
2539  * @param channel The channel the peer wants to establish
2540  * @param initiator The peer's peer ID
2541  * @param port The port the channel is being established over
2542  * @param options Further options
2543  */
2544   static void *
2545 handle_inbound_channel (void *cls,
2546                         struct GNUNET_CADET_Channel *channel,
2547                         const struct GNUNET_PeerIdentity *initiator,
2548                         uint32_t port,
2549                         enum GNUNET_CADET_ChannelOption options)
2550 {
2551   struct PeerContext *peer_ctx;
2552   struct GNUNET_PeerIdentity peer;
2553
2554   peer = *initiator;
2555   LOG (GNUNET_ERROR_TYPE_DEBUG,
2556       "New channel was established to us (Peer %s).\n",
2557       GNUNET_i2s (&peer));
2558
2559   GNUNET_assert (NULL != channel);
2560
2561   // we might not even store the recv_channel
2562
2563   peer_ctx = get_peer_ctx (peer_map, &peer);
2564   // FIXME what do we do if a channel is established twice?
2565   //       overwrite? Clean old channel? ...?
2566   //if (NULL != peer_ctx->recv_channel)
2567   //{
2568   //  peer_ctx->recv_channel = channel;
2569   //}
2570   peer_ctx->recv_channel = channel;
2571
2572   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, &peer, peer_ctx,
2573       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
2574
2575   /* This would make the push-message unnecessary */
2576   LOG (GNUNET_ERROR_TYPE_DEBUG,
2577       "Got peer_id %s from peerinfo\n",
2578       GNUNET_i2s (&peer));
2579   new_peer_id (&peer);
2580
2581   peer_is_live (peer_ctx);
2582
2583   return NULL; // TODO
2584 }
2585
2586
2587 /**
2588  * This is called when a channel is destroyed.
2589  *
2590  * @param cls The closure
2591  * @param channel The channel being closed
2592  * @param channel_ctx The context associated with this channel
2593  */
2594   static void
2595 cleanup_channel (void *cls,
2596                 const struct GNUNET_CADET_Channel *channel,
2597                 void *channel_ctx)
2598 {
2599   struct GNUNET_PeerIdentity *peer;
2600   struct PeerContext *peer_ctx;
2601
2602   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
2603       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
2604        // Guess simply casting isn't the nicest way...
2605        // FIXME wait for cadet to change this function
2606
2607   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
2608   {/* We don't want to implicitly create a context that we're about to kill */
2609     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
2610     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
2611       return;
2612
2613     if (get_peer_flag (peer_ctx, TO_DESTROY))
2614     {/* We initiatad the destruction of this particular peer */
2615       if (channel == peer_ctx->send_channel)
2616         peer_ctx->send_channel = NULL;
2617       else if (channel == peer_ctx->recv_channel)
2618         peer_ctx->recv_channel = NULL;
2619
2620       to_file (file_name_view_log,
2621                "-%s\t(cleanup channel, ourself)",
2622                GNUNET_i2s_full (peer));
2623     }
2624
2625     else
2626     { /* We did not initiate the destruction of this peer */
2627       if (channel == peer_ctx->send_channel)
2628       { /* Something (but us) killd the channel - clean up peer */
2629         LOG (GNUNET_ERROR_TYPE_DEBUG,
2630             "send channel (%s) was destroyed - cleaning up\n",
2631             GNUNET_i2s (peer));
2632         peer_ctx->send_channel = NULL;
2633         /* Somwewhat {ab,re}use the iterator function */
2634         /* Cast to void is ok, because it's used as void in peer_remove_cb */
2635         (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
2636       }
2637       else if (channel == peer_ctx->recv_channel)
2638       { /* Other peer doesn't want to send us messages anymore */
2639         LOG (GNUNET_ERROR_TYPE_DEBUG,
2640              "Peer %s destroyed recv channel - cleaning up channel\n",
2641              GNUNET_i2s (peer));
2642         peer_ctx->recv_channel = NULL;
2643       }
2644       else
2645       {
2646         LOG (GNUNET_ERROR_TYPE_WARNING,
2647              "unknown channel (%s) was destroyed\n",
2648              GNUNET_i2s (peer));
2649       }
2650     }
2651   }
2652
2653   else
2654   { /* We don't know a context to that peer */
2655     LOG (GNUNET_ERROR_TYPE_DEBUG,
2656          "channel (%s) without associated context was destroyed\n",
2657          GNUNET_i2s (peer));
2658   }
2659 }
2660
2661
2662 /**
2663  * Actually start the service.
2664  */
2665   static void
2666 rps_start (struct GNUNET_SERVER_Handle *server)
2667 {
2668   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2669     {&handle_client_request,     NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
2670       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
2671     {&handle_client_seed,        NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
2672     #ifdef ENABLE_MALICIOUS
2673     {&handle_client_act_malicious, NULL, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2674     #endif /* ENABLE_MALICIOUS */
2675     {NULL, NULL, 0, 0}
2676   };
2677
2678   GNUNET_SERVER_add_handlers (server, handlers);
2679   GNUNET_SERVER_disconnect_notify (server,
2680                                    &handle_client_disconnect,
2681                                    NULL);
2682   LOG (GNUNET_ERROR_TYPE_INFO, "Ready to receive requests from clients\n");
2683
2684
2685   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
2686   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
2687
2688   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2689                                                         &shutdown_task,
2690                                                         NULL);
2691 }
2692
2693
2694 /**
2695  * Process statistics requests.
2696  *
2697  * @param cls closure
2698  * @param server the initialized server
2699  * @param c configuration to use
2700  */
2701   static void
2702 run (void *cls,
2703      struct GNUNET_SERVER_Handle *server,
2704      const struct GNUNET_CONFIGURATION_Handle *c)
2705 {
2706   int size;
2707   int out_size;
2708
2709   // TODO check what this does -- copied from gnunet-boss
2710   // - seems to work as expected
2711   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
2712   cfg = c;
2713
2714
2715   /* Get own ID */
2716   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
2717   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2718               "STARTING SERVICE (rps) for peer [%s]\n",
2719               GNUNET_i2s (&own_identity));
2720   #ifdef ENABLE_MALICIOUS
2721   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2722               "Malicious execution compiled in.\n");
2723   #endif /* ENABLE_MALICIOUS */
2724
2725
2726
2727   /* Get time interval from the configuration */
2728   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
2729                                                         "ROUNDINTERVAL",
2730                                                         &round_interval))
2731   {
2732     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2733                                "RPS", "ROUNDINTERVAL");
2734     GNUNET_SCHEDULER_shutdown ();
2735     return;
2736   }
2737
2738   /* Get initial size of sampler/view from the configuration */
2739   if (GNUNET_OK !=
2740       GNUNET_CONFIGURATION_get_value_number (cfg, "RPS", "INITSIZE",
2741         (long long unsigned int *) &sampler_size_est_need))
2742   {
2743     GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR,
2744                                "RPS", "INITSIZE");
2745     GNUNET_SCHEDULER_shutdown ();
2746     return;
2747   }
2748   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
2749
2750
2751   view = GNUNET_CONTAINER_multipeermap_create (4, GNUNET_NO);
2752
2753   /* file_name_view_log */
2754   if (GNUNET_OK != GNUNET_DISK_directory_create ("/tmp/rps/"))
2755   {
2756     LOG (GNUNET_ERROR_TYPE_WARNING,
2757          "Failed to create directory /tmp/rps/\n");
2758   }
2759
2760   size = (14 + strlen (GNUNET_i2s_full (&own_identity)) + 1) * sizeof (char);
2761   file_name_view_log = GNUNET_malloc (size);
2762   out_size = GNUNET_snprintf (file_name_view_log,
2763                               size,
2764                               "/tmp/rps/view-%s",
2765                               GNUNET_i2s_full (&own_identity));
2766   if (size < out_size ||
2767       0 > out_size)
2768   {
2769     LOG (GNUNET_ERROR_TYPE_WARNING,
2770          "Failed to write string to buffer (size: %i, out_size: %i)\n",
2771          size,
2772          out_size);
2773   }
2774
2775
2776   /* connect to NSE */
2777   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
2778
2779
2780   alpha = 0.45;
2781   beta  = 0.45;
2782
2783   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
2784
2785
2786   /* Initialise cadet */
2787   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
2788     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
2789       sizeof (struct GNUNET_MessageHeader)},
2790     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2791       sizeof (struct GNUNET_MessageHeader)},
2792     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
2793     {NULL, 0, 0}
2794   };
2795
2796   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
2797   cadet_handle = GNUNET_CADET_connect (cfg,
2798                                        cls,
2799                                        &handle_inbound_channel,
2800                                        &cleanup_channel,
2801                                        cadet_handlers,
2802                                        ports);
2803
2804   peerinfo_handle = GNUNET_PEERINFO_connect (cfg);
2805
2806   /* Initialise sampler */
2807   struct GNUNET_TIME_Relative half_round_interval;
2808   struct GNUNET_TIME_Relative  max_round_interval;
2809
2810   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
2811   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
2812
2813   prot_sampler =   RPS_sampler_init     (sampler_size_est_need, max_round_interval);
2814   client_sampler = RPS_sampler_mod_init (sampler_size_est_need, max_round_interval);
2815
2816   /* Initialise push and pull maps */
2817   push_list = NULL;
2818   push_list_size = 0;
2819   pull_list = NULL;
2820   pull_list_size = 0;
2821
2822
2823   num_hist_update_tasks = 0;
2824
2825
2826   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
2827   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
2828   // TODO send push/pull to each of those peers?
2829
2830   peerinfo_notify_handle = GNUNET_PEERINFO_notify (cfg,
2831                                                    GNUNET_NO,
2832                                                    process_peerinfo_peers,
2833                                                    NULL);
2834
2835   rps_start (server);
2836 }
2837
2838
2839 /**
2840  * The main function for the rps service.
2841  *
2842  * @param argc number of arguments from the command line
2843  * @param argv command line arguments
2844  * @return 0 ok, 1 on error
2845  */
2846   int
2847 main (int argc, char *const *argv)
2848 {
2849   return (GNUNET_OK ==
2850           GNUNET_SERVICE_run (argc,
2851                               argv,
2852                               "rps",
2853                               GNUNET_SERVICE_OPTION_NONE,
2854                               &run, NULL)) ? 0 : 1;
2855 }
2856
2857 /* end of gnunet-service-rps.c */