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