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