cf3bd080e4fdfa5c001911b81df444aafaa52039
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      (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 take care that messages are not longer than 64k
42
43 // TODO check for overflows
44
45 // TODO align message structs
46
47 // (TODO api -- possibility of getting weak random peer immideately)
48
49 // TODO malicious peer
50
51 // TODO Change API to accept initialisation peers
52
53 // TODO Change API to accept good peers 'friends'
54
55 // TODO store peers somewhere
56
57 // TODO check that every id we get is valid - is it reachable?
58
59 // hist_size_init, hist_size_max
60
61 /**
62  * Our configuration.
63  */
64 static const struct GNUNET_CONFIGURATION_Handle *cfg;
65
66 /**
67  * Our own identity.
68  */
69 static struct GNUNET_PeerIdentity *own_identity;
70
71 /**
72  * Closure to the callback cadet calls on each peer it passes to us
73  */
74 struct init_peer_cls
75 {
76   /**
77    * The server handle to later listen to client requests
78    */
79   struct GNUNET_SERVER_Handle *server;
80
81   /**
82    * Counts how many peers cadet already passed to us
83    */
84   uint32_t i;
85 };
86
87
88   struct GNUNET_PeerIdentity *
89 get_rand_peer (const struct GNUNET_PeerIdentity *peer_list, unsigned int size);
90
91
92 /***********************************************************************
93  * Housekeeping with peers
94 ***********************************************************************/
95
96 /**
97  * Struct used to store the context of a connected client.
98  */
99 struct client_ctx
100 {
101   /**
102    * The message queue to communicate with the client.
103    */
104   struct GNUNET_MQ_Handle *mq;
105 };
106
107 /**
108  * Used to keep track in what lists single peerIDs are.
109  */
110 enum in_list_flag // probably unneeded
111 {
112   in_other_sampler_list = 0x1,
113   in_other_gossip_list  = 0x2, // unneeded?
114   in_own_sampler_list   = 0x4,
115   in_own_gossip_list    = 0x8 // unneeded?
116 };
117
118 /**
119  * Struct used to keep track of other peer's status
120  *
121  * This is stored in a multipeermap.
122  */
123 struct peer_context
124 {
125   /**
126    * In own gossip/sampler list, in other's gossip/sampler list
127    */
128   uint32_t in_flags; // unneeded?
129
130   /**
131    * Message queue open to client
132    */
133   struct GNUNET_MQ_Handle *mq;
134
135   /**
136    * Channel open to client.
137    */
138   struct GNUNET_CADET_Channel *to_channel;
139
140   /**
141    * Channel open from client.
142    */
143   struct GNUNET_CADET_Channel *from_channel; // unneeded
144
145   /**
146    * This is pobably followed by 'statistical' data (when we first saw
147    * him, how did we get his ID, how many pushes (in a timeinterval),
148    * ...)
149    */
150 };
151
152 /***********************************************************************
153  * /Housekeeping with peers
154 ***********************************************************************/
155
156 /***********************************************************************
157  * Globals
158 ***********************************************************************/
159
160 /**
161  * Set of all peers to keep track of them.
162  */
163 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
164
165
166 /**
167  * The gossiped list of peers.
168  */
169 static struct GNUNET_PeerIdentity *gossip_list;
170
171 /**
172  * Size of the gossiped list
173  */
174 static unsigned int gossip_list_size;
175
176
177 /**
178  * The estimated size of the network.
179  *
180  * Influenced by the stdev.
181  */
182 static unsigned int est_size;
183 //size_t est_size;
184
185
186 /**
187  * Percentage of total peer number in the gossip list
188  * to send random PUSHes to
189  *
190  * TODO do not read from configuration
191  */
192 static float alpha;
193
194 /**
195  * Percentage of total peer number in the gossip list
196  * to send random PULLs to
197  *
198  * TODO do not read from configuration
199  */
200 static float beta;
201
202 /**
203  * The percentage gamma of history updates.
204  * Simply 1 - alpha - beta
205  */
206
207
208 /**
209  * Identifier for the main task that runs periodically.
210  */
211 static struct GNUNET_SCHEDULER_Task * do_round_task;
212
213 /**
214  * Time inverval the do_round task runs in.
215  */
216 static struct GNUNET_TIME_Relative round_interval;
217
218
219
220 /**
221  * List to store peers received through pushes temporary.
222  *
223  * TODO -> multipeermap
224  */
225 static struct GNUNET_PeerIdentity *push_list;
226
227 /**
228  * Size of the push_list;
229  */
230 static unsigned int push_list_size;
231 //size_t push_list_size;
232
233 /**
234  * List to store peers received through pulls temporary.
235  *
236  * TODO -> multipeermap
237  */
238 static struct GNUNET_PeerIdentity *pull_list;
239
240 /**
241  * Size of the pull_list;
242  */
243 static unsigned int pull_list_size;
244 //size_t pull_list_size;
245
246
247 /**
248  * Handler to NSE.
249  */
250 static struct GNUNET_NSE_Handle *nse;
251
252 /**
253  * Handler to CADET.
254  */
255 static struct GNUNET_CADET_Handle *cadet_handle;
256
257 /**
258  * Global counter
259  */
260 uint64_t g_i = 0;
261
262
263 /**
264  * Request counter.
265  *
266  * Only needed in the beginning to check how many of the 64 deltas
267  * we already have
268  */
269 static unsigned int req_counter;
270
271 /**
272  * Time of the last request we received.
273  *
274  * Used to compute the expected request rate.
275  */
276 static struct GNUNET_TIME_Absolute last_request;
277
278 /**
279  * Size of #request_deltas.
280  */
281 #define REQUEST_DELTAS_SIZE 64
282 static unsigned int request_deltas_size = REQUEST_DELTAS_SIZE;
283
284 /**
285  * Last 64 deltas between requests
286  */
287 static struct GNUNET_TIME_Relative request_deltas[REQUEST_DELTAS_SIZE];
288
289 /**
290  * The prediction of the rate of requests
291  */
292 static struct GNUNET_TIME_Relative  request_rate;
293
294
295 /***********************************************************************
296  * /Globals
297 ***********************************************************************/
298
299
300 /***********************************************************************
301  * Util functions
302 ***********************************************************************/
303
304 /**
305  * Check if peer is already in peer array.
306  */
307   int
308 in_arr (const struct GNUNET_PeerIdentity *array,
309         unsigned int arr_size,
310         const struct GNUNET_PeerIdentity *peer)
311 {
312   GNUNET_assert (NULL != peer);
313
314   if (0 == arr_size)
315     return GNUNET_NO;
316
317   GNUNET_assert (NULL != array);
318
319   unsigned int i;
320
321   i = 0;
322   while (0 != GNUNET_CRYPTO_cmp_peer_identity (&array[i], peer) &&
323          i < arr_size)
324     i++;
325
326   if (i == arr_size)
327     return GNUNET_NO;
328   else
329     return GNUNET_YES;
330 }
331
332
333 /**
334  * Get random peer from the gossip list.
335  */
336   struct GNUNET_PeerIdentity *
337 get_rand_peer(const struct GNUNET_PeerIdentity *peer_list, unsigned int list_size)
338 {
339   uint64_t r_index;
340   struct GNUNET_PeerIdentity *peer;
341
342   peer = GNUNET_new(struct GNUNET_PeerIdentity);
343   // FIXME if we have only NULL in gossip list this will block
344   // but then we might have a problem nevertheless
345
346   do
347   {
348
349     /**;
350      * Choose the r_index of the peer we want to return
351      * at random from the interval of the gossip list
352      */
353     r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
354                                      list_size);
355
356     *peer = peer_list[r_index];
357   } while (NULL == peer);
358
359   return peer;
360 }
361
362
363 /**
364  * Get the context of a peer. If not existing, create.
365  */
366   struct peer_context *
367 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
368 {
369   struct peer_context *ctx;
370
371   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, peer))
372   {
373     ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, peer);
374   }
375   else
376   {
377     ctx = GNUNET_new (struct peer_context);
378     ctx->in_flags = 0;
379     ctx->mq = NULL;
380     ctx->to_channel = NULL;
381     ctx->from_channel = NULL;
382     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
383   }
384   return ctx;
385 }
386
387
388 /**
389  * Get the channel of a peer. If not existing, create.
390  */
391   struct GNUNET_CADET_Channel *
392 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
393 {
394   struct peer_context *ctx;
395
396   ctx = get_peer_ctx (peer_map, peer);
397   if (NULL == ctx->to_channel)
398   {
399     ctx->to_channel = GNUNET_CADET_channel_create (cadet_handle, NULL, peer,
400                                                    GNUNET_RPS_CADET_PORT,
401                                                    GNUNET_CADET_OPTION_RELIABLE);
402     // do I have to explicitly put it in the peer_map?
403     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer, ctx,
404                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
405   }
406   return ctx->to_channel;
407 }
408
409
410 /**
411  * Get the message queue of a specific peer.
412  *
413  * If we already have a message queue open to this client,
414  * simply return it, otherways create one.
415  */
416   struct GNUNET_MQ_Handle *
417 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer_id)
418 {
419   struct peer_context *ctx;
420
421   ctx = get_peer_ctx (peer_map, peer_id);
422   if (NULL == ctx->mq)
423   {
424     (void) get_channel (peer_map, peer_id);
425     ctx->mq = GNUNET_CADET_mq_create (ctx->to_channel);
426     //do I have to explicitly put it in the peer_map?
427     (void) GNUNET_CONTAINER_multipeermap_put (peer_map, peer_id, ctx,
428                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
429   }
430   return ctx->mq;
431 }
432
433
434 /**
435  * Sum all time relatives of an array.
436   */
437   struct GNUNET_TIME_Relative
438 T_relative_sum (const struct GNUNET_TIME_Relative *rel_array, uint64_t arr_size)
439 {
440   struct GNUNET_TIME_Relative sum;
441   uint64_t i;
442
443   sum = GNUNET_TIME_UNIT_ZERO;
444   for ( i = 0 ; i < arr_size ; i++ )
445   {
446     sum = GNUNET_TIME_relative_add (sum, rel_array[i]);
447   }
448   return sum;
449 }
450
451
452 /**
453  * Compute the average of given time relatives.
454  */
455   struct GNUNET_TIME_Relative
456 T_relative_avg (const struct GNUNET_TIME_Relative *rel_array, uint64_t arr_size)
457 {
458   return GNUNET_TIME_relative_divide (T_relative_sum (rel_array, arr_size), arr_size); // FIXME find a way to devide that by arr_size
459 }
460
461
462 /***********************************************************************
463  * /Util functions
464 ***********************************************************************/
465
466 /**
467  * Function called by NSE.
468  *
469  * Updates sizes of sampler list and gossip list and adapt those lists
470  * accordingly.
471  */
472   void
473 nse_callback(void *cls, struct GNUNET_TIME_Absolute timestamp, double logestimate, double std_dev)
474 {
475   double estimate;
476   unsigned int old_est;
477   //double scale; // TODO this might go gloabal/config
478
479   old_est = est_size;
480
481   LOG (GNUNET_ERROR_TYPE_DEBUG,
482       "Received a ns estimate - logest: %f, std_dev: %f (old_est: %f)\n",
483       logestimate, std_dev, old_est);
484   //scale = .01;
485   estimate = GNUNET_NSE_log_estimate_to_n (logestimate);
486   // GNUNET_NSE_log_estimate_to_n (logestimate);
487   estimate = pow (estimate, 1./3);
488   // TODO add if std_dev is a number
489   // estimate += (std_dev * scale);
490   if ( 0 < estimate ) {
491     LOG (GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
492     est_size = estimate;
493   } else
494     LOG (GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
495
496   /* If the NSE has changed adapt the lists accordingly */
497   // TODO respect the request rate, min, max
498   if (old_est > est_size*4)
499   { /* Shrinking */
500     RPS_sampler_resize (old_est/2);
501   }
502   else if (old_est < est_size)
503   { /* Growing */
504     if (est_size < old_est*2)
505       RPS_sampler_resize (old_est*2);
506     else
507       RPS_sampler_resize (est_size);
508   }
509 }
510
511 /**
512  * Handle RPS request from the client.
513  *
514  * @param cls closure
515  * @param client identification of the client
516  * @param message the actual message
517  */
518 static void
519 // TODO rename
520 handle_cs_request (void *cls,
521             struct GNUNET_SERVER_Client *client,
522             const struct GNUNET_MessageHeader *message)
523 {
524   LOG(GNUNET_ERROR_TYPE_DEBUG, "Client requested (a) random peer(s).\n");
525
526   struct GNUNET_RPS_CS_RequestMessage *msg;
527   //unsigned int n_arr[sampler_list->size];// =
528     //GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
529   //struct GNUNET_MQ_Handle *mq;
530   struct client_ctx *cli_ctx;
531   struct GNUNET_MQ_Envelope *ev;
532   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
533   uint64_t num_peers;
534   const struct GNUNET_PeerIdentity *peers;
535   //uint64_t i;
536
537
538   /* Estimate request rate */
539   if (request_deltas_size > req_counter)
540     req_counter++;
541   if ( 1 < req_counter)
542   {
543     /* Shift last request deltas to the right */
544     memcpy (&request_deltas[1],
545         request_deltas,
546         (req_counter - 1) * sizeof (struct GNUNET_TIME_Relative));
547     /* Add current delta to beginning */
548     request_deltas[0] = GNUNET_TIME_absolute_get_difference (last_request,
549         GNUNET_TIME_absolute_get ());
550     request_rate = T_relative_avg (request_deltas, req_counter);
551   }
552   last_request = GNUNET_TIME_absolute_get();
553   // TODO resize the size of the extended_samplers
554
555
556   // TODO check message size
557   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
558   cli_ctx = GNUNET_SERVER_client_get_user_context (client, struct client_ctx);
559   if ( NULL == cli_ctx ) {
560     cli_ctx = GNUNET_new(struct client_ctx);
561     cli_ctx->mq = GNUNET_MQ_queue_for_server_client (client);
562     GNUNET_SERVER_client_set_user_context (client, cli_ctx);
563   }
564   
565   // How many peers do we give back?
566   // Wait until we have enough random peers?
567
568   num_peers = GNUNET_ntohll (msg->num_peers);
569
570   ev = GNUNET_MQ_msg_extra (out_msg,
571                             num_peers * sizeof (struct GNUNET_PeerIdentity),
572                             GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
573   out_msg->num_peers = msg->num_peers; // No conversion between network and network order
574
575   //&out_msg[1] = RPS_sampler_get_n_rand_peers (num_peers);
576   peers = RPS_sampler_get_n_rand_peers (num_peers);
577   memcpy(&out_msg[1],
578       peers,
579       num_peers * sizeof (struct GNUNET_PeerIdentity));
580   
581   GNUNET_MQ_send (cli_ctx->mq, ev);
582   //GNUNET_MQ_destroy(mq);
583
584   GNUNET_SERVER_receive_done (client,
585                               GNUNET_OK);
586 }
587
588 /**
589  * Handle a PUSH message from another peer.
590  *
591  * Check the proof of work and store the PeerID
592  * in the temporary list for pushed PeerIDs.
593  *
594  * @param cls Closure
595  * @param channel The channel the PUSH was received over
596  * @param channel_ctx The context associated with this channel
597  * @param msg The message header
598  */
599 static int
600 handle_peer_push (void *cls,
601     struct GNUNET_CADET_Channel *channel,
602     void **channel_ctx,
603     const struct GNUNET_MessageHeader *msg)
604 {
605   const struct GNUNET_PeerIdentity *peer;
606
607   // (check the proof of work) 
608   
609   // TODO accept empty message
610   if (ntohs(msg->size) != sizeof (struct GNUNET_RPS_P2P_PushMessage))
611   {
612     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
613     return GNUNET_SYSERR;
614   }
615
616   peer = (const struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
617   // FIXME wait for cadet to change this function
618   LOG (GNUNET_ERROR_TYPE_DEBUG, "PUSH received (%s)\n", GNUNET_i2s (peer));
619   
620   /* Add the sending peer to the push_list */
621   if (GNUNET_NO == in_arr (push_list, pull_list_size, peer))
622     GNUNET_array_append (push_list, push_list_size, *peer);
623
624   return GNUNET_OK;
625 }
626
627 /**
628  * Handle PULL REQUEST request message from another peer.
629  *
630  * Reply with the gossip list of PeerIDs.
631  *
632  * @param cls Closure
633  * @param channel The channel the PUSH was received over
634  * @param channel_ctx The context associated with this channel
635  * @param msg The message header
636  */
637 static int
638 handle_peer_pull_request (void *cls,
639     struct GNUNET_CADET_Channel *channel,
640     void **channel_ctx,
641     const struct GNUNET_MessageHeader *msg)
642 {
643   struct GNUNET_PeerIdentity *peer;
644   struct GNUNET_MQ_Handle *mq;
645   struct GNUNET_MQ_Envelope *ev;
646   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
647
648   // assert that msg->size is 0
649
650   // TODO accept empty message
651   if (ntohs(msg->size) != sizeof (struct GNUNET_RPS_P2P_PullRequestMessage))
652   {
653     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
654     return GNUNET_SYSERR;
655   }
656
657   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (channel, GNUNET_CADET_OPTION_PEER);
658   // FIXME wait for cadet to change this function
659   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REQUEST from peer %s received\n", GNUNET_i2s (peer));
660
661   mq = get_mq (peer_map, peer);
662
663   ev = GNUNET_MQ_msg_extra (out_msg,
664                            gossip_list_size * sizeof (struct GNUNET_PeerIdentity),
665                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
666   out_msg->num_peers = GNUNET_htonll (gossip_list_size);
667   memcpy (&out_msg[1], gossip_list,
668          gossip_list_size * sizeof (struct GNUNET_PeerIdentity));
669
670   GNUNET_MQ_send (mq, ev);
671
672   return GNUNET_OK;
673 }
674
675 /**
676  * Handle PULL REPLY message from another peer.
677  *
678  * Check whether we sent a corresponding request and
679  * whether this reply is the first one.
680  *
681  * @param cls Closure
682  * @param channel The channel the PUSH was received over
683  * @param channel_ctx The context associated with this channel
684  * @param msg The message header
685  */
686 static int
687 handle_peer_pull_reply (void *cls,
688     struct GNUNET_CADET_Channel *channel,
689     void **channel_ctx,
690     const struct GNUNET_MessageHeader *msg)
691 {
692   LOG (GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
693
694   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
695   struct GNUNET_PeerIdentity *peers;
696   uint64_t i;
697
698   if (sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) < ntohs (msg->size))
699   {
700     GNUNET_break_op (0); // At the moment our own implementation seems to break that.
701     return GNUNET_SYSERR;
702   }
703   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
704   if (ntohs (msg->size) - sizeof (struct GNUNET_RPS_P2P_PullReplyMessage) / sizeof (struct GNUNET_PeerIdentity) != GNUNET_ntohll (in_msg->num_peers))
705   {
706     GNUNET_break_op (0);
707     return GNUNET_SYSERR;
708   }
709
710   // TODO check that we sent a request and that it is the first reply
711
712   peers = (struct GNUNET_PeerIdentity *) &msg[1];
713   for ( i = 0 ; i < GNUNET_ntohll (in_msg->num_peers) ; i++ )
714   {
715     if (GNUNET_NO == in_arr(pull_list, pull_list_size, &peers[i]))
716       GNUNET_array_append (pull_list, pull_list_size, peers[i]);
717   }
718
719   // TODO check that id is valid - whether it is reachable
720
721   return GNUNET_OK;
722 }
723
724
725 /**
726  * Send out PUSHes and PULLs.
727  *
728  * This is executed regylary.
729  */
730 static void
731 do_round (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
732 {
733   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
734
735   uint64_t i;
736   //unsigned int *n_arr;
737   unsigned int n_peers; /* Number of peers we send pushes/pulls to */
738   struct GNUNET_RPS_P2P_PushMessage        *push_msg;
739   struct GNUNET_RPS_P2P_PullRequestMessage *pull_msg; // FIXME Send empty message
740   struct GNUNET_MQ_Envelope *ev;
741   const struct GNUNET_PeerIdentity *peer;
742   struct GNUNET_MQ_Handle *mq;
743
744   // TODO print lists, ...
745   // TODO randomise and spread calls herein over time
746
747
748   /* Would it make sense to have one shuffeled gossip list and then
749    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
750    * use the rest to update sampler?
751    * in essence get random peers with consumption */
752
753   /* Send PUSHes */
754   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) gossip_list_size);
755   n_peers = round (alpha * gossip_list_size);
756   if (0 == n_peers)
757     n_peers = 1;
758   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to send pushes to %u (%f * %u) peers.\n",
759       n_peers, alpha, gossip_list_size);
760   for ( i = 0 ; i < n_peers ; i++ )
761   {
762     peer = get_rand_peer (gossip_list, gossip_list_size);
763     if (own_identity != peer)
764     { // FIXME if this fails schedule/loop this for later
765       LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PUSH to peer %s of gossiped list.\n", GNUNET_i2s (peer));
766
767       ev = GNUNET_MQ_msg (push_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
768       push_msg = NULL;
769       // FIXME sometimes it returns a pointer to a freed mq
770       mq = get_mq (peer_map, peer);
771       GNUNET_MQ_send (mq, ev);
772     }
773   }
774
775
776   /* Send PULL requests */
777   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
778   n_peers = round (beta * gossip_list_size);
779   if (0 == n_peers)
780     n_peers = 1;
781   LOG (GNUNET_ERROR_TYPE_DEBUG, "Going to send pulls to %u (%f * %u) peers.\n",
782       n_peers, beta, gossip_list_size);
783   for ( i = 0 ; i < n_peers ; i++ )
784   {
785     peer = get_rand_peer (gossip_list, gossip_list_size);
786     if (own_identity != peer)
787     { // FIXME if this fails schedule/loop this for later
788       LOG (GNUNET_ERROR_TYPE_DEBUG, "Sending PULL request to peer %s of gossiped list.\n", GNUNET_i2s (peer));
789
790       ev = GNUNET_MQ_msg (pull_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
791       pull_msg = NULL;
792       mq = get_mq (peer_map, peer);
793       GNUNET_MQ_send (mq, ev);
794     }
795   }
796
797
798   /* Update gossip list */
799   uint64_t r_index;
800
801   if ( push_list_size <= alpha * gossip_list_size &&
802        push_list_size != 0 &&
803        pull_list_size != 0 )
804   {
805     LOG(GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list. ()\n");
806
807     uint64_t first_border;
808     uint64_t second_border;
809     
810     GNUNET_array_grow(gossip_list, gossip_list_size, est_size);
811
812     first_border = round(alpha * gossip_list_size);
813     for ( i = 0 ; i < first_border ; i++ )
814     { // TODO use RPS_sampler_get_n_rand_peers
815       /* Update gossip list with peers received through PUSHes */
816       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
817                                        push_list_size);
818       gossip_list[i] = push_list[r_index];
819       // TODO change the in_flags accordingly
820     }
821
822     second_border = first_border + round(beta * gossip_list_size);
823     for ( i = first_border ; i < second_border ; i++ )
824     {
825       /* Update gossip list with peers received through PULLs */
826       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
827                                        pull_list_size);
828       gossip_list[i] = pull_list[r_index];
829       // TODO change the in_flags accordingly
830     }
831
832     for ( i = second_border ; i < gossip_list_size ; i++ )
833     {
834       /* Update gossip list with peers from history */
835       peer = RPS_sampler_get_n_rand_peers (1),
836       gossip_list[i] = *peer;
837       // TODO change the in_flags accordingly
838     }
839
840   }
841   else
842   {
843     LOG(GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list. ()\n");
844   }
845   // TODO independent of that also get some peers from CADET_get_peers()?
846
847
848   /* Update samplers */
849
850   for ( i = 0 ; i < push_list_size ; i++ )
851   {
852     RPS_sampler_update_list (&push_list[i]);
853     // TODO set in_flag?
854   }
855
856   for ( i = 0 ; i < pull_list_size ; i++ )
857   {
858     RPS_sampler_update_list (&pull_list[i]);
859     // TODO set in_flag?
860   }
861
862
863   /* Empty push/pull lists */
864   GNUNET_array_grow (push_list, push_list_size, 0);
865   GNUNET_array_grow (pull_list, pull_list_size, 0);
866
867   struct GNUNET_TIME_Relative time_next_round;
868   struct GNUNET_TIME_Relative half_round_interval;
869   unsigned int rand_delay;
870
871   /* Compute random time value between .5 * round_interval and 1.5 *round_interval */
872   half_round_interval = GNUNET_TIME_relative_divide (round_interval, 2);
873   do
874   {
875   /*
876    * Compute random value between (0 and 1) * round_interval
877    * via multiplying round_interval with a 'fraction' (0 to value)/value
878    */
879   rand_delay = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT_MAX/10);
880   time_next_round = GNUNET_TIME_relative_multiply (round_interval,  rand_delay);
881   time_next_round = GNUNET_TIME_relative_divide   (time_next_round, UINT_MAX/10);
882   time_next_round = GNUNET_TIME_relative_add      (time_next_round, half_round_interval);
883   } while (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == time_next_round.rel_value_us);
884
885   /* Schedule next round */
886   do_round_task = GNUNET_SCHEDULER_add_delayed (round_interval, &do_round, NULL);
887   LOG (GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
888 }
889
890
891 /**
892  * Open a connection to given peer and store channel and mq.
893  */
894   void
895 insertCB (void *cls, const struct GNUNET_PeerIdentity *id)
896 {
897   // We open a channel to be notified when this peer goes down.
898   (void) get_channel (peer_map, id);
899 }
900
901
902 /**
903  * Close the connection to given peer and delete channel and mq.
904  */
905   void
906 removeCB (void *cls, const struct GNUNET_PeerIdentity *id)
907 {
908   size_t s;
909   struct peer_context *ctx;
910
911   s = RPS_sampler_count_id (id);
912   if ( 1 >= s )
913   {
914     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (peer_map, id))
915     {
916       ctx = GNUNET_CONTAINER_multipeermap_get (peer_map, id);
917       if (NULL != ctx->to_channel)
918       {
919         if (NULL != ctx->mq)
920         {
921           GNUNET_MQ_destroy (ctx->mq);
922         }
923         // may already be freed at shutdown of cadet
924         //GNUNET_CADET_channel_destroy (ctx->to_channel);
925       }
926       // TODO cleanup peer
927       (void) GNUNET_CONTAINER_multipeermap_remove_all (peer_map, id);
928     }
929   }
930 }
931
932 static void
933 rps_start (struct GNUNET_SERVER_Handle *server);
934
935 /**
936  * This is called from GNUNET_CADET_get_peers().
937  *
938  * It is called on every peer(ID) that cadet somehow has contact with.
939  * We use those to initialise the sampler.
940  */
941 void
942 init_peer_cb (void *cls,
943               const struct GNUNET_PeerIdentity *peer,
944               int tunnel, // "Do we have a tunnel towards this peer?"
945               unsigned int n_paths, // "Number of known paths towards this peer"
946               unsigned int best_path) // "How long is the best path?
947                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
948 {
949   struct init_peer_cls *ipc;
950
951   ipc = (struct init_peer_cls *) cls;
952   if ( NULL != peer )
953   {
954     LOG (GNUNET_ERROR_TYPE_DEBUG,
955         "Got %" PRIX32 ". peer %s (at %p) from CADET (gossip_list_size: %u)\n",
956         ipc->i, GNUNET_i2s (peer), peer, gossip_list_size);
957     RPS_sampler_update_list (peer);
958     (void) get_peer_ctx (peer_map, peer); // unneeded? -> insertCB
959
960     if (ipc->i < gossip_list_size)
961     {
962       gossip_list[ipc->i] = *peer; // FIXME sometimes we're writing to invalid space here
963                                    // not sure whether fixed
964       ipc->i++;
965     }
966
967     // send push/pull to each of those peers?
968   }
969   else
970   {
971     if (ipc->i < gossip_list_size)
972     {
973       memcpy(&gossip_list[ipc->i],
974           RPS_sampler_get_n_rand_peers (1),
975           (gossip_list_size - ipc->i) * sizeof(struct GNUNET_PeerIdentity));
976     }
977     rps_start (ipc->server);
978     GNUNET_free (ipc);
979   }
980 }
981
982
983 /**
984  * Task run during shutdown.
985  *
986  * @param cls unused
987  * @param tc unused
988  */
989 static void
990 shutdown_task (void *cls,
991                const struct GNUNET_SCHEDULER_TaskContext *tc)
992 {
993   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
994
995   if ( NULL != do_round_task )
996   {
997     GNUNET_SCHEDULER_cancel (do_round_task);
998     do_round_task = NULL;
999   }
1000
1001   GNUNET_NSE_disconnect (nse);
1002   GNUNET_CADET_disconnect (cadet_handle);
1003   GNUNET_free (own_identity);
1004   RPS_sampler_destroy ();
1005   GNUNET_array_grow (request_deltas, request_deltas_size, 0);
1006   GNUNET_array_grow (gossip_list, gossip_list_size, 0);
1007   GNUNET_array_grow (push_list, push_list_size, 0);
1008   GNUNET_array_grow (pull_list, pull_list_size, 0);
1009 }
1010
1011
1012 /**
1013  * A client disconnected.  Remove all of its data structure entries.
1014  *
1015  * @param cls closure, NULL
1016  * @param client identification of the client
1017  */
1018 static void
1019 handle_client_disconnect (void *cls,
1020                           struct GNUNET_SERVER_Client * client)
1021 {
1022 }
1023
1024 /**
1025  * Handle the channel a peer opens to us.
1026  *
1027  * @param cls The closure
1028  * @param channel The channel the peer wants to establish
1029  * @param initiator The peer's peer ID
1030  * @param port The port the channel is being established over
1031  * @param options Further options
1032  */
1033   static void *
1034 handle_inbound_channel (void *cls,
1035                         struct GNUNET_CADET_Channel *channel,
1036                         const struct GNUNET_PeerIdentity *initiator,
1037                         uint32_t port,
1038                         enum GNUNET_CADET_ChannelOption options)
1039 {
1040   struct peer_context *ctx;
1041
1042   LOG(GNUNET_ERROR_TYPE_DEBUG, "New channel was established to us (Peer %s).\n", GNUNET_i2s(initiator));
1043
1044   GNUNET_assert( NULL != channel );
1045
1046   // we might not even store the from_channel
1047
1048   ctx = get_peer_ctx(peer_map, initiator);
1049   if (NULL != ctx->from_channel)
1050   {
1051     ctx->from_channel = channel;
1052   }
1053
1054   // FIXME there might already be an established channel
1055
1056   //ctx->in_flags = in_other_gossip_list;
1057   ctx->mq = NULL; // TODO create mq?
1058
1059   (void) GNUNET_CONTAINER_multipeermap_put (peer_map, initiator, ctx,
1060       GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
1061   return NULL; // TODO
1062 }
1063
1064 /**
1065  * This is called when a remote peer destroys a channel.
1066  *
1067  * @param cls The closure
1068  * @param channel The channel being closed
1069  * @param channel_ctx The context associated with this channel
1070  */
1071 static void
1072 cleanup_channel(void *cls,
1073                 const struct GNUNET_CADET_Channel *channel,
1074                 void *channel_ctx)
1075 {
1076   struct GNUNET_PeerIdentity *peer;
1077   LOG(GNUNET_ERROR_TYPE_DEBUG, "Channel to remote peer was destroyed.\n");
1078
1079   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info (
1080       (struct GNUNET_CADET_Channel *) channel, GNUNET_CADET_OPTION_PEER);
1081        // Guess simply casting isn't the nicest way...
1082        // FIXME wait for cadet to change this function
1083   RPS_sampler_reinitialise_by_value (peer);
1084 }
1085
1086 /**
1087  * Actually start the service.
1088  */
1089 static void
1090 rps_start (struct GNUNET_SERVER_Handle *server)
1091 {
1092   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1093     {&handle_cs_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST,
1094       sizeof (struct GNUNET_RPS_CS_RequestMessage)},
1095     {NULL, NULL, 0, 0}
1096   };
1097
1098   GNUNET_SERVER_add_handlers (server, handlers);
1099   GNUNET_SERVER_disconnect_notify (server,
1100                                    &handle_client_disconnect,
1101                                    NULL);
1102   LOG(GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1103
1104
1105   do_round_task = GNUNET_SCHEDULER_add_now (&do_round, NULL);
1106   LOG(GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1107
1108   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1109                                 &shutdown_task,
1110                                 NULL);
1111 }
1112
1113
1114 /**
1115  * Process statistics requests.
1116  *
1117  * @param cls closure
1118  * @param server the initialized server
1119  * @param c configuration to use
1120  */
1121 static void
1122 run (void *cls,
1123      struct GNUNET_SERVER_Handle *server,
1124      const struct GNUNET_CONFIGURATION_Handle *c)
1125 {
1126   // TODO check what this does -- copied from gnunet-boss
1127   // - seems to work as expected
1128   GNUNET_log_setup ("rps", GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG), NULL);
1129
1130   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS started\n");
1131
1132   struct init_peer_cls *ipc;
1133
1134   cfg = c;
1135
1136
1137   /* Get own ID */
1138   own_identity = GNUNET_new (struct GNUNET_PeerIdentity);
1139   GNUNET_CRYPTO_get_peer_identity (cfg, own_identity); // TODO check return value
1140   GNUNET_assert (NULL != own_identity);
1141   LOG (GNUNET_ERROR_TYPE_DEBUG, "Own identity is %s (at %p).\n", GNUNET_i2s(own_identity), own_identity);
1142
1143
1144   /* Get time interval from the configuration */
1145   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1146                                                         "ROUNDINTERVAL",
1147                                                         &round_interval))
1148   {
1149     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1150     GNUNET_SCHEDULER_shutdown();
1151     return;
1152   }
1153
1154   /* Get initial size of sampler/gossip list from the configuration */
1155   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1156                                                          "INITSIZE",
1157                                                          (long long unsigned int *) &est_size))
1158   {
1159     LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1160     GNUNET_SCHEDULER_shutdown ();
1161     return;
1162   }
1163   LOG (GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", est_size);
1164
1165   //gossip_list_size = est_size; // TODO rename est_size
1166
1167   gossip_list = NULL;
1168   GNUNET_array_grow (gossip_list, gossip_list_size, est_size);
1169
1170
1171   /* connect to NSE */
1172   nse = GNUNET_NSE_connect(cfg, nse_callback, NULL);
1173   // TODO check whether that was successful
1174   // TODO disconnect on shutdown
1175   LOG(GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1176
1177
1178   alpha = 0.45;
1179   beta  = 0.45;
1180   // TODO initialise thresholds - ?
1181
1182   /* Get alpha from the configuration */
1183   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1184                                                          "ALPHA",
1185                                                          &alpha))
1186   {
1187     LOG(GNUNET_ERROR_TYPE_DEBUG, "No ALPHA specified in the config\n");
1188   }
1189   LOG(GNUNET_ERROR_TYPE_DEBUG, "ALPHA is %f\n", alpha);
1190  
1191   /* Get beta from the configuration */
1192   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1193                                                          "BETA",
1194                                                          &beta))
1195   {
1196     LOG (GNUNET_ERROR_TYPE_DEBUG, "No BETA specified in the config\n");
1197   }
1198   LOG (GNUNET_ERROR_TYPE_DEBUG, "BETA is %f\n", beta);
1199
1200   // TODO check that alpha + beta < 1
1201
1202   peer_map = GNUNET_CONTAINER_multipeermap_create (est_size, GNUNET_NO);
1203
1204
1205   /* Initialise cadet */
1206   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1207     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        , 0},
1208     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST, 0},
1209     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1210     {NULL, 0, 0}
1211   };
1212
1213   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1214   cadet_handle = GNUNET_CADET_connect (cfg,
1215                                     cls,
1216                                     &handle_inbound_channel,
1217                                     &cleanup_channel,
1218                                     cadet_handlers,
1219                                     ports);
1220   LOG (GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1221
1222
1223   /* Initialise sampler */
1224   RPS_sampler_init (est_size, own_identity, insertCB, NULL, removeCB, NULL);
1225
1226   /* Initialise push and pull maps */
1227   push_list = NULL;
1228   push_list_size = 0;
1229   pull_list = NULL;
1230   pull_list_size = 0;
1231
1232
1233   ipc = GNUNET_new (struct init_peer_cls);
1234   ipc->server = server;
1235   ipc->i = 0;
1236   LOG (GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1237   GNUNET_CADET_get_peers (cadet_handle, &init_peer_cb, ipc);
1238
1239   // TODO send push/pull to each of those peers?
1240 }
1241
1242
1243 /**
1244  * The main function for the rps service.
1245  *
1246  * @param argc number of arguments from the command line
1247  * @param argv command line arguments
1248  * @return 0 ok, 1 on error
1249  */
1250 int
1251 main (int argc, char *const *argv)
1252 {
1253   return (GNUNET_OK ==
1254           GNUNET_SERVICE_run (argc,
1255                               argv,
1256                               "rps",
1257                               GNUNET_SERVICE_OPTION_NONE,
1258                               &run, NULL)) ? 0 : 1;
1259 }
1260
1261 /* end of gnunet-service-rps.c */