26778a14e3bd48b9296d4f732b3612b1701a4791
[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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, 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_nse_service.h"
30 #include "rps.h"
31
32 #include "gnunet-service-rps_sampler.h"
33
34 #include <math.h>
35 #include <inttypes.h>
36
37 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
38
39 // TODO modify @brief in every file
40
41 // TODO check for overflows
42
43 // TODO align message structs
44
45 // (TODO api -- possibility of getting weak random peer immideately)
46
47 // TODO malicious peer
48
49 // TODO connect to friends
50
51 // TODO store peers somewhere
52
53 // TODO ignore list?
54
55 // hist_size_init, hist_size_max
56
57 /**
58  * Our configuration.
59  */
60 static const struct GNUNET_CONFIGURATION_Handle *cfg;
61
62 /**
63  * Our own identity.
64  */
65 static struct GNUNET_PeerIdentity own_identity;
66
67
68   struct GNUNET_PeerIdentity *
69 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list, unsigned int size,
70                            const struct GNUNET_PeerIdentity *ignore_list, unsigned int ignore_size);
71
72
73 /***********************************************************************
74  * Housekeeping with peers
75 ***********************************************************************/
76
77 /**
78  * Struct used to store the context of a connected client.
79  */
80 struct client_ctx
81 {
82   /**
83    * The message queue to communicate with the client.
84    */
85   struct GNUNET_MQ_Handle *mq;
86 };
87
88 /**
89  * Used to keep track in what lists single peerIDs are.
90  */
91 enum PeerFlags
92 {
93   PULL_REPLY_PENDING   = 0x01,
94   IN_OTHER_GOSSIP_LIST = 0x02, // unneeded?
95   IN_OWN_SAMPLER_LIST  = 0x04, // unneeded?
96   IN_OWN_GOSSIP_LIST   = 0x08, // unneeded?
97
98   /**
99    * We set this bit when we can be sure the other peer is/was live.
100    */
101   VALID                = 0x10
102 };
103
104
105 /**
106  * Functions of this type can be used to be stored at a peer for later execution.
107  */
108 typedef void (* PeerOp) (void *cls, const struct GNUNET_PeerIdentity *peer);
109
110 /**
111  * Outstanding operation on peer consisting of callback and closure
112  */
113 struct PeerOutstandingOp
114 {
115   /**
116    * Callback
117    */
118   PeerOp op;
119
120   /**
121    * Closure
122    */
123   void *op_cls;
124 };
125
126
127 /**
128  * Struct used to keep track of other peer's status
129  *
130  * This is stored in a multipeermap.
131  */
132 struct PeerContext
133 {
134   /**
135    * In own gossip/sampler list, in other's gossip/sampler list
136    */
137   uint32_t peer_flags;
138
139   /**
140    * Message queue open to client
141    */
142   struct GNUNET_MQ_Handle *mq;
143
144   /**
145    * Channel open to client.
146    */
147   struct GNUNET_CADET_Channel *send_channel;
148
149   /**
150    * Channel open from client.
151    */
152   struct GNUNET_CADET_Channel *recv_channel; // unneeded?
153
154   /**
155    * Array of outstanding operations on this peer.
156    */
157   struct PeerOutstandingOp *outstanding_ops;
158
159   /**
160    * Number of outstanding operations.
161    */
162   unsigned int num_outstanding_ops;
163   //size_t num_outstanding_ops;
164
165   /**
166    * Handle to the callback given to cadet_ntfy_tmt_rdy()
167    *
168    * To be canceled on shutdown.
169    */
170   struct GNUNET_CADET_TransmitHandle *is_live_task;
171
172   /**
173    * Identity of the peer
174    */
175   struct GNUNET_PeerIdentity peer_id;
176
177   /**
178    * This is pobably followed by 'statistical' data (when we first saw
179    * him, how did we get his ID, how many pushes (in a timeinterval),
180    * ...)
181    */
182 };
183
184 /***********************************************************************
185  * /Housekeeping with peers
186 ***********************************************************************/
187
188
189
190
191
192 /***********************************************************************
193  * Globals
194 ***********************************************************************/
195
196 /**
197  * Sampler used for the Brahms protocol itself.
198  */
199 static struct RPS_Sampler *prot_sampler;
200
201 /**
202  * Sampler used for the clients.
203  */
204 static struct RPS_Sampler *client_sampler;
205
206 /**
207  * Set of all peers to keep track of them.
208  */
209 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
210
211
212 /**
213  * The gossiped list of peers.
214  */
215 static struct GNUNET_PeerIdentity *gossip_list;
216
217 /**
218  * Size of the gossiped list
219  */
220 //static unsigned int gossip_list_size;
221 static uint32_t gossip_list_size;
222
223
224 /**
225  * The size of sampler we need to be able to satisfy the client's need of
226  * random peers.
227  */
228 static unsigned int sampler_size_client_need;
229
230 /**
231  * The size of sampler we need to be able to satisfy the Brahms protocol's
232  * need of random peers.
233  *
234  * This is directly taken as the #gossip_list_size on update of the
235  * #gossip_list
236  *
237  * This is one minimum size the sampler grows to.
238  */
239 static unsigned int sampler_size_est_need;
240
241
242 /**
243  * Percentage of total peer number in the gossip list
244  * to send random PUSHes to
245  */
246 static float alpha;
247
248 /**
249  * Percentage of total peer number in the gossip list
250  * to send random PULLs to
251  */
252 static float beta;
253
254 /**
255  * The percentage gamma of history updates.
256  * Simply 1 - alpha - beta
257  */
258
259
260 /**
261  * Identifier for the main task that runs periodically.
262  */
263 static struct GNUNET_SCHEDULER_Task *do_round_task;
264
265 /**
266  * Time inverval the do_round task runs in.
267  */
268 static struct GNUNET_TIME_Relative round_interval;
269
270
271
272 /**
273  * List to store peers received through pushes temporary.
274  *
275  * TODO -> multipeermap
276  */
277 static struct GNUNET_PeerIdentity *push_list;
278
279 /**
280  * Size of the push_list;
281  */
282 static unsigned int push_list_size;
283 //size_t push_list_size;
284
285 /**
286  * List to store peers received through pulls temporary.
287  *
288  * TODO -> multipeermap
289  */
290 static struct GNUNET_PeerIdentity *pull_list;
291
292 /**
293  * Size of the pull_list;
294  */
295 static unsigned int pull_list_size;
296 //size_t pull_list_size;
297
298
299 /**
300  * Handler to NSE.
301  */
302 static struct GNUNET_NSE_Handle *nse;
303
304 /**
305  * Handler to CADET.
306  */
307 static struct GNUNET_CADET_Handle *cadet_handle;
308
309
310 /**
311  * Request counter.
312  *
313  * Only needed in the beginning to check how many of the 64 deltas
314  * we already have
315  */
316 static unsigned int req_counter;
317
318 /**
319  * Time of the last request we received.
320  *
321  * Used to compute the expected request rate.
322  */
323 static struct GNUNET_TIME_Absolute last_request;
324
325 /**
326  * Size of #request_deltas.
327  */
328 #define REQUEST_DELTAS_SIZE 64
329 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
330
331 /**
332  * Last 64 deltas between requests
333  */
334 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
335
336 /**
337  * The prediction of the rate of requests
338  */
339 static struct GNUNET_TIME_Relative  request_rate;
340
341
342 /**
343  * List with the peers we sent requests to.
344  */
345 struct GNUNET_PeerIdentity *pending_pull_reply_list;
346
347 /**
348  * Size of #pending_pull_reply_list.
349  */
350 uint32_t pending_pull_reply_list_size;
351
352
353 /**
354  * Number of history update tasks.
355  */
356 uint32_t num_hist_update_tasks;
357
358
359 #ifdef ENABLE_MALICIOUS
360 /**
361  * Type of malicious peer
362  *
363  * 0 Don't act malicious at all - Default
364  * 1 Try to maximise representation
365  * 2 Try to partition the network
366  */
367 uint32_t mal_type = 0;
368
369 /**
370  * Other malicious peers
371  */
372 static struct GNUNET_PeerIdentity *mal_peers;
373
374 /**
375  * Number of other malicious peers
376  */
377 static uint32_t num_mal_peers;
378
379 /**
380  * If type is 2 this is the attacked peer
381  */
382 static struct GNUNET_PeerIdentity attacked_peer;
383 #endif /* ENABLE_MALICIOUS */
384
385
386 /***********************************************************************
387  * /Globals
388 ***********************************************************************/
389
390
391
392
393
394
395 /***********************************************************************
396  * Util functions
397 ***********************************************************************/
398
399 /**
400  * Set a peer flag of given peer context.
401  */
402 #define set_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags |= mask)
403
404 /**
405  * Get peer flag of given peer context.
406  */
407 #define get_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags & mask ? GNUNET_YES : GNUNET_NO)
408
409 /**
410  * Unset flag of given peer context.
411  */
412 #define unset_peer_flag(peer_ctx, mask) (peer_ctx->peer_flags &= (~mask))
413
414
415 /**
416  * Clean the send channel of a peer
417  */
418 void
419 peer_clean (const struct GNUNET_PeerIdentity *peer);
420
421
422 /**
423  * Check if peer is already in peer array.
424  */
425   int
426 in_arr (const struct GNUNET_PeerIdentity *array,
427         unsigned int arr_size,
428         const struct GNUNET_PeerIdentity *peer)
429 {
430   GNUNET_assert (NULL != peer);
431
432   if (0 == arr_size)
433     return GNUNET_NO;
434
435   GNUNET_assert (NULL != array);
436
437   unsigned int i;
438
439   for (i = 0; i < arr_size ; i++)
440     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer))
441       return GNUNET_YES;
442   return GNUNET_NO;
443 }
444
445
446 /**
447  * Print peerlist to log.
448  */
449 void
450 print_peer_list (struct GNUNET_PeerIdentity *list, unsigned int len)
451 {
452   unsigned int i;
453
454   LOG (GNUNET_ERROR_TYPE_DEBUG,
455        "Printing peer list of length %u at %p:\n",
456        len,
457        list);
458   for (i = 0 ; i < len ; i++)
459   {
460     LOG (GNUNET_ERROR_TYPE_DEBUG,
461          "%u. peer: %s\n",
462          i, GNUNET_i2s (&list[i]));
463   }
464 }
465
466
467 /**
468  * Remove peer from list.
469  */
470   void
471 rem_from_list (struct GNUNET_PeerIdentity **peer_list,
472                unsigned int *list_size,
473                const struct GNUNET_PeerIdentity *peer)
474 {
475   unsigned int i;
476   struct GNUNET_PeerIdentity *tmp;
477
478   tmp = *peer_list;
479
480   LOG (GNUNET_ERROR_TYPE_DEBUG,
481        "Removing peer %s from list at %p\n",
482        GNUNET_i2s (peer),
483        tmp);
484
485   for ( i = 0 ; i < *list_size ; i++ )
486   {
487     if (0 == GNUNET_CRYPTO_cmp_peer_identity (&tmp[i], peer))
488     {
489       if (i < *list_size -1)
490       { /* Not at the last entry -- shift peers left */
491         memcpy (&tmp[i], &tmp[i +1],
492                 ((*list_size) - i -1) * sizeof (struct GNUNET_PeerIdentity));
493       }
494       /* Remove last entry (should be now useless PeerID) */
495       GNUNET_array_grow (tmp, *list_size, (*list_size) -1);
496     }
497   }
498   *peer_list = tmp;
499 }
500
501 /**
502  * Get random peer from the given list but don't return one from the @a ignore_list.
503  */
504   struct GNUNET_PeerIdentity *
505 get_rand_peer_ignore_list (const struct GNUNET_PeerIdentity *peer_list,
506                            uint32_t list_size,
507                            const struct GNUNET_PeerIdentity *ignore_list,
508                            uint32_t ignore_size)
509 {
510   uint32_t r_index;
511   uint32_t tmp_size;
512   struct GNUNET_PeerIdentity *tmp_peer_list;
513   struct GNUNET_PeerIdentity *peer;
514
515   GNUNET_assert (NULL != peer_list);
516   if (0 == list_size)
517     return NULL;
518
519   tmp_size = 0;
520   tmp_peer_list = NULL;
521   GNUNET_array_grow (tmp_peer_list, tmp_size, list_size);
522   memcpy (tmp_peer_list,
523           peer_list,
524           list_size * sizeof (struct GNUNET_PeerIdentity));
525   peer = GNUNET_new (struct GNUNET_PeerIdentity);
526
527   /**;
528    * Choose the r_index of the peer we want to return
529    * at random from the interval of the gossip list
530    */
531   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
532                                       tmp_size);
533   *peer = tmp_peer_list[r_index];
534
535   while (in_arr (ignore_list, ignore_size, peer))
536   {
537     rem_from_list (&tmp_peer_list, &tmp_size, peer);
538
539     print_peer_list (tmp_peer_list, tmp_size);
540
541     if (0 == tmp_size)
542     {
543       GNUNET_free (peer);
544       return NULL;
545     }
546
547     /**;
548      * Choose the r_index of the peer we want to return
549      * at random from the interval of the gossip list
550      */
551     r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
552                                         tmp_size);
553     *peer = tmp_peer_list[r_index];
554   }
555
556
557   GNUNET_array_grow (tmp_peer_list, tmp_size, 0);
558
559   return peer;
560 }
561
562
563 /**
564  * Get the context of a peer. If not existing, create.
565  */
566   struct PeerContext *
567 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
568               const struct GNUNET_PeerIdentity *peer)
569 {
570   struct PeerContext *ctx;
571
572   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
573   {
574     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
575   }
576   else
577   {
578     ctx = GNUNET_new (struct PeerContext);
579     ctx->peer_flags = 0;
580     ctx->mq = NULL;
581     ctx->send_channel = NULL;
582     ctx->recv_channel = NULL;
583     ctx->outstanding_ops = NULL;
584     ctx->num_outstanding_ops = 0;
585     ctx->is_live_task = NULL;
586     ctx->peer_id = *peer;
587     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
588                                               GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
589   }
590   return ctx;
591 }
592
593
594 /**
595  * Put random peer from sampler into the gossip list as history update.
596  */
597   void
598 hist_update (void *cls, struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
599 {
600   GNUNET_assert (1 == num_peers);
601
602   if (gossip_list_size < sampler_size_est_need)
603     GNUNET_array_append (gossip_list, gossip_list_size, *ids);
604
605   if (0 < num_hist_update_tasks)
606     num_hist_update_tasks--;
607 }
608
609
610 /**
611  * Set the peer flag to living and call the outstanding operations on this peer.
612  */
613 static size_t
614 peer_is_live (struct PeerContext *peer_ctx)
615 {
616   struct GNUNET_PeerIdentity *peer;
617
618   peer = &peer_ctx->peer_id;
619   set_peer_flag (peer_ctx, VALID);
620
621   LOG (GNUNET_ERROR_TYPE_DEBUG, "Peer %s is live\n", GNUNET_i2s (peer));
622
623   if (0 != peer_ctx->num_outstanding_ops)
624   { /* Call outstanding operations */
625     unsigned int i;
626
627     for (i = 0 ; i < peer_ctx->num_outstanding_ops ; i++)
628       peer_ctx->outstanding_ops[i].op (peer_ctx->outstanding_ops[i].op_cls, peer);
629     GNUNET_array_grow (peer_ctx->outstanding_ops, peer_ctx->num_outstanding_ops, 0);
630   }
631
632   if (NULL != peer_ctx->is_live_task)
633   {
634     GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
635     peer_ctx->is_live_task = NULL;
636   }
637
638   return 0;
639 }
640
641
642 /**
643  * Callback that is called when a channel was effectively established.
644  * This is given to ntfy_tmt_rdy and called when the channel was
645  * successfully established.
646  */
647 static size_t
648 cadet_ntfy_tmt_rdy_cb (void *cls, size_t size, void *buf)
649 {
650   struct PeerContext *peer_ctx = (struct PeerContext *) cls;
651
652   if (NULL != buf
653       && 0 != size)
654   {
655     peer_ctx->is_live_task = NULL;
656     peer_is_live (peer_ctx);
657   }
658
659   //if (NULL != peer_ctx->is_live_task)
660   //{
661   //  LOG (GNUNET_ERROR_TYPE_DEBUG,
662   //       "Trying to cancle is_live_task for peer %s\n",
663   //       GNUNET_i2s (&peer_ctx->peer_id));
664   //  GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
665   //  peer_ctx->is_live_task = NULL;
666   //}
667
668   return 0;
669 }
670
671
672 /**
673  * Get the channel of a peer. If not existing, create.
674  */
675   struct GNUNET_CADET_Channel *
676 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
677              const struct GNUNET_PeerIdentity *peer)
678 {
679   struct PeerContext *peer_ctx;
680
681   peer_ctx = get_peer_ctx (peer_map, peer);
682   if (NULL == peer_ctx->send_channel)
683   {
684     LOG (GNUNET_ERROR_TYPE_DEBUG,
685          "Trying to establish channel to peer %s\n",
686          GNUNET_i2s (peer));
687
688     peer_ctx->send_channel =
689       GNUNET_CADET_channel_create (cadet_handle,
690                                    NULL,
691                                    peer,
692                                    GNUNET_RPS_CADET_PORT,
693                                    GNUNET_CADET_OPTION_RELIABLE);
694
695     // do I have to explicitly put it in the peer_map?
696     (void) GNUNET_CONTAINER_multipeermap_put
697       (peer_map,
698        peer,
699        peer_ctx,
700        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
701   }
702   return peer_ctx->send_channel;
703 }
704
705
706 /**
707  * Get the message queue of a specific peer.
708  *
709  * If we already have a message queue open to this client,
710  * simply return it, otherways create one.
711  */
712   struct GNUNET_MQ_Handle *
713 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map,
714         const struct GNUNET_PeerIdentity *peer_id)
715 {
716   struct PeerContext *peer_ctx;
717
718   peer_ctx = get_peer_ctx (peer_map, peer_id);
719
720   if (NULL == peer_ctx->mq)
721   {
722     (void) get_channel (peer_map, peer_id);
723     peer_ctx->mq = GNUNET_CADET_mq_create (peer_ctx->send_channel);
724     //do I have to explicitly put it in the peer_map?
725     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, peer_ctx,
726                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
727   }
728   return peer_ctx->mq;
729 }
730
731
732 /**
733  * Issue check whether peer is live
734  *
735  * @param peer_ctx the context of the peer
736  */
737 void
738 check_peer_live (struct PeerContext *peer_ctx)
739 {
740   (void) get_channel (peer_map, &peer_ctx->peer_id);
741   LOG (GNUNET_ERROR_TYPE_DEBUG,
742        "Get informed about peer %s getting live\n",
743        GNUNET_i2s (&peer_ctx->peer_id));
744   peer_ctx->is_live_task =
745       GNUNET_CADET_notify_transmit_ready (peer_ctx->send_channel,
746                                           GNUNET_NO,
747                                           GNUNET_TIME_UNIT_FOREVER_REL,
748                                           sizeof (struct GNUNET_MessageHeader),
749                                           cadet_ntfy_tmt_rdy_cb,
750                                           peer_ctx);
751   // FIXME check whether this is NULL
752 }
753
754
755 /**
756  * Sum all time relatives of an array.
757   */
758   struct GNUNET_TIME_Relative
759 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
760 {
761   struct GNUNET_TIME_Relative sum;
762   uint32_t i;
763
764   sum = GNUNET_TIME_UNIT_ZERO;
765   for ( i = 0 ; i < arr_size ; i++ )
766   {
767     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
768   }
769   return sum;
770 }
771
772
773 /**
774  * Compute the average of given time relatives.
775  */
776   struct GNUNET_TIME_Relative
777 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint32_t arr_size)
778 {
779   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size);
780 }
781
782
783 /**
784  * Insert PeerID in #pull_list
785  *
786  * Called once we know a peer is live.
787  */
788   void
789 insert_in_pull_list (void *cls, const struct GNUNET_PeerIdentity *peer)
790 {
791   if (GNUNET_NO == in_arr (pull_list, pull_list_size, peer))
792     GNUNET_array_append (pull_list, pull_list_size, *peer);
793
794   peer_clean (peer);
795 }
796
797 /**
798  * Check whether #insert_in_pull_list was already scheduled
799  */
800   int
801 insert_in_pull_list_scheduled (const struct PeerContext *peer_ctx)
802 {
803   unsigned int i;
804
805   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
806     if (insert_in_pull_list == peer_ctx->outstanding_ops[i].op)
807       return GNUNET_YES;
808   return GNUNET_NO;
809 }
810
811
812 /**
813  * Insert PeerID in #gossip_list
814  *
815  * Called once we know a peer is live.
816  */
817   void
818 insert_in_gossip_list (void *cls, const struct GNUNET_PeerIdentity *peer)
819 {
820   if (GNUNET_NO == in_arr (gossip_list, gossip_list_size, peer))
821     GNUNET_array_append (gossip_list, gossip_list_size, *peer);
822
823   (void) get_channel (peer_map, peer);
824 }
825
826 /**
827  * Check whether #insert_in_gossip_list was already scheduled
828  */
829   int
830 insert_in_gossip_list_scheduled (const struct PeerContext *peer_ctx)
831 {
832   unsigned int i;
833
834   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
835     if (insert_in_gossip_list == peer_ctx->outstanding_ops[i].op)
836       return GNUNET_YES;
837   return GNUNET_NO;
838 }
839
840
841 /**
842  * Update sampler with given PeerID.
843  */
844   void
845 insert_in_sampler (void *cls, const struct GNUNET_PeerIdentity *peer)
846 {
847   LOG (GNUNET_ERROR_TYPE_DEBUG,
848        "Updating samplers with peer %s from insert_in_sampler()\n",
849        GNUNET_i2s (peer));
850   RPS_sampler_update (prot_sampler,   peer);
851   RPS_sampler_update (client_sampler, peer);
852 }
853
854
855 /**
856  * Check whether #insert_in_sampler was already scheduled
857  */
858 static int
859 insert_in_sampler_scheduled (const struct PeerContext *peer_ctx)
860 {
861   unsigned int i;
862
863   for ( i = 0 ; i < peer_ctx->num_outstanding_ops ; i++ )
864     if (insert_in_sampler== peer_ctx->outstanding_ops[i].op)
865       return GNUNET_YES;
866   return GNUNET_NO;
867 }
868
869
870 /**
871  * Wrapper around #RPS_sampler_resize()
872  *
873  * If we do not have enough sampler elements, double current sampler size
874  * If we have more than enough sampler elements, halv current sampler size
875  */
876 static void
877 resize_wrapper (struct RPS_Sampler *sampler, uint32_t new_size)
878 {
879   unsigned int sampler_size;
880
881   // TODO statistics
882   // TODO respect the min, max
883   sampler_size = RPS_sampler_get_size (sampler);
884   if (sampler_size > new_size * 4)
885   { /* Shrinking */
886     RPS_sampler_resize (sampler, sampler_size / 2);
887   }
888   else if (sampler_size < new_size)
889   { /* Growing */
890     RPS_sampler_resize (sampler, sampler_size * 2);
891   }
892   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
893 }
894
895
896 /**
897  * Wrapper around #RPS_sampler_resize() resizing the client sampler
898  */
899 static void
900 client_resize_wrapper ()
901 {
902   uint32_t bigger_size;
903   unsigned int sampler_size;
904
905   // TODO statistics
906
907   sampler_size = RPS_sampler_get_size (client_sampler);
908
909   if (sampler_size_est_need > sampler_size_client_need)
910     bigger_size = sampler_size_est_need;
911   else
912     bigger_size = sampler_size_client_need;
913
914   // TODO respect the min, max
915   resize_wrapper (client_sampler, bigger_size);
916   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler_size is now %u\n", sampler_size);
917 }
918
919
920 /**
921  * Estimate request rate
922  *
923  * Called every time we receive a request from the client.
924  */
925   void
926 est_request_rate()
927 {
928   struct GNUNET_TIME_Relative max_round_duration;
929
930   if (request_deltas_size > req_counter)
931     req_counter++;
932   if ( 1 < req_counter)
933   {
934     /* Shift last request deltas to the right */
935     memcpy (&request_deltas[1],
936         request_deltas,
937         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
938
939     /* Add current delta to beginning */
940     request_deltas[0] =
941         GNUNET_TIME_absolute_get_difference (last_request,
942                                              GNUNET_TIME_absolute_get ());
943     request_rate = T_relative_avg (request_deltas, req_counter);
944
945     /* Compute the duration a round will maximally take */
946     max_round_duration =
947         GNUNET_TIME_relative_add (round_interval,
948                                   GNUNET_TIME_relative_divide (round_interval, 2));
949
950     /* Set the estimated size the sampler has to have to
951      * satisfy the current client request rate */
952     sampler_size_client_need =
953         max_round_duration.rel_value_us / request_rate.rel_value_us;
954
955     /* Resize the sampler */
956     client_resize_wrapper ();
957   }
958   last_request = GNUNET_TIME_absolute_get ();
959 }
960
961
962 /***********************************************************************
963  * /Util functions
964 ***********************************************************************/
965
966
967
968
969
970 /**
971  * Function called by NSE.
972  *
973  * Updates sizes of sampler list and gossip list and adapt those lists
974  * accordingly.
975  */
976   void
977 nse_callback (void *cls, struct GNUNET_TIME_Absolute timestamp,
978               double logestimate, double std_dev)
979 {
980   double estimate;
981   //double scale; // TODO this might go gloabal/config
982
983   LOG (GNUNET_ERROR_TYPE_DEBUG,
984        "Received a ns estimate - logest: %f, std_dev: %f (old_size: %u)\n",
985        logestimate, std_dev, RPS_sampler_get_size (prot_sampler));
986   //scale = .01;
987   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
988   // GNUNET_NSE_log_estimate_to_n (logestimate);
989   estimate = pow (estimate, 1.0 / 3);
990   // TODO add if std_dev is a number
991   // estimate += (std_dev * scale);
992   if (2 < ceil (estimate))
993   {
994     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
995     sampler_size_est_need = estimate;
996   } else
997     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
998
999   /* If the NSE has changed adapt the lists accordingly */
1000   resize_wrapper (prot_sampler, sampler_size_est_need);
1001   client_resize_wrapper ();
1002 }
1003
1004
1005 /**
1006  * Callback called once the requested PeerIDs are ready.
1007  *
1008  * Sends those to the requesting client.
1009  */
1010 void client_respond (void *cls,
1011     struct GNUNET_PeerIdentity *ids, uint32_t num_peers)
1012 {
1013   LOG (GNUNET_ERROR_TYPE_DEBUG, "sampler returned %" PRIX32 " peers\n", num_peers);
1014   struct GNUNET_MQ_Envelope *ev;
1015   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
1016   struct GNUNET_SERVER_Client *client;
1017   uint32_t size_needed;
1018   struct client_ctx *cli_ctx;
1019
1020   client = (struct GNUNET_SERVER_Client *) cls;
1021
1022   size_needed = sizeof (struct GNUNET_RPS_CS_ReplyMessage) +
1023                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1024
1025   GNUNET_assert (GNUNET_SERVER_MAX_MESSAGE_SIZE >= size_needed);
1026
1027   ev = GNUNET_MQ_msg_extra (out_msg,
1028                             num_peers * sizeof (struct GNUNET_PeerIdentity),
1029                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
1030   out_msg->num_peers = htonl (num_peers);
1031
1032   memcpy (&out_msg[1],
1033       ids,
1034       num_peers * sizeof (struct GNUNET_PeerIdentity));
1035   GNUNET_free (ids);
1036
1037   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
1038   if ( NULL == cli_ctx ) {
1039     cli_ctx = GNUNET_new (struct client_ctx);
1040     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
1041     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
1042   }
1043
1044   GNUNET_MQ_send (cli_ctx->mq, ev);
1045 }
1046
1047
1048 /**
1049  * Handle RPS request from the client.
1050  *
1051  * @param cls closure
1052  * @param client identification of the client
1053  * @param message the actual message
1054  */
1055 static void
1056 handle_client_request (void *cls,
1057             struct GNUNET_SERVER_Client *client,
1058             const struct GNUNET_MessageHeader *message)
1059 {
1060   struct GNUNET_RPS_CS_RequestMessage *msg;
1061   uint32_t num_peers;
1062   uint32_t size_needed;
1063   uint32_t i;
1064
1065   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
1066
1067   num_peers = ntohl (msg->num_peers);
1068   size_needed = sizeof (struct GNUNET_RPS_CS_RequestMessage) +
1069                 num_peers * sizeof (struct GNUNET_PeerIdentity);
1070
1071   if (GNUNET_SERVER_MAX_MESSAGE_SIZE < size_needed)
1072   {
1073     GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1074     return;
1075   }
1076
1077   for (i = 0 ; i < num_peers ; i++)
1078     est_request_rate();
1079
1080   LOG (GNUNET_ERROR_TYPE_DEBUG, "Client requested %" PRIX32 " random peer(s).\n", num_peers);
1081
1082   RPS_sampler_get_n_rand_peers (client_sampler, client_respond,
1083                                 client, num_peers, GNUNET_YES);
1084
1085   GNUNET_SERVER_receive_done (client,
1086                               GNUNET_OK);
1087 }
1088
1089
1090 /**
1091  * Handle seed from the client.
1092  *
1093  * @param cls closure
1094  * @param client identification of the client
1095  * @param message the actual message
1096  */
1097   static void
1098 handle_client_seed (void *cls,
1099             struct GNUNET_SERVER_Client *client,
1100             const struct GNUNET_MessageHeader *message)
1101 {
1102   struct GNUNET_RPS_CS_SeedMessage *in_msg;
1103   struct GNUNET_PeerIdentity *peers;
1104   uint32_t num_peers;
1105   uint32_t i;
1106
1107   if (sizeof (struct GNUNET_RPS_CS_SeedMessage) > ntohs (message->size))
1108   {
1109     GNUNET_break_op (0);
1110     GNUNET_SERVER_receive_done (client,
1111                                 GNUNET_SYSERR);
1112   }
1113
1114   in_msg = (struct GNUNET_RPS_CS_SeedMessage *) message;
1115   num_peers = ntohl (in_msg->num_peers);
1116   peers = (struct GNUNET_PeerIdentity *) &in_msg[1];
1117   //peers = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
1118   //memcpy (peers, &in_msg[1], num_peers * sizeof (struct GNUNET_PeerIdentity));
1119
1120   if ((ntohs (message->size) - sizeof (struct GNUNET_RPS_CS_SeedMessage)) /
1121       sizeof (struct GNUNET_PeerIdentity) != num_peers)
1122   {
1123     GNUNET_break_op (0);
1124     GNUNET_SERVER_receive_done (client,
1125                                 GNUNET_SYSERR);
1126   }
1127
1128   LOG (GNUNET_ERROR_TYPE_DEBUG,
1129        "Client seeded peers:\n");
1130   print_peer_list (peers, num_peers);
1131
1132   // TODO check for validity of ids
1133
1134   for (i = 0 ; i < num_peers ; i++)
1135   {
1136     LOG (GNUNET_ERROR_TYPE_DEBUG,
1137          "Updating samplers with seed %" PRIX32 ": %s\n",
1138          i,
1139          GNUNET_i2s (&peers[i]));
1140
1141     RPS_sampler_update (prot_sampler,   &peers[i]);
1142     RPS_sampler_update (client_sampler, &peers[i]);
1143   }
1144
1145   //GNUNET_free (peers);
1146
1147   GNUNET_SERVER_receive_done (client,
1148                                                 GNUNET_OK);
1149 }
1150
1151
1152 /**
1153  * Handle a PUSH message from another peer.
1154  *
1155  * Check the proof of work and store the PeerID
1156  * in the temporary list for pushed PeerIDs.
1157  *
1158  * @param cls Closure
1159  * @param channel The channel the PUSH was received over
1160  * @param channel_ctx The context associated with this channel
1161  * @param msg The message header
1162  */
1163 static int
1164 handle_peer_push (void *cls,
1165     struct GNUNET_CADET_Channel *channel,
1166     void **channel_ctx,
1167     const struct GNUNET_MessageHeader *msg)
1168 {
1169   const struct GNUNET_PeerIdentity *peer;
1170
1171   // (check the proof of work)
1172
1173   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
1174   // FIXME wait for cadet to change this function
1175   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
1176
1177   /* Add the sending peer to the push_list */
1178   if (GNUNET_NO == in_arr (push_list, push_list_size, peer))
1179     GNUNET_array_append (push_list, push_list_size, *peer);
1180
1181   return GNUNET_OK;
1182 }
1183
1184 /**
1185  * Handle PULL REQUEST request message from another peer.
1186  *
1187  * Reply with the gossip list of PeerIDs.
1188  *
1189  * @param cls Closure
1190  * @param channel The channel the PUSH was received over
1191  * @param channel_ctx The context associated with this channel
1192  * @param msg The message header
1193  */
1194 static int
1195 handle_peer_pull_request (void *cls,
1196     struct GNUNET_CADET_Channel *channel,
1197     void **channel_ctx,
1198     const struct GNUNET_MessageHeader *msg)
1199 {
1200   struct GNUNET_PeerIdentity *peer;
1201   uint32_t send_size;
1202   struct GNUNET_MQ_Handle *mq;
1203   struct GNUNET_MQ_Envelope *ev;
1204   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1205
1206
1207   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel,
1208                                                                        GNUNET_CADET_OPTION_PEER);
1209   // FIXME wait for cadet to change this function
1210
1211   /* Compute actual size */
1212   send_size = sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) +
1213               gossip_list_size * sizeof (struct GNUNET_PeerIdentity);
1214
1215   if (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE < send_size)
1216     /* Compute number of peers to send
1217      * If too long, simply truncate */
1218     send_size =
1219       (GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE -
1220        sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1221        sizeof (struct GNUNET_PeerIdentity);
1222   else
1223     send_size = gossip_list_size;
1224
1225   LOG (GNUNET_ERROR_TYPE_DEBUG,
1226       "PULL REQUEST from peer %s received, going to send %u peers\n",
1227       GNUNET_i2s (peer), send_size);
1228
1229   mq = get_mq (peer_map, peer);
1230
1231   ev = GNUNET_MQ_msg_extra (out_msg,
1232                            send_size * sizeof (struct GNUNET_PeerIdentity),
1233                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1234   //out_msg->num_peers = htonl (gossip_list_size);
1235   out_msg->num_peers = htonl (send_size);
1236   memcpy (&out_msg[1], gossip_list,
1237          send_size * sizeof (struct GNUNET_PeerIdentity));
1238
1239   GNUNET_MQ_send (mq, ev);
1240
1241   return GNUNET_OK;
1242 }
1243
1244
1245 /**
1246  * Handle PULL REPLY message from another peer.
1247  *
1248  * Check whether we sent a corresponding request and
1249  * whether this reply is the first one.
1250  *
1251  * @param cls Closure
1252  * @param channel The channel the PUSH was received over
1253  * @param channel_ctx The context associated with this channel
1254  * @param msg The message header
1255  */
1256   static int
1257 handle_peer_pull_reply (void *cls,
1258                         struct GNUNET_CADET_Channel *channel,
1259                         void **channel_ctx,
1260                         const struct GNUNET_MessageHeader *msg)
1261 {
1262   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1263
1264   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1265   struct GNUNET_PeerIdentity *peers;
1266   struct PeerContext *peer_ctx;
1267   struct GNUNET_PeerIdentity *sender;
1268   struct PeerContext *sender_ctx;
1269   struct PeerOutstandingOp out_op;
1270   uint32_t i;
1271
1272   /* Check for protocol violation */
1273   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) > ntohs (msg->size))
1274   {
1275     GNUNET_break_op (0);
1276     return GNUNET_SYSERR;
1277   }
1278
1279   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1280   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1281       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1282   {
1283     LOG (GNUNET_ERROR_TYPE_ERROR,
1284         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1285         ntohl (in_msg->num_peers),
1286         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage)) /
1287             sizeof (struct GNUNET_PeerIdentity));
1288     GNUNET_break_op (0);
1289     return GNUNET_SYSERR;
1290   }
1291
1292   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1293       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1294        // Guess simply casting isn't the nicest way...
1295        // FIXME wait for cadet to change this function
1296   sender_ctx = get_peer_ctx (peer_map, sender);
1297
1298   if (GNUNET_YES == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1299   {
1300     GNUNET_break_op (0);
1301     return GNUNET_OK;
1302   }
1303
1304   /* Do actual logic */
1305   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1306   for (i = 0 ; i < ntohl (in_msg->num_peers) ; i++)
1307   {
1308     peer_ctx = get_peer_ctx (peer_map, &peers[i]);
1309     if (GNUNET_YES == get_peer_flag (peer_ctx, VALID)
1310         || NULL != peer_ctx->send_channel
1311         || NULL != peer_ctx->recv_channel)
1312     {
1313       if (GNUNET_NO == in_arr (pull_list, pull_list_size, &peers[i])
1314           && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peers[i]))
1315         GNUNET_array_append (pull_list, pull_list_size, peers[i]);
1316     }
1317     else if (GNUNET_NO == insert_in_pull_list_scheduled (peer_ctx))
1318     {
1319       out_op.op = insert_in_pull_list;
1320       out_op.op_cls = NULL;
1321       GNUNET_array_append (peer_ctx->outstanding_ops,
1322                            peer_ctx->num_outstanding_ops,
1323                            out_op);
1324       check_peer_live (peer_ctx);
1325     }
1326   }
1327
1328   unset_peer_flag (sender_ctx, PULL_REPLY_PENDING);
1329   rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, sender);
1330
1331   return GNUNET_OK;
1332 }
1333
1334
1335
1336
1337 #ifdef ENABLE_MALICIOUS
1338 /**
1339  * Turn RPS service to act malicious.
1340  *
1341  * @param cls Closure
1342  * @param channel The channel the PUSH was received over
1343  * @param channel_ctx The context associated with this channel
1344  * @param msg The message header
1345  */
1346   static int
1347 handle_peer_act_malicious (void *cls,
1348                            struct GNUNET_CADET_Channel *channel,
1349                            void **channel_ctx,
1350                            const struct GNUNET_MessageHeader *msg)
1351 {
1352   struct GNUNET_RPS_CS_ActMaliciousMessage *in_msg;
1353   struct GNUNET_PeerIdentity *sender;
1354   struct PeerContext *sender_ctx;
1355   struct GNUNET_PeerIdentity *peers;
1356
1357   /* Check for protocol violation */
1358   if (sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage) > ntohs (msg->size))
1359   {
1360     GNUNET_break_op (0);
1361     return GNUNET_SYSERR;
1362   }
1363
1364   in_msg = (struct GNUNET_RPS_CS_ActMaliciousMessage *) msg;
1365   if ((ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1366       sizeof (struct GNUNET_PeerIdentity) != ntohl (in_msg->num_peers))
1367   {
1368     LOG (GNUNET_ERROR_TYPE_ERROR,
1369         "message says it sends %" PRIu64 " peers, have space for %i peers\n",
1370         ntohl (in_msg->num_peers),
1371         (ntohs (msg->size) - sizeof (struct GNUNET_RPS_CS_ActMaliciousMessage)) /
1372             sizeof (struct GNUNET_PeerIdentity));
1373     GNUNET_break_op (0);
1374     return GNUNET_SYSERR;
1375   }
1376
1377   sender = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1378       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1379        // Guess simply casting isn't the nicest way...
1380        // FIXME wait for cadet to change this function
1381   sender_ctx = get_peer_ctx (peer_map, sender);
1382
1383   if (GNUNET_YES == get_peer_flag (sender_ctx, PULL_REPLY_PENDING))
1384   {
1385     GNUNET_break_op (0);
1386     return GNUNET_OK;
1387   }
1388
1389
1390   /* Do actual logic */
1391   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1392   num_mal_peers = ntohl (in_msg->num_peers);
1393   mal_type = ntohl (in_msg->type);
1394
1395   LOG (GNUNET_ERROR_TYPE_DEBUG,
1396        "Now acting malicious type %" PRIX32 "\n",
1397        mal_type);
1398
1399   if (1 == mal_type)
1400   { /* Try to maximise representation */
1401     num_mal_peers = ntohl (in_msg->num_peers);
1402     mal_peers = GNUNET_new_array (num_mal_peers,
1403                                   struct GNUNET_PeerIdentity);
1404     memcpy (mal_peers, peers, num_mal_peers);
1405
1406     /* Substitute do_round () with do_mal_round () */
1407     GNUNET_SCHEDULER_cancel (do_round_task);
1408     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1409   }
1410   else if (2 == mal_type)
1411   { /* Try to partition the network */
1412     num_mal_peers = ntohl (in_msg->num_peers) - 1;
1413     mal_peers = GNUNET_new_array (num_mal_peers,
1414                                   struct GNUNET_PeerIdentity);
1415     memcpy (mal_peers, peers, num_mal_peers);
1416     attacked_peer = peers[num_mal_peers];
1417
1418     /* Substitute do_round () with do_mal_round () */
1419     GNUNET_SCHEDULER_cancel (do_round_task);
1420     do_round_task = GNUNET_SCHEDULER_add_now (&do_mal_round, NULL);
1421   }
1422   else if (0 == mal_type)
1423   { /* Stop acting malicious */
1424     num_mal_peers = 0;
1425     GNUNET_free (mal_peers);
1426
1427     /* Substitute do_mal_round () with do_round () */
1428     GNUNET_SCHEDULER_cancel (do_round_task);
1429     do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1430   }
1431   else
1432   {
1433     GNUNET_break (0);
1434   }
1435
1436   return GNUNET_OK;
1437 }
1438
1439
1440 /**
1441  * Send out PUSHes and PULLs maliciously.
1442  *
1443  * This is executed regylary.
1444  */
1445 static void
1446 do_mal_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1447 {
1448   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round maliciously.\n");
1449
1450   /* Do stuff */
1451
1452   /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
1453   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
1454   do
1455   {
1456   /*
1457    * Compute random value between (0 and 1) * round_interval
1458    * via multiplying round_interval with a 'fraction' (0 to value)/value
1459    */
1460   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
1461   time_next_round = GNUNET_TIME_relative_multiply (round_interval,  rand_delay);
1462   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
1463   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
1464   } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
1465
1466   /* Schedule next round */
1467   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_mal_round, NULL);
1468   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1469 }
1470 #endif /* ENABLE_MALICIOUS */
1471
1472
1473 /**
1474  * Send out PUSHes and PULLs, possibly update #gossip_list, samplers.
1475  *
1476  * This is executed regylary.
1477  */
1478 static void
1479 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1480 {
1481   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round.\n");
1482
1483   uint32_t i;
1484   unsigned int *permut;
1485   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
1486   struct GNUNET_MQ_Envelope *ev;
1487   struct GNUNET_PeerIdentity peer;
1488   struct GNUNET_PeerIdentity *tmp_peer;
1489   struct GNUNET_MQ_Handle *mq;
1490
1491   LOG (GNUNET_ERROR_TYPE_DEBUG,
1492        "Printing gossip list:\n");
1493   for (i = 0 ; i < gossip_list_size ; i++)
1494     LOG (GNUNET_ERROR_TYPE_DEBUG,
1495          "\t%s\n", GNUNET_i2s (&gossip_list[i]));
1496   // TODO log lists, ...
1497
1498   /* Would it make sense to have one shuffeled gossip list and then
1499    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1500    * use the rest to update sampler?
1501    * in essence get random peers with consumption */
1502
1503   /* Send PUSHes */
1504   if (0 < gossip_list_size)
1505   {
1506     permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG,
1507                                            (unsigned int) gossip_list_size);
1508     n_peers = ceil (alpha * gossip_list_size);
1509     LOG (GNUNET_ERROR_TYPE_DEBUG,
1510          "Going to send pushes to %u ceil (%f * %u) peers.\n",
1511          n_peers, alpha, gossip_list_size);
1512     for (i = 0 ; i < n_peers ; i++)
1513     {
1514       peer = gossip_list[permut[i]];
1515       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer)) // TODO
1516       { // FIXME if this fails schedule/loop this for later
1517         LOG (GNUNET_ERROR_TYPE_DEBUG,
1518              "Sending PUSH to peer %s of gossiped list.\n",
1519              GNUNET_i2s (&peer));
1520
1521         ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1522         mq = get_mq (peer_map, &peer);
1523         GNUNET_MQ_send (mq, ev);
1524       }
1525     }
1526     GNUNET_free (permut);
1527   }
1528
1529
1530   /* Send PULL requests */
1531   //permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1532   n_peers = ceil (beta * gossip_list_size);
1533   LOG (GNUNET_ERROR_TYPE_DEBUG,
1534        "Going to send pulls to %u ceil (%f * %u) peers.\n",
1535        n_peers, beta, gossip_list_size);
1536   for (i = 0 ; i < n_peers ; i++)
1537   {
1538     tmp_peer = get_rand_peer_ignore_list (gossip_list, gossip_list_size,
1539         pending_pull_reply_list, pending_pull_reply_list_size);
1540     if (NULL != tmp_peer)
1541     {
1542       peer = *tmp_peer;
1543       GNUNET_free (tmp_peer);
1544
1545       GNUNET_array_append (pending_pull_reply_list, pending_pull_reply_list_size, peer);
1546
1547       if (0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, &peer))
1548       { // FIXME if this fails schedule/loop this for later
1549         LOG (GNUNET_ERROR_TYPE_DEBUG,
1550              "Sending PULL request to peer %s of gossiped list.\n",
1551              GNUNET_i2s (&peer));
1552
1553         ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1554         mq = get_mq (peer_map, &peer);
1555         GNUNET_MQ_send (mq, ev);
1556       }
1557     }
1558   }
1559
1560
1561   /* Update gossip list */
1562
1563   if ( push_list_size <= alpha * gossip_list_size &&
1564        push_list_size != 0 &&
1565        pull_list_size != 0 )
1566   {
1567     LOG (GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list.\n");
1568
1569     uint32_t first_border;
1570     uint32_t second_border;
1571     uint32_t r_index;
1572     uint32_t peers_to_clean_size;
1573     struct GNUNET_PeerIdentity *peers_to_clean;
1574
1575     peers_to_clean = NULL;
1576     peers_to_clean_size = 0;
1577     GNUNET_array_grow (peers_to_clean, peers_to_clean_size, gossip_list_size);
1578     memcpy (peers_to_clean,
1579             gossip_list,
1580             gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
1581
1582     first_border  =                ceil (alpha * sampler_size_est_need);
1583     second_border = first_border + ceil (beta  * sampler_size_est_need);
1584
1585     GNUNET_array_grow (gossip_list, gossip_list_size, second_border);
1586
1587     for (i = 0 ; i < first_border ; i++)
1588     { // TODO use RPS_sampler_get_n_rand_peers
1589       /* Update gossip list with peers received through PUSHes */
1590       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1591                                        push_list_size);
1592       gossip_list[i] = push_list[r_index];
1593       // TODO change the peer_flags accordingly
1594     }
1595
1596     for (i = first_border ; i < second_border ; i++)
1597     {
1598       /* Update gossip list with peers received through PULLs */
1599       r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
1600                                        pull_list_size);
1601       gossip_list[i] = pull_list[r_index];
1602       // TODO change the peer_flags accordingly
1603     }
1604
1605     for (i = second_border ; i < sampler_size_est_need ; i++)
1606     {
1607       /* Update gossip list with peers from history */
1608       RPS_sampler_get_n_rand_peers (prot_sampler, hist_update, NULL, 1, GNUNET_NO);
1609       num_hist_update_tasks++;
1610       // TODO change the peer_flags accordingly
1611     }
1612
1613     for (i = 0 ; i < gossip_list_size ; i++)
1614       rem_from_list (&peers_to_clean, &peers_to_clean_size, &gossip_list[i]);
1615
1616     for (i = 0 ; i < peers_to_clean_size ; i++)
1617       peer_clean (&peers_to_clean[i]);
1618
1619     GNUNET_free (peers_to_clean);
1620   }
1621   else
1622   {
1623     LOG (GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list.\n");
1624   }
1625   // TODO independent of that also get some peers from CADET_get_peers()?
1626
1627
1628   /* Update samplers */
1629   for ( i = 0 ; i < push_list_size ; i++ )
1630   {
1631     LOG (GNUNET_ERROR_TYPE_DEBUG,
1632          "Updating with peer %s from push list\n",
1633          GNUNET_i2s (&push_list[i]));
1634     RPS_sampler_update (prot_sampler,   &push_list[i]);
1635     RPS_sampler_update (client_sampler, &push_list[i]);
1636     // TODO set in_flag?
1637   }
1638
1639   for ( i = 0 ; i < pull_list_size ; i++ )
1640   {
1641     LOG (GNUNET_ERROR_TYPE_DEBUG,
1642          "Updating with peer %s from pull list\n",
1643          GNUNET_i2s (&pull_list[i]));
1644     RPS_sampler_update (prot_sampler,   &push_list[i]);
1645     RPS_sampler_update (client_sampler, &push_list[i]);
1646     // TODO set in_flag?
1647   }
1648
1649
1650   /* Empty push/pull lists */
1651   GNUNET_array_grow (push_list, push_list_size, 0);
1652   GNUNET_array_grow (pull_list, pull_list_size, 0);
1653
1654   struct GNUNET_TIME_Relative time_next_round;
1655   struct GNUNET_TIME_Relative half_round_interval;
1656   unsigned int rand_delay;
1657
1658
1659   /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
1660   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
1661   do
1662   {
1663   /*
1664    * Compute random value between (0 and 1) * round_interval
1665    * via multiplying round_interval with a 'fraction' (0 to value)/value
1666    */
1667   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
1668   time_next_round = GNUNET_TIME_relative_multiply (round_interval,  rand_delay);
1669   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
1670   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
1671   } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
1672
1673   /* Schedule next round */
1674   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
1675   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1676 }
1677
1678
1679 static void
1680 rps_start (struct GNUNET_SERVER_Handle *server);
1681
1682
1683 /**
1684  * This is called from GNUNET_CADET_get_peers().
1685  *
1686  * It is called on every peer(ID) that cadet somehow has contact with.
1687  * We use those to initialise the sampler.
1688  */
1689 void
1690 init_peer_cb (void *cls,
1691               const struct GNUNET_PeerIdentity *peer,
1692               int tunnel, // "Do we have a tunnel towards this peer?"
1693               unsigned int n_paths, // "Number of known paths towards this peer"
1694               unsigned int best_path) // "How long is the best path?
1695                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1696 {
1697   struct PeerOutstandingOp out_op;
1698   struct PeerContext *peer_ctx;
1699
1700   if (NULL != peer
1701       && 0 != GNUNET_CRYPTO_cmp_peer_identity (&own_identity, peer))
1702   {
1703     LOG (GNUNET_ERROR_TYPE_DEBUG,
1704         "Got peer %s (at %p) from CADET (gossip_list_size: %u)\n",
1705         GNUNET_i2s (peer), peer, gossip_list_size);
1706
1707     // maybe create a function for that
1708     peer_ctx = get_peer_ctx (peer_map, peer);
1709     if (GNUNET_YES != get_peer_flag (peer_ctx, VALID))
1710     {
1711       if (GNUNET_NO == insert_in_sampler_scheduled (peer_ctx))
1712       {
1713         out_op.op = insert_in_sampler;
1714         out_op.op_cls = NULL;
1715         GNUNET_array_append (peer_ctx->outstanding_ops,
1716                              peer_ctx->num_outstanding_ops,
1717                              out_op);
1718       }
1719
1720       if (GNUNET_NO == insert_in_gossip_list_scheduled (peer_ctx))
1721       {
1722         out_op.op = insert_in_gossip_list;
1723         out_op.op_cls = NULL;
1724         GNUNET_array_append (peer_ctx->outstanding_ops,
1725                              peer_ctx->num_outstanding_ops,
1726                              out_op);
1727       }
1728
1729       /* Trigger livelyness test on peer */
1730       check_peer_live (peer_ctx);
1731     }
1732
1733     // send push/pull to each of those peers?
1734   }
1735 }
1736
1737
1738 /**
1739  * Clean the send channel of a peer
1740  */
1741 void
1742 peer_clean (const struct GNUNET_PeerIdentity *peer)
1743 {
1744   struct PeerContext *peer_ctx;
1745   struct GNUNET_CADET_Channel *channel;
1746
1747   if (GNUNET_YES != in_arr (gossip_list, gossip_list_size, peer)
1748       && GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1749   {
1750     peer_ctx = get_peer_ctx (peer_map, peer);
1751     if (NULL != peer_ctx->send_channel)
1752     {
1753       channel = peer_ctx->send_channel;
1754       peer_ctx->send_channel = NULL;
1755       GNUNET_CADET_channel_destroy (channel);
1756     }
1757   }
1758 }
1759
1760
1761 /**
1762  * Callback used to remove peers from the multipeermap.
1763  */
1764   int
1765 peer_remove_cb (void *cls, const struct GNUNET_PeerIdentity *key, void *value)
1766 {
1767   struct PeerContext *peer_ctx;
1768   const struct GNUNET_CADET_Channel *channel =
1769     (const struct GNUNET_CADET_Channel *) cls;
1770   struct GNUNET_CADET_Channel *recv;
1771   struct GNUNET_CADET_Channel *send;
1772
1773   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, value))
1774   {
1775     peer_ctx = (struct PeerContext *) value;
1776
1777     if (0 != peer_ctx->num_outstanding_ops)
1778       GNUNET_array_grow (peer_ctx->outstanding_ops,
1779                          peer_ctx->num_outstanding_ops,
1780                          0);
1781
1782     if (NULL != peer_ctx->mq)
1783       GNUNET_MQ_destroy (peer_ctx->mq);
1784
1785     if (NULL != peer_ctx->is_live_task)
1786     {
1787     LOG (GNUNET_ERROR_TYPE_DEBUG,
1788          "Trying to cancle is_live_task for peer %s\n",
1789          GNUNET_i2s (key));
1790       GNUNET_CADET_notify_transmit_ready_cancel (peer_ctx->is_live_task);
1791       peer_ctx->is_live_task = NULL;
1792     }
1793
1794     send = peer_ctx->send_channel;
1795     peer_ctx->send_channel = NULL;
1796     if (NULL != send
1797         && channel != send)
1798     {
1799       GNUNET_CADET_channel_destroy (send);
1800     }
1801
1802     recv = peer_ctx->send_channel;
1803     peer_ctx->recv_channel = NULL;
1804     if (NULL != recv
1805         && channel != recv)
1806     {
1807       GNUNET_CADET_channel_destroy (recv);
1808     }
1809
1810     if (GNUNET_YES != GNUNET_CONTAINER_multipeermap_remove_all (peer_map, key))
1811       LOG (GNUNET_ERROR_TYPE_WARNING, "removing peer from peer_map failed\n");
1812     else
1813       GNUNET_free (peer_ctx);
1814   }
1815
1816   return GNUNET_YES;
1817 }
1818
1819
1820 /**
1821  * Task run during shutdown.
1822  *
1823  * @param cls unused
1824  * @param tc unused
1825  */
1826 static void
1827 shutdown_task (void *cls,
1828                      const struct GNUNET_SCHEDULER_TaskContext *tc)
1829 {
1830   LOG (GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1831
1832   if (NULL != do_round_task)
1833   {
1834     GNUNET_SCHEDULER_cancel (do_round_task);
1835     do_round_task = NULL;
1836   }
1837
1838
1839   {
1840   if (GNUNET_SYSERR ==
1841         GNUNET_CONTAINER_multipeermap_iterate (peer_map, peer_remove_cb, NULL))
1842     LOG (GNUNET_ERROR_TYPE_WARNING,
1843         "Iterating over peers to disconnect from them was cancelled\n");
1844   }
1845
1846   GNUNET_NSE_disconnect (nse);
1847   GNUNET_CADET_disconnect (cadet_handle);
1848   RPS_sampler_destroy (prot_sampler);
1849   RPS_sampler_destroy (client_sampler);
1850   LOG (GNUNET_ERROR_TYPE_DEBUG,
1851        "Size of the peermap: %u\n",
1852        GNUNET_CONTAINER_multipeermap_size (peer_map));
1853   GNUNET_break (0 == GNUNET_CONTAINER_multipeermap_size (peer_map));
1854   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
1855   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1856   GNUNET_array_grow (push_list, push_list_size, 0);
1857   GNUNET_array_grow (pull_list, pull_list_size, 0);
1858 }
1859
1860
1861 /**
1862  * A client disconnected.  Remove all of its data structure entries.
1863  *
1864  * @param cls closure, NULL
1865  * @param client identification of the client
1866  */
1867 static void
1868 handle_client_disconnect (void *cls,
1869                           struct GNUNET_SERVER_Client * client)
1870 {
1871 }
1872
1873
1874 /**
1875  * Handle the channel a peer opens to us.
1876  *
1877  * @param cls The closure
1878  * @param channel The channel the peer wants to establish
1879  * @param initiator The peer's peer ID
1880  * @param port The port the channel is being established over
1881  * @param options Further options
1882  */
1883   static void *
1884 handle_inbound_channel (void *cls,
1885                         struct GNUNET_CADET_Channel *channel,
1886                         const struct GNUNET_PeerIdentity *initiator,
1887                         uint32_t port,
1888                         enum GNUNET_CADET_ChannelOption options)
1889 {
1890   struct PeerContext *peer_ctx;
1891   struct GNUNET_PeerIdentity peer;
1892
1893   peer = *initiator;
1894   LOG (GNUNET_ERROR_TYPE_DEBUG,
1895       "New channel was established to us (Peer %s).\n",
1896       GNUNET_i2s (&peer));
1897
1898   GNUNET_assert (NULL != channel);
1899
1900   // we might not even store the recv_channel
1901
1902   peer_ctx = get_peer_ctx (peer_map, &peer);
1903   // FIXME what do we do if a channel is established twice?
1904   //       overwrite? Clean old channel? ...?
1905   //if (NULL != peer_ctx->recv_channel)
1906   //{
1907   //  peer_ctx->recv_channel = channel;
1908   //}
1909   peer_ctx->recv_channel = channel;
1910
1911   peer_ctx->mq = NULL;
1912
1913   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, &peer, peer_ctx,
1914       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1915
1916   peer_is_live (peer_ctx);
1917
1918   return NULL; // TODO
1919 }
1920
1921
1922 /**
1923  * This is called when a remote peer destroys a channel.
1924  *
1925  * @param cls The closure
1926  * @param channel The channel being closed
1927  * @param channel_ctx The context associated with this channel
1928  */
1929   static void
1930 cleanup_channel (void *cls,
1931                 const struct GNUNET_CADET_Channel *channel,
1932                 void *channel_ctx)
1933 {
1934   struct GNUNET_PeerIdentity *peer;
1935   struct PeerContext *peer_ctx;
1936
1937   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1938       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1939        // Guess simply casting isn't the nicest way...
1940        // FIXME wait for cadet to change this function
1941   LOG (GNUNET_ERROR_TYPE_DEBUG, "Cleaning up channel to peer %s\n",
1942        GNUNET_i2s (peer));
1943
1944   if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
1945   {
1946     peer_ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
1947
1948     if (NULL == peer_ctx) /* It could have been removed by shutdown_task */
1949       return;
1950
1951     if (channel == peer_ctx->send_channel)
1952     { /* Peer probably went down */
1953       rem_from_list (&gossip_list, &gossip_list_size, peer);
1954       rem_from_list (&pending_pull_reply_list, &pending_pull_reply_list_size, peer);
1955
1956       /* Somwewhat {ab,re}use the iterator function */
1957       /* Cast to void is ok, because it's used as void in peer_remove_cb */
1958       (void) peer_remove_cb ((void *) channel, peer, peer_ctx);
1959     }
1960     else /* Other peer doesn't want to send us messages anymore */
1961       peer_ctx->recv_channel = NULL;
1962   }
1963 }
1964
1965
1966 /**
1967  * Actually start the service.
1968  */
1969   static void
1970 rps_start (struct GNUNET_SERVER_Handle *server)
1971 {
1972   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1973     {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1974       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1975     {&handle_client_seed,    NULL, GNUNET_MESSAGE_TYPE_RPS_CS_SEED, 0},
1976     {NULL, NULL, 0, 0}
1977   };
1978
1979   GNUNET_SERVER_add_handlers (server, handlers);
1980   GNUNET_SERVER_disconnect_notify (server,
1981                                    &handle_client_disconnect,
1982                                    NULL);
1983   LOG (GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1984
1985
1986   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1987   LOG (GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1988
1989   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1990                                                         &shutdown_task,
1991                                                         NULL);
1992 }
1993
1994
1995 /**
1996  * Process statistics requests.
1997  *
1998  * @param cls closure
1999  * @param server the initialized server
2000  * @param c configuration to use
2001  */
2002   static void
2003 run (void *cls,
2004      struct GNUNET_SERVER_Handle *server,
2005      const struct GNUNET_CONFIGURATION_Handle *c)
2006 {
2007   // TODO check what this does -- copied from gnunet-boss
2008   // - seems to work as expected
2009   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
2010   cfg = c;
2011
2012
2013   /* Get own ID */
2014   GNUNET_CRYPTO_get_peer_identity (cfg, &own_identity); // TODO check return value
2015   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
2016               "STARTING SERVICE (rps) for peer [%s]\n",
2017               GNUNET_i2s (&own_identity));
2018   #ifdef ENABLE_MALICIOUS
2019   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2020               "Malicious execution compiled in.\n");
2021   #endif /* ENABLE_MALICIOUS */
2022
2023
2024
2025   /* Get time interval from the configuration */
2026   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
2027                                                         "ROUNDINTERVAL",
2028                                                         &round_interval))
2029   {
2030     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
2031     GNUNET_SCHEDULER_shutdown ();
2032     return;
2033   }
2034
2035   /* Get initial size of sampler/gossip list from the configuration */
2036   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
2037                                                          "INITSIZE",
2038                                                          (long long unsigned int *) &sampler_size_est_need))
2039   {
2040     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
2041     GNUNET_SCHEDULER_shutdown ();
2042     return;
2043   }
2044   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", sampler_size_est_need);
2045
2046
2047   gossip_list = NULL;
2048
2049
2050   /* connect to NSE */
2051   nse = GNUNET_NSE_connect (cfg, nse_callback, NULL);
2052   // TODO check whether that was successful
2053   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
2054
2055
2056   alpha = 0.45;
2057   beta  = 0.45;
2058
2059   peer_map = GNUNET_CONTAINER_multipeermap_create (sampler_size_est_need, GNUNET_NO);
2060
2061
2062   /* Initialise cadet */
2063   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
2064     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        ,
2065       sizeof (struct GNUNET_MessageHeader)},
2066     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST,
2067       sizeof (struct GNUNET_MessageHeader)},
2068     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
2069     #if ENABLE_MALICIOUS
2070     {&handle_peer_act_malicious, GNUNET_MESSAGE_TYPE_RPS_ACT_MALICIOUS , 0},
2071     #endif /* ENABLE_MALICIOUS */
2072     {NULL, 0, 0}
2073   };
2074
2075   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
2076   cadet_handle = GNUNET_CADET_connect (cfg,
2077                                        cls,
2078                                        &handle_inbound_channel,
2079                                        &cleanup_channel,
2080                                        cadet_handlers,
2081                                        ports);
2082   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
2083
2084
2085   /* Initialise sampler */
2086   struct GNUNET_TIME_Relative half_round_interval;
2087   struct GNUNET_TIME_Relative  max_round_interval;
2088
2089   half_round_interval = GNUNET_TIME_relative_multiply (round_interval, .5);
2090   max_round_interval = GNUNET_TIME_relative_add (round_interval, half_round_interval);
2091
2092   prot_sampler =   RPS_sampler_init (sampler_size_est_need, max_round_interval);
2093   client_sampler = RPS_sampler_init (sampler_size_est_need, max_round_interval);
2094
2095   /* Initialise push and pull maps */
2096   push_list = NULL;
2097   push_list_size = 0;
2098   pull_list = NULL;
2099   pull_list_size = 0;
2100   pending_pull_reply_list = NULL;
2101   pending_pull_reply_list_size = 0;
2102
2103
2104   num_hist_update_tasks = 0;
2105
2106
2107   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
2108   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, NULL);
2109   // TODO send push/pull to each of those peers?
2110
2111
2112   rps_start (server);
2113 }
2114
2115
2116 /**
2117  * The main function for the rps service.
2118  *
2119  * @param argc number of arguments from the command line
2120  * @param argv command line arguments
2121  * @return 0 ok, 1 on error
2122  */
2123   int
2124 main (int argc, char *const *argv)
2125 {
2126   return (GNUNET_OK ==
2127           GNUNET_SERVICE_run (argc,
2128                               argv,
2129                               "rps",
2130                               GNUNET_SERVICE_OPTION_NONE,
2131                               &run, NULL)) ? 0 : 1;
2132 }
2133
2134 /* end of gnunet-service-rps.c */