making GNUNET_SCHEDULER_cancel() perform in O(1) instead of O(n) to help or even...
[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 <math.h>
33 #include <inttypes.h>
34
35 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
36
37 // TODO modify @brief in every file
38
39 // TODO take care that messages are not longer than 64k
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 Change API to accept initialisation peers
50
51 /**
52  * Our configuration.
53  */
54 static const struct GNUNET_CONFIGURATION_Handle *cfg;
55
56 /**
57  * Our own identity.
58  */
59 struct GNUNET_PeerIdentity *own_identity;
60
61
62   struct GNUNET_PeerIdentity *
63 get_rand_peer(struct GNUNET_PeerIdentity *peer_list, unsigned int size);
64
65 /***********************************************************************
66  * Sampler
67  *
68  * WARNING: This section needs to be reviewed regarding the use of
69  * functions providing (pseudo)randomness!
70 ***********************************************************************/
71
72 // TODO care about invalid input of the caller (size 0 or less...)
73
74 // It might be interesting to formulate this independent of PeerIDs.
75
76 /**
77  * Callback that is called when a new PeerID is inserted into a sampler.
78  *
79  * @param cls the closure given alongside this function.
80  * @param id the PeerID that is inserted
81  * @param hash the hash the sampler produced of the PeerID
82  */
83 typedef void (* SAMPLER_insertCB) (void *cls,
84     const struct GNUNET_PeerIdentity *id,
85     struct GNUNET_HashCode hash);
86
87 /**
88  * Callback that is called when a new PeerID is removed from a sampler.
89  *
90  * @param cls the closure given alongside this function.
91  * @param id the PeerID that is removed
92  * @param hash the hash the sampler produced of the PeerID
93  */
94 typedef void (* SAMPLER_removeCB) (void *cls,
95     const struct GNUNET_PeerIdentity *id,
96     struct GNUNET_HashCode hash);
97
98 /**
99  * A sampler sampling PeerIDs.
100  */
101 struct Sampler
102 {
103   /**
104    * Min-wise linear permutation used by this sampler.
105    *
106    * This is an key later used by a hmac.
107    */
108   struct GNUNET_CRYPTO_AuthKey auth_key;
109
110   /**
111    * The PeerID this sampler currently samples.
112    */
113   struct GNUNET_PeerIdentity *peer_id;
114
115   /**
116    * The according hash value of this PeerID.
117    */
118   struct GNUNET_HashCode peer_id_hash;
119
120   /**
121    * Samplers are kept in a linked list.
122    */
123   struct Sampler *next;
124
125   /**
126    * Samplers are kept in a linked list.
127    */
128   struct Sampler *prev;
129
130 };
131
132 /**
133  * A n-tuple of samplers.
134  */
135 struct Samplers
136 {
137   /**
138    * Number of samplers we hold.
139    */
140   unsigned int size;
141   //size_t size;
142   
143   /**
144    * All PeerIDs in one array.
145    */
146   struct GNUNET_PeerIdentity *peer_ids;
147
148   /**
149    * Callback to be called when a peer gets inserted into a sampler.
150    */
151   SAMPLER_insertCB insertCB;
152
153   /**
154    * Closure to the insertCB.
155    */
156   void *insertCLS;
157
158   /**
159    * Callback to be called when a peer gets inserted into a sampler.
160    */
161   SAMPLER_removeCB removeCB;
162
163   /**
164    * Closure to the removeCB.
165    */
166   void *removeCLS;
167
168   /**
169    * The head of the DLL.
170    */
171   struct Sampler *head;
172
173   /**
174    * The tail of the DLL.
175    */
176   struct Sampler *tail;
177
178 };
179
180 /**
181  * (Re)Initialise given Sampler with random min-wise independent function.
182  *
183  * In this implementation this means choosing an auth_key for later use in
184  * a hmac at random.
185  *
186  * @param id pointer to the place where this sampler will store the PeerID.
187  *           This will be overwritten.
188  */
189   struct Sampler *
190 SAMPLER_init(struct GNUNET_PeerIdentity *id)
191 {
192   struct Sampler *s;
193   
194   s = GNUNET_new(struct Sampler);
195
196   // I guess I don't need to call GNUNET_CRYPTO_hmac_derive_key()...
197   GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_STRONG,
198                              &(s->auth_key.key),
199                              GNUNET_CRYPTO_HASH_LENGTH);
200
201   GNUNET_assert(NULL != id);
202   s->peer_id = id;
203   memcpy(s->peer_id, own_identity, sizeof(struct GNUNET_PeerIdentity)); // FIXME this should probably be NULL -- the caller has to handle those.
204   //s->peer_id = own_identity; // Maybe set to own PeerID. So we always have
205                      // a valid PeerID in the sampler.
206                      // Maybe take a PeerID as second argument.
207   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: initialised with PeerID %s (at %p) \n",
208       GNUNET_i2s(s->peer_id), s->peer_id);
209
210   GNUNET_CRYPTO_hmac(&s->auth_key, s->peer_id,
211                      sizeof(struct GNUNET_PeerIdentity),
212                      &s->peer_id_hash);
213
214   s->prev = NULL;
215   s->next = NULL;
216
217   return s;
218 }
219
220 /**
221  * Compare two hashes.
222  *
223  * Used by SAMPLER_next() to compare hashes.
224  */
225   int
226 hash_cmp(struct GNUNET_HashCode *hash1, struct GNUNET_HashCode *hash2)
227 {
228   return memcmp( (const void *) hash1, (const void *) hash2, sizeof(struct GNUNET_HashCode));
229 }
230
231 /**
232  * Compare two PeerIDs.
233  *
234  * Used by SAMPLER_next() to compare hashes.
235  * @param p1 Some peer identity.
236  * @param p2 Some peer identity.
237  * @return 1 if p1 > p2, -1 if p1 < p2 and 0 if p1 == p2.
238  */
239   int
240 peer_cmp(const struct GNUNET_PeerIdentity *id1, const struct GNUNET_PeerIdentity *id2)
241 {
242   return memcmp( (const void *) id1, (const void *) id2, sizeof(struct GNUNET_PeerIdentity));
243 }
244
245 /**
246  * Input an PeerID into the given sampler.
247  */
248   static void
249 SAMPLER_next(struct Sampler *s, const struct GNUNET_PeerIdentity *other,
250     SAMPLER_insertCB insertCB, void *insertCLS,
251     SAMPLER_removeCB removeCB, void *removeCLS)
252   // TODO call update herein
253 {
254   struct GNUNET_HashCode other_hash;
255
256   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: New PeerID %s at %p\n",
257       GNUNET_i2s(other), other);
258   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Old PeerID %s at %p\n",
259       GNUNET_i2s(s->peer_id), s->peer_id);
260
261   if ( 0 == peer_cmp(other, s->peer_id) )
262   {
263     LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:          Got PeerID %s\n",
264         GNUNET_i2s(other));
265     LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Have already PeerID %s\n",
266         GNUNET_i2s(s->peer_id));
267   }
268   else
269   {
270     GNUNET_CRYPTO_hmac(&s->auth_key,
271         other,
272         sizeof(struct GNUNET_PeerIdentity),
273         &other_hash);
274
275     if ( NULL == s->peer_id )
276     { // Or whatever is a valid way to say
277       // "we have no PeerID at the moment"
278       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Got PeerID %s; Simply accepting (got NULL previously).\n",
279           GNUNET_i2s(other));
280       memcpy(s->peer_id, other, sizeof(struct GNUNET_PeerIdentity));
281       //s->peer_id = other;
282       s->peer_id_hash = other_hash;
283       if (NULL != insertCB)
284       {
285         insertCB(insertCLS, s->peer_id, s->peer_id_hash);
286       }
287     }
288     else if ( 0 > hash_cmp(&other_hash, &s->peer_id_hash) )
289     {
290       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:            Got PeerID %s\n",
291           GNUNET_i2s(other));
292       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Discarding old PeerID %s\n",
293           GNUNET_i2s(s->peer_id));
294
295       if ( NULL != removeCB )
296       {
297         LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Removing old PeerID %s with the remove callback.\n",
298             GNUNET_i2s(s->peer_id));
299         removeCB(removeCLS, s->peer_id, s->peer_id_hash);
300       }
301
302       memcpy(s->peer_id, other, sizeof(struct GNUNET_PeerIdentity));
303       //s->peer_id = other;
304       s->peer_id_hash = other_hash;
305
306       if ( NULL != insertCB )
307       {
308         LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Inserting new PeerID %s with the insert callback.\n",
309             GNUNET_i2s(s->peer_id));
310         insertCB(insertCLS, s->peer_id, s->peer_id_hash);
311       }
312     }
313     else
314     {
315       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:         Got PeerID %s\n",
316           GNUNET_i2s(other));
317       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Keeping old PeerID %s\n",
318           GNUNET_i2s(s->peer_id));
319     }
320   }
321 }
322
323 /**
324  * Gow or shrink the size of the tuple of samplers.
325  *
326  * @param samplers the samplers to grow
327  * @param new_size the new size of the samplers
328  * @param fill_up_id if growing, that has to point to a
329  *                   valid PeerID and will be used
330  *                   to initialise newly created samplers
331  */
332   void
333 SAMPLER_samplers_resize (struct Samplers * samplers,
334     unsigned int new_size,
335     struct GNUNET_PeerIdentity *fill_up_id)
336 {
337   if ( samplers->size == new_size )
338   {
339     LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Size remains the same -- nothing to do\n");
340     return;
341   }
342
343   unsigned int old_size;
344   struct Sampler *iter;
345   uint64_t i;
346   struct Sampler *tmp;
347
348   old_size = samplers->size;
349   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Growing/Shrinking samplers %u -> %u\n", old_size, new_size);
350
351   iter = samplers->head;
352
353   if ( new_size < old_size )
354   {
355     for ( i = new_size ; i < old_size ; i++ )
356     {/* Remove unneeded rest */
357       tmp = iter->next;
358       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Removing %" PRIX64 ". sampler\n", i);
359       if (NULL != samplers->removeCB)
360         samplers->removeCB(samplers->removeCLS, iter->peer_id, iter->peer_id_hash);
361       GNUNET_CONTAINER_DLL_remove(samplers->head, samplers->tail, iter);
362       GNUNET_free(iter);
363       iter = tmp;
364     }
365   }
366
367   GNUNET_array_grow(samplers->peer_ids, samplers->size, new_size);
368   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: samplers->peer_ids now points to %p\n", samplers->peer_ids);
369
370   if ( new_size > old_size )
371   { /* Growing */
372     GNUNET_assert( NULL != fill_up_id );
373     for ( i = 0 ; i < new_size ; i++ )
374     { /* All samplers */
375       if ( i < old_size )
376       { /* Update old samplers */
377         iter->peer_id = &samplers->peer_ids[i];
378         LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Updated %" PRIX64 ". sampler, now pointing to %p, contains %s\n",
379             i, &samplers->peer_ids[i], GNUNET_i2s(iter->peer_id));
380         iter = iter->next;
381       }
382       else
383       { /* Add new samplers */
384         memcpy(&samplers->peer_ids[i], fill_up_id, sizeof(struct GNUNET_PeerIdentity));
385         iter = SAMPLER_init(&samplers->peer_ids[i]);
386         if (NULL != samplers->insertCB)
387         {
388           samplers->insertCB(samplers->insertCLS, iter->peer_id, iter->peer_id_hash);
389         }
390         GNUNET_CONTAINER_DLL_insert_tail(samplers->head, samplers->tail, iter);
391         LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Added %" PRIX64 ". sampler, now pointing to %p, contains %s\n",
392             i, &samplers->peer_ids[i], GNUNET_i2s(iter->peer_id));
393       }
394     }
395   }
396   else// if ( new_size < old_size )
397   { /* Shrinking */
398     for ( i = 0 ; i < new_size ; i++)
399     { /* All samplers */
400       tmp = iter->next;
401       /* Update remaining samplers */
402       iter->peer_id = &samplers->peer_ids[i];
403       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Updatied %" PRIX64 ". sampler, now pointing to %p, contains %s\n",
404           i, &samplers->peer_ids[i], GNUNET_i2s(iter->peer_id));
405
406       iter = tmp;
407     }
408   }
409
410   GNUNET_assert(samplers->size == new_size);
411   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Finished growing/shrinking.\n");
412 }
413
414
415 /**
416  * Initialise a tuple of samplers.
417  */
418 struct Samplers *
419 SAMPLER_samplers_init(size_t init_size, struct GNUNET_PeerIdentity *id,
420     SAMPLER_insertCB insertCB, void *insertCLS,
421     SAMPLER_removeCB removeCB, void *removeCLS)
422 {
423   struct Samplers *samplers;
424   //struct Sampler *s;
425   //uint64_t i;
426
427   samplers = GNUNET_new(struct Samplers);
428   samplers->size = 0;
429   samplers->peer_ids = NULL;
430   samplers->insertCB = insertCB;
431   samplers->insertCLS = insertCLS;
432   samplers->removeCB = removeCB;
433   samplers->removeCLS = removeCLS;
434   samplers->head = samplers->tail = NULL;
435   //samplers->peer_ids = GNUNET_new_array(init_size, struct GNUNET_PeerIdentity);
436
437   SAMPLER_samplers_resize(samplers, init_size, id);
438
439   //for ( i = 0 ; i < init_size ; i++ )
440   //{
441   //  GNUNET_array_append(samplers->peer_ids,
442   //      samplers->size,
443   //      *id);
444   //  s = SAMPLER_init(&samplers->peer_ids[i]);
445   //  GNUNET_CONTAINER_DLL_insert_tail(samplers->head,
446   //      samplers->tail,
447   //      s);
448   //}
449   //samplers->size = init_size;
450   GNUNET_assert(init_size == samplers->size);
451   return samplers;
452 }
453
454
455 /**
456  * A fuction to update every sampler in the given list
457  */
458   static void
459 SAMPLER_update_list(struct Samplers *samplers, const struct GNUNET_PeerIdentity *id)
460 {
461   struct Sampler *iter;
462
463   iter = samplers->head;
464   while ( NULL != iter->next )
465   {
466     SAMPLER_next(iter, id,
467         samplers->insertCB, samplers->insertCLS,
468         samplers->removeCB, samplers->removeCLS);
469     iter = iter->next;
470   }
471   
472 }
473
474 /**
475  * Get one random peer out of the sampled peers.
476  *
477  * We might want to reinitialise this sampler after giving the
478  * corrsponding peer to the client.
479  */
480   const struct GNUNET_PeerIdentity* 
481 SAMPLER_get_rand_peer (struct Samplers *samplers)
482 {
483   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER_get_rand_peer:\n");
484
485   if ( 0 == samplers->size )
486   {
487     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sgrp: List empty - Returning own PeerID %s\n", GNUNET_i2s(own_identity));
488     return own_identity;
489   }
490   else
491   {
492     const struct GNUNET_PeerIdentity *peer;
493
494     peer = get_rand_peer(samplers->peer_ids, samplers->size);
495     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sgrp: Returning PeerID %s\n", GNUNET_i2s(peer));
496     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sgrp: (own ID: %s)\n", GNUNET_i2s(own_identity));
497
498     return peer;
499   }
500 }
501
502 /**
503  * Get n random peers out of the sampled peers.
504  *
505  * We might want to reinitialise this sampler after giving the
506  * corrsponding peer to the client.
507  * Random with or without consumption?
508  */
509   const struct GNUNET_PeerIdentity*  // TODO give back simple array
510 SAMPLER_get_n_rand_peers (struct Samplers *samplers, uint64_t n)
511 {
512   // TODO check if we have too much (distinct) sampled peers
513   // If we are not ready yet maybe schedule for later
514   struct GNUNET_PeerIdentity *peers;
515   uint64_t i;
516   
517   peers = GNUNET_malloc(n * sizeof(struct GNUNET_PeerIdentity));
518
519   for ( i = 0 ; i < n ; i++ ) {
520     //peers[i] = SAMPLER_get_rand_peer(samplers);
521     memcpy(&peers[i], SAMPLER_get_rand_peer(samplers), sizeof(struct GNUNET_PeerIdentity));
522   }
523
524   // TODO something else missing?
525   return peers;
526 }
527
528 /**
529  * Counts how many Samplers currently hold a given PeerID.
530  */
531   uint64_t
532 SAMPLER_count_id ( struct Samplers *samplers, const struct GNUNET_PeerIdentity *id )
533 {
534   struct Sampler *iter;
535   uint64_t count;
536
537   iter = samplers->head;
538   count = 0;
539   while ( NULL != iter )
540   {
541     if ( 0 == peer_cmp( iter->peer_id, id) )
542       count++;
543     iter = iter->next;
544   }
545   return count;
546 }
547
548
549 /**
550  * Cleans the samplers.
551  * 
552  * @param samplers the samplers to clean up.
553  */
554   void
555 SAMPLER_samplers_destroy (struct Samplers *samplers)
556 {
557   //struct Sampler *iter;
558   //struct Sampler *tmp;
559
560   SAMPLER_samplers_resize(samplers, 0, NULL);
561   //iter = samplers->head;
562   //while (NULL != iter) // use _samplers_resize(0)?
563   //{
564   //  iter = iter->next;
565   //  tmp = iter->prev;
566   //  GNUNET_CONTAINER_DLL_remove(samplers->head, samplers->tail, iter->prev);
567   //  GNUNET_free(tmp);
568   //}
569   //GNUNET_array_grow(samplers->peer_ids, samplers->size, 0);
570   GNUNET_free(samplers);
571 }
572
573 /***********************************************************************
574  * /Sampler
575 ***********************************************************************/
576
577
578
579 /***********************************************************************
580  * Housekeeping with peers
581 ***********************************************************************/
582
583 /**
584  * Struct used to store the context of a connected client.
585  */
586 struct client_ctx
587 {
588   /**
589    * The message queue to communicate with the client.
590    */
591   struct GNUNET_MQ_Handle *mq;
592 };
593
594 /**
595  * Used to keep track in what lists single peerIDs are.
596  */
597 enum in_list_flag // probably unneeded
598 {
599   in_other_sampler_list = 0x1,
600   in_other_gossip_list  = 0x2, // unneeded?
601   in_own_sampler_list   = 0x4,
602   in_own_gossip_list    = 0x8 // unneeded?
603 };
604
605 /**
606  * Struct used to keep track of other peer's status
607  *
608  * This is stored in a multipeermap.
609  */
610 struct peer_context
611 {
612   /**
613    * In own gossip/sampler list, in other's gossip/sampler list
614    */
615   uint32_t in_flags; // unneeded?
616
617   /**
618    * Message queue open to client
619    */
620   struct GNUNET_MQ_Handle *mq;
621
622   /**
623    * Channel open to client.
624    */
625   struct GNUNET_CADET_Channel *to_channel;
626
627   /**
628    * Channel open from client.
629    */
630   struct GNUNET_CADET_Channel *from_channel; // unneeded
631
632   /**
633    * This is pobably followed by 'statistical' data (when we first saw
634    * him, how did we get his ID, how many pushes (in a timeinterval),
635    * ...)
636    */
637 };
638
639 /***********************************************************************
640  * /Housekeeping with peers
641 ***********************************************************************/
642
643 /**
644  * Set of all peers to keep track of them.
645  */
646 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
647
648
649 /**
650  * The samplers.
651  */
652 struct Samplers *sampler_list;
653
654
655 /**
656  * The gossiped list of peers.
657  */
658 struct GNUNET_PeerIdentity *gossip_list;
659
660 /**
661  * Size of the gossiped list
662  */
663 unsigned int gossip_list_size;
664
665
666 /**
667  * The estimated size of the network.
668  *
669  * Influenced by the stdev.
670  */
671 unsigned int est_size;
672 //size_t est_size;
673
674
675 /**
676  * Percentage of total peer number in the gossip list
677  * to send random PUSHes to
678  */
679 float alpha;
680
681 /**
682  * Percentage of total peer number in the gossip list
683  * to send random PULLs to
684  */
685 float beta;
686
687 /**
688  * The percentage gamma of history updates.
689  * Simply 1 - alpha - beta
690  */
691
692
693
694
695 /**
696  * Identifier for the main task that runs periodically.
697  */
698 struct GNUNET_SCHEDULER_Task * do_round_task;
699
700 /**
701  * Time inverval the do_round task runs in.
702  */
703 struct GNUNET_TIME_Relative round_interval;
704
705
706
707 /**
708  * List to store peers received through pushes temporary.
709  */
710 struct GNUNET_PeerIdentity *push_list;
711
712 /**
713  * Size of the push_list;
714  */
715 unsigned int push_list_size;
716 //size_t push_list_size;
717
718 /**
719  * List to store peers received through pulls temporary.
720  */
721 struct GNUNET_PeerIdentity *pull_list;
722
723 /**
724  * Size of the pull_list;
725  */
726 unsigned int pull_list_size;
727 //size_t pull_list_size;
728
729
730 /**
731  * Handler to NSE.
732  */
733 struct GNUNET_NSE_Handle *nse;
734
735 /**
736  * Handler to CADET.
737  */
738 struct GNUNET_CADET_Handle *cadet_handle;
739
740
741 /***********************************************************************
742  * Util functions
743 ***********************************************************************/
744
745 /**
746  * Get random peer from the gossip list.
747  */
748   struct GNUNET_PeerIdentity *
749 get_rand_peer(struct GNUNET_PeerIdentity *peer_list, unsigned int size)
750 {
751   uint64_t r_index;
752   struct GNUNET_PeerIdentity *peer;
753
754   // TODO find a better solution.
755   // FIXME if we have only own ID in gossip list this will block
756   // but then we might have a problem nevertheless ?
757
758   do {
759
760     /**;
761      * Choose the r_index of the peer we want to return
762      * at random from the interval of the gossip list
763      */
764     r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
765                                      size);
766
767     peer = &(peer_list[r_index]);
768   } while ( own_identity == peer || NULL == peer );
769
770   return peer;
771 }
772
773 /**
774  * Make sure the context of a given peer exists.
775  */
776   void
777 touch_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
778 {
779   struct peer_context *ctx;
780
781   if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains( peer_map, peer ) )
782   {
783     ctx = GNUNET_CONTAINER_multipeermap_get(peer_map, peer);
784   }
785   else
786   {
787     ctx = GNUNET_malloc(sizeof(struct peer_context));
788     ctx->in_flags = 0;
789     ctx->mq = NULL;
790     ctx->to_channel = NULL;
791     ctx->from_channel = NULL;
792     GNUNET_CONTAINER_multipeermap_put( peer_map, peer, ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
793   }
794 }
795
796 /**
797  * Get the context of a peer. If not existing, create.
798  */
799   struct peer_context *
800 get_peer_ctx (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
801 {
802   struct peer_context *ctx;
803
804   touch_peer_ctx(peer_map, peer);
805   ctx = GNUNET_CONTAINER_multipeermap_get(peer_map, peer);
806   return ctx;
807 }
808
809 /**
810  * Get the channel of a peer. If not existing, create.
811  */
812   void
813 touch_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
814 {
815   struct peer_context *ctx;
816
817   ctx = get_peer_ctx (peer_map, peer);
818   if (NULL == ctx->to_channel)
819   {
820     ctx->to_channel = GNUNET_CADET_channel_create(cadet_handle, NULL, peer,
821                                                   GNUNET_RPS_CADET_PORT,
822                                                   GNUNET_CADET_OPTION_RELIABLE);
823     //TODO do I have to explicitly put it in the peer_map?
824   }
825 }
826
827 /**
828  * Get the channel of a peer. If not existing, create.
829  */
830   struct GNUNET_CADET_Channel *
831 get_channel (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer)
832 {
833   struct peer_context *ctx;
834
835   ctx = get_peer_ctx (peer_map, peer);
836   touch_channel(peer_map, peer);
837   return ctx->to_channel;
838 }
839
840 /**
841  * Make sure the mq for a given peer exists.
842  *
843  * If we already have a message queue open to this client,
844  * simply return it, otherways create one.
845  */
846   void
847 touch_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer_id)
848 {
849   struct peer_context *ctx;
850
851   ctx = get_peer_ctx(peer_map, peer_id);
852   if (NULL == ctx->mq)
853   {
854     touch_channel(peer_map, peer_id);
855     ctx->mq = GNUNET_CADET_mq_create(ctx->to_channel);
856     //TODO do I have to explicitly put it in the peer_map?
857     //GNUNET_CONTAINER_multipeermap_put(peer_map, peer_id, ctx,
858     //                                  GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
859   }
860 }
861
862 /**
863  * Get the message queue of a specific peer.
864  *
865  * If we already have a message queue open to this client,
866  * simply return it, otherways create one.
867  */
868   struct GNUNET_MQ_Handle *
869 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, const struct GNUNET_PeerIdentity *peer_id)
870 {
871   struct peer_context *ctx;
872
873   ctx = get_peer_ctx(peer_map, peer_id);
874   touch_mq(peer_map, peer_id);
875
876   return ctx->mq;
877 }
878
879 /***********************************************************************
880  * /Util functions
881 ***********************************************************************/
882
883 /**
884  * Function called by NSE.
885  *
886  * Updates sizes of sampler list and gossip list and adapt those lists
887  * accordingly.
888  */
889   void
890 nse_callback(void *cls, struct GNUNET_TIME_Absolute timestamp, double logestimate, double std_dev)
891 {
892   double estimate;
893   //double scale; // TODO this might go gloabal/config
894
895   LOG(GNUNET_ERROR_TYPE_DEBUG, "Received a ns estimate - logest: %f, std_dev: %f\n", logestimate, std_dev);
896   //scale = .01;
897   estimate = 1 << (uint64_t) round(logestimate);
898   // GNUNET_NSE_log_estimate_to_n (logestimate);
899   estimate = pow(estimate, 1./3);// * (std_dev * scale); // TODO add
900   if ( 0 < estimate ) {
901     LOG(GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
902     est_size = estimate;
903   } else {
904     LOG(GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
905   }
906 }
907
908 /**
909  * Handle RPS request from the client.
910  *
911  * @param cls closure
912  * @param client identification of the client
913  * @param message the actual message
914  */
915 static void
916 // TODO rename
917 handle_cs_request (void *cls,
918             struct GNUNET_SERVER_Client *client,
919             const struct GNUNET_MessageHeader *message)
920 {
921   LOG(GNUNET_ERROR_TYPE_DEBUG, "Client requested (a) random peer(s).\n");
922
923   struct GNUNET_RPS_CS_RequestMessage *msg;
924   //unsigned int n_arr[sampler_list->size];// =
925     //GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
926   //struct GNUNET_MQ_Handle *mq;
927   struct client_ctx *cli_ctx;
928   struct GNUNET_MQ_Envelope *ev;
929   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
930   uint64_t num_peers;
931   //uint64_t i;
932
933   // TODO
934   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
935   // Does not work because the compiler seems not to find it.
936   cli_ctx = GNUNET_SERVER_client_get_user_context(client, struct client_ctx);
937   if ( NULL == cli_ctx ) {
938     cli_ctx = GNUNET_new(struct client_ctx);
939     cli_ctx->mq = GNUNET_MQ_queue_for_server_client(client);
940     GNUNET_SERVER_client_set_user_context(client, cli_ctx);
941   }
942   
943   // TODO How many peers do we give back?
944   // Wait until we have enough random peers?
945
946   ev = GNUNET_MQ_msg_extra(out_msg,
947                            GNUNET_ntohll(msg->num_peers) * sizeof(struct GNUNET_PeerIdentity),
948                            GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
949   out_msg->num_peers = msg->num_peers; // No conversion between network and host order
950
951   num_peers = GNUNET_ntohll(msg->num_peers);
952   //&out_msg[1] = SAMPLER_get_n_rand_peers(sampler_list, num_peers);
953   memcpy(&out_msg[1],
954       SAMPLER_get_n_rand_peers(sampler_list, num_peers),
955       num_peers * sizeof(struct GNUNET_PeerIdentity));
956   
957   GNUNET_MQ_send(cli_ctx->mq, ev);
958   //GNUNET_MQ_destroy(mq);
959
960   GNUNET_SERVER_receive_done (client,
961                               GNUNET_OK);
962 }
963
964 /**
965  * Handle a PUSH message from another peer.
966  *
967  * Check the proof of work and store the PeerID
968  * in the temporary list for pushed PeerIDs.
969  *
970  * @param cls Closure
971  * @param channel The channel the PUSH was received over
972  * @param channel_ctx The context associated with this channel
973  * @param msg The message header
974  */
975 static int
976 handle_peer_push (void *cls,
977     struct GNUNET_CADET_Channel *channel,
978     void **channel_ctx,
979     const struct GNUNET_MessageHeader *msg)
980 {
981   LOG(GNUNET_ERROR_TYPE_DEBUG, "PUSH received\n");
982
983   struct GNUNET_PeerIdentity *peer;
984
985   // TODO check the proof of work
986   // and check limit for PUSHes
987   // IF we count per peer PUSHes
988   // maybe remove from gossip/sampler list
989   
990   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info( channel, GNUNET_CADET_OPTION_PEER );
991   
992   /* Add the sending peer to the push_list */
993   LOG(GNUNET_ERROR_TYPE_DEBUG, "Adding peer to push_list of size %u\n", push_list_size);
994   GNUNET_array_append(push_list, push_list_size, *peer);
995   LOG(GNUNET_ERROR_TYPE_DEBUG, "Size of push_list is now %u\n", push_list_size);
996
997   return GNUNET_OK;
998 }
999
1000 /**
1001  * Handle PULL REQUEST request message from another peer.
1002  *
1003  * Reply with the gossip list of PeerIDs.
1004  *
1005  * @param cls Closure
1006  * @param channel The channel the PUSH was received over
1007  * @param channel_ctx The context associated with this channel
1008  * @param msg The message header
1009  */
1010 static int
1011 handle_peer_pull_request (void *cls,
1012     struct GNUNET_CADET_Channel *channel,
1013     void **channel_ctx,
1014     const struct GNUNET_MessageHeader *msg)
1015 {
1016
1017   struct GNUNET_PeerIdentity *peer;
1018   struct GNUNET_MQ_Handle *mq;
1019   //struct GNUNET_RPS_P2P_PullRequestMessage *in_msg;
1020   struct GNUNET_MQ_Envelope *ev;
1021   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
1022
1023   // TODO find some way to keep one peer from spamming with pull requests
1024   // allow only one request per time interval ?
1025   // otherwise remove from peerlist?
1026
1027   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info(channel, GNUNET_CADET_OPTION_PEER);
1028   LOG(GNUNET_ERROR_TYPE_DEBUG, "PULL REQUEST from peer %s received\n", GNUNET_i2s(peer));
1029
1030   mq = GNUNET_CADET_mq_create(channel); // TODO without mq?
1031   //mq = get_mq(peer_map, peer);
1032
1033   //in_msg = (struct GNUNET_RPS_P2P_PullRequestMessage *) msg;
1034   // TODO how many peers do we actually send?
1035   // GNUNET_ntohll(in_msg->num_peers)
1036   ev = GNUNET_MQ_msg_extra(out_msg,
1037                            gossip_list_size * sizeof(struct GNUNET_PeerIdentity),
1038                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
1039   out_msg->num_peers = GNUNET_htonll(gossip_list_size);
1040   memcpy(&out_msg[1], gossip_list,
1041          gossip_list_size * sizeof(struct GNUNET_PeerIdentity));
1042
1043   GNUNET_MQ_send(mq, ev);
1044
1045   GNUNET_MQ_destroy(mq);
1046
1047
1048   return GNUNET_OK;
1049 }
1050
1051 /**
1052  * Handle PULL REPLY message from another peer.
1053  *
1054  * Check whether we sent a corresponding request and
1055  * whether this reply is the first one.
1056  *
1057  * @param cls Closure
1058  * @param channel The channel the PUSH was received over
1059  * @param channel_ctx The context associated with this channel
1060  * @param msg The message header
1061  */
1062 static int
1063 handle_peer_pull_reply (void *cls,
1064     struct GNUNET_CADET_Channel *channel,
1065     void **channel_ctx,
1066     const struct GNUNET_MessageHeader *msg)
1067 {
1068   LOG(GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
1069
1070   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
1071   struct GNUNET_PeerIdentity *peers;
1072   uint64_t i;
1073
1074   // TODO check that we sent a request and that it is the first reply
1075
1076   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1077   peers = (struct GNUNET_PeerIdentity *) &msg[1];
1078   for ( i = 0 ; i < GNUNET_ntohll(in_msg->num_peers) ; i++ ) {
1079     GNUNET_array_append(pull_list, pull_list_size, peers[i]);
1080   }
1081
1082   // TODO maybe a disconnect happens here
1083   
1084   return GNUNET_OK;
1085 }
1086
1087
1088 /**
1089  * Send out PUSHes and PULLs.
1090  *
1091  * This is executed regylary.
1092  */
1093 static void
1094 do_round(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1095 {
1096   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
1097
1098   uint64_t i;
1099   //unsigned int *n_arr;
1100   struct GNUNET_RPS_P2P_PushMessage        *push_msg;
1101   struct GNUNET_RPS_P2P_PullRequestMessage *pull_msg; // FIXME Send empty message
1102   struct GNUNET_MQ_Envelope *ev;
1103   struct GNUNET_PeerIdentity *peer;
1104
1105   // TODO print lists, ...
1106   // TODO cleanup peer_map
1107
1108
1109   /* If the NSE has changed adapt the lists accordingly */
1110   if ( sampler_list->size != est_size )
1111     SAMPLER_samplers_resize(sampler_list, est_size, own_identity);
1112
1113   GNUNET_array_grow(gossip_list, gossip_list_size, est_size);
1114
1115
1116   /* Would it make sense to have one shuffeled gossip list and then
1117    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1118    * use the rest to update sampler?
1119    * in essence get random peers with consumption */
1120
1121   /* Send PUSHes */
1122   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) gossip_list_size);
1123   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to send pushes to %f (%f * %u) peers.\n",
1124       alpha * gossip_list_size, alpha, gossip_list_size);
1125   for ( i = 0 ; i < alpha * gossip_list_size ; i++ ) { // TODO compute length
1126     peer = get_rand_peer(gossip_list, gossip_list_size);
1127     // TODO check NULL == peer
1128     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sending PUSH to peer %s of gossiped list.\n", GNUNET_i2s(peer));
1129
1130     ev = GNUNET_MQ_msg(push_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1131     //ev = GNUNET_MQ_msg_extra();
1132     /* TODO Compute proof of work here
1133     push_msg; */
1134     push_msg->placeholder = 0;
1135     GNUNET_MQ_send( get_mq(peer_map, peer), ev );
1136
1137     // TODO modify in_flags of respective peer?
1138   }
1139
1140
1141   /* Send PULL requests */
1142   // TODO
1143   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list->size);
1144   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to send pulls to %f (%f * %u) peers.\n",
1145       beta * gossip_list_size, beta, gossip_list_size);
1146   for ( i = 0 ; i < beta * gossip_list_size ; i++ ){ // TODO compute length
1147     peer = get_rand_peer(gossip_list, gossip_list_size);
1148     // TODO check NULL == peer
1149     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sending PULL request to peer %s of gossiped list.\n", GNUNET_i2s(peer));
1150
1151     ev = GNUNET_MQ_msg(pull_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1152     //ev = GNUNET_MQ_msg_extra();
1153     pull_msg->placeholder = 0;
1154     GNUNET_MQ_send( get_mq(peer_map, peer), ev );
1155     // TODO modify in_flags of respective peer?
1156   }
1157
1158
1159   /* Update gossip list */
1160   uint64_t r_index;
1161
1162   if ( push_list_size <= alpha * gossip_list_size &&
1163        push_list_size != 0 &&
1164        pull_list_size != 0 )
1165   {
1166     LOG(GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list. ()\n");
1167
1168     uint64_t first_border;
1169     uint64_t second_border;
1170
1171     first_border = round(alpha * gossip_list_size);
1172     for ( i = 0 ; i < first_border ; i++ )
1173     { // TODO use SAMPLER_get_n_rand_peers
1174       /* Update gossip list with peers received through PUSHes */
1175       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
1176                                        push_list_size);
1177       gossip_list[i] = push_list[r_index];
1178       // TODO change the in_flags accordingly
1179     }
1180
1181     second_border = first_border + round(beta * gossip_list_size);
1182     for ( i = first_border ; i < second_border ; i++ )
1183     {
1184       /* Update gossip list with peers received through PULLs */
1185       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
1186                                        pull_list_size);
1187       gossip_list[i] = pull_list[r_index];
1188       // TODO change the in_flags accordingly
1189     }
1190
1191     for ( i = second_border ; i < gossip_list_size ; i++ )
1192     {
1193       /* Update gossip list with peers from history */
1194       r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
1195                                        sampler_list->size);
1196       gossip_list[i] = sampler_list->peer_ids[r_index];
1197       // TODO change the in_flags accordingly
1198     }
1199
1200   }
1201   else
1202   {
1203     LOG(GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list. ()\n");
1204   }
1205   // TODO independent of that also get some peers from CADET_get_peers()?
1206
1207
1208   /* Update samplers */
1209
1210   for ( i = 0 ; i < push_list_size ; i++ )
1211   {
1212     SAMPLER_update_list(sampler_list, &push_list[i]);
1213     // TODO set in_flag?
1214   }
1215
1216   for ( i = 0 ; i < pull_list_size ; i++ )
1217   {
1218     SAMPLER_update_list(sampler_list, &pull_list[i]);
1219     // TODO set in_flag?
1220   }
1221
1222
1223   /* Empty push/pull lists */
1224   GNUNET_array_grow(push_list, push_list_size, 0);
1225   push_list_size = 0; // I guess that's not necessary but doesn't hurt
1226   GNUNET_array_grow(pull_list, pull_list_size, 0);
1227   pull_list_size = 0; // I guess that's not necessary but doesn't hurt
1228
1229
1230   /* Schedule next round */
1231   do_round_task = GNUNET_SCHEDULER_add_delayed( round_interval, &do_round, NULL );
1232   LOG(GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1233 }
1234
1235 /**
1236  * Open a connection to given peer and store channel and mq.
1237  */
1238   void
1239 insertCB (void *cls, const struct GNUNET_PeerIdentity *id, struct GNUNET_HashCode hash)
1240 {
1241   touch_mq(peer_map, id);
1242 }
1243
1244 /**
1245  * Close the connection to given peer and delete channel and mq.
1246  */
1247   void
1248 removeCB (void *cls, const struct GNUNET_PeerIdentity *id, struct GNUNET_HashCode hash)
1249 {
1250   size_t s;
1251   struct peer_context *ctx;
1252
1253   s = SAMPLER_count_id(sampler_list, id);
1254   if ( 1 >= s ) {
1255     if (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains(peer_map, id))
1256     {
1257       ctx = GNUNET_CONTAINER_multipeermap_get(peer_map, id);
1258       if (NULL != ctx->to_channel)
1259       {
1260         if (NULL != ctx->mq)
1261         {
1262           GNUNET_MQ_destroy(ctx->mq);
1263         }
1264         GNUNET_CADET_channel_destroy(ctx->to_channel);
1265       }
1266       // TODO cleanup peer
1267       GNUNET_CONTAINER_multipeermap_remove_all(peer_map, id);
1268     }
1269   }
1270 }
1271
1272 static void
1273 rps_start (struct GNUNET_SERVER_Handle *server);
1274
1275 /**
1276  * This is called from GNUNET_CADET_get_peers().
1277  *
1278  * It is called on every peer(ID) that cadet somehow has contact with.
1279  * We use those to initialise the sampler.
1280  */
1281 void
1282 init_peer_cb (void *cls,
1283               const struct GNUNET_PeerIdentity *peer,
1284               int tunnel, // "Do we have a tunnel towards this peer?"
1285               unsigned int n_paths, // "Number of known paths towards this peer"
1286               unsigned int best_path) // "How long is the best path?
1287                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1288 {
1289   if ( NULL != peer )
1290   {
1291     LOG(GNUNET_ERROR_TYPE_DEBUG, "Got peer %s (at %p) from CADET\n", GNUNET_i2s(peer), peer);
1292     SAMPLER_update_list(sampler_list, peer);
1293     touch_peer_ctx(peer_map, peer);
1294
1295     uint64_t i;
1296     i = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, gossip_list_size);
1297     gossip_list[i] = *peer;
1298     // TODO send push/pull to each of those peers?
1299   }
1300   else
1301   {
1302     rps_start( (struct GNUNET_SERVER_Handle *) cls);
1303   }
1304 }
1305
1306
1307
1308
1309 /**
1310  * Task run during shutdown.
1311  *
1312  * @param cls unused
1313  * @param tc unused
1314  */
1315 static void
1316 shutdown_task (void *cls,
1317                const struct GNUNET_SCHEDULER_TaskContext *tc)
1318 {
1319   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1320
1321   if ( NULL != do_round_task )
1322   {
1323     GNUNET_SCHEDULER_cancel (do_round_task);
1324     do_round_task = NULL;
1325   }
1326
1327   GNUNET_NSE_disconnect(nse);
1328   GNUNET_CADET_disconnect(cadet_handle);
1329   GNUNET_free(own_identity);
1330   //GNUNET_free(round_interval);
1331   //GNUNET_free(gossip_list);
1332   SAMPLER_samplers_destroy(sampler_list);
1333   GNUNET_array_grow(gossip_list, gossip_list_size, 0);
1334   GNUNET_array_grow(push_list, push_list_size, 0);
1335   GNUNET_array_grow(pull_list, pull_list_size, 0);
1336   // TODO delete global data
1337 }
1338
1339
1340 /**
1341  * A client disconnected.  Remove all of its data structure entries.
1342  *
1343  * @param cls closure, NULL
1344  * @param client identification of the client
1345  */
1346 static void
1347 handle_client_disconnect (void *cls,
1348                           struct GNUNET_SERVER_Client * client)
1349 {
1350   // TODO reinitialise that sampler
1351 }
1352
1353 /**
1354  * Handle the channel a peer opens to us.
1355  *
1356  * @param cls The closure
1357  * @param channel The channel the peer wants to establish
1358  * @param initiator The peer's peer ID
1359  * @param port The port the channel is being established over
1360  * @param options Further options
1361  */
1362   static void *
1363 handle_inbound_channel (void *cls,
1364                         struct GNUNET_CADET_Channel *channel,
1365                         const struct GNUNET_PeerIdentity *initiator,
1366                         uint32_t port,
1367                         enum GNUNET_CADET_ChannelOption options)
1368 {
1369   LOG(GNUNET_ERROR_TYPE_DEBUG, "New channel was established to us.\n");
1370
1371   GNUNET_assert( NULL != channel );
1372
1373   // TODO we might not even store the from_channel
1374
1375   if ( GNUNET_CONTAINER_multipeermap_contains( peer_map, initiator ) ) {
1376     ((struct peer_context *) GNUNET_CONTAINER_multipeermap_get( peer_map, initiator ))->from_channel = channel;
1377     // FIXME there might already be an established channel
1378   } else {
1379     struct peer_context *ctx;
1380
1381     ctx = GNUNET_malloc( sizeof(struct peer_context));
1382     ctx->in_flags = in_other_gossip_list;
1383     ctx->mq = NULL; // TODO create mq?
1384     ctx->from_channel = channel;
1385
1386     GNUNET_CONTAINER_multipeermap_put( peer_map, initiator, ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1387   }
1388   return NULL; // TODO
1389 }
1390
1391 /**
1392  * This is called when a remote peer destroys a channel.
1393  *
1394  * @param cls The closure
1395  * @param channel The channel being closed
1396  * @param channel_ctx The context associated with this channel
1397  */
1398 static void
1399 cleanup_channel(void *cls,
1400                 const struct GNUNET_CADET_Channel *channel,
1401                 void *channel_ctx)
1402 {
1403   LOG(GNUNET_ERROR_TYPE_DEBUG, "Channel was destroyed by remote peer.\n");
1404   // TODO test whether that was a peer in the samplers/a peer we opened a connection to
1405   //      and if so, reinitialise the sampler
1406 }
1407
1408 /**
1409  * Actually start the service.
1410  */
1411 static void
1412 rps_start (struct GNUNET_SERVER_Handle *server)
1413 {
1414   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1415     {&handle_cs_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST, 0},
1416     {NULL, NULL, 0, 0}
1417   };
1418
1419   GNUNET_SERVER_add_handlers (server, handlers);
1420   GNUNET_SERVER_disconnect_notify (server,
1421                                    &handle_client_disconnect,
1422                                    NULL);
1423   LOG(GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1424
1425
1426
1427   do_round_task = GNUNET_SCHEDULER_add_delayed( round_interval, &do_round, NULL);
1428   LOG(GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1429
1430   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1431                                 &shutdown_task,
1432                                 NULL);
1433 }
1434
1435
1436
1437 /**
1438  * Process statistics requests.
1439  *
1440  * @param cls closure
1441  * @param server the initialized server
1442  * @param c configuration to use
1443  */
1444 static void
1445 run (void *cls,
1446      struct GNUNET_SERVER_Handle *server,
1447      const struct GNUNET_CONFIGURATION_Handle *c)
1448 {
1449   // TODO check what this does -- copied from gnunet-boss
1450   // - seems to work as expected
1451   GNUNET_log_setup("rps", GNUNET_error_type_to_string(GNUNET_ERROR_TYPE_DEBUG), NULL);
1452
1453   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS started\n");
1454
1455   cfg = c;
1456
1457
1458   own_identity = GNUNET_new(struct GNUNET_PeerIdentity); // needed?
1459
1460   GNUNET_CRYPTO_get_peer_identity(cfg, own_identity); // TODO check return value
1461
1462   GNUNET_assert(NULL != own_identity);
1463
1464   LOG(GNUNET_ERROR_TYPE_DEBUG, "Own identity is %s (at %p).\n", GNUNET_i2s(own_identity), own_identity);
1465
1466
1467
1468   /* Get time interval from the configuration */
1469   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1470                                                         "ROUNDINTERVAL",
1471                                                         &round_interval))
1472   {
1473     LOG(GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1474     GNUNET_SCHEDULER_shutdown();
1475     return;
1476   }
1477
1478   /* Get initial size of sampler/gossip list from the configuration */
1479   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1480                                                          "INITSIZE",
1481                                                          (long long unsigned int *) &est_size))
1482   {
1483     LOG(GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1484     GNUNET_SCHEDULER_shutdown();
1485     return;
1486   }
1487   LOG(GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", est_size);
1488
1489   //gossip_list_size = est_size; // TODO rename est_size
1490
1491   gossip_list = NULL;
1492
1493   GNUNET_array_grow(gossip_list, gossip_list_size, est_size);
1494
1495
1496   /* connect to NSE */
1497   nse = GNUNET_NSE_connect(cfg, nse_callback, NULL);
1498   // TODO check whether that was successful
1499   // TODO disconnect on shutdown
1500   LOG(GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1501
1502
1503   alpha = 0.45;
1504   beta  = 0.45;
1505   // TODO initialise thresholds - ?
1506
1507   ///* Get alpha from the configuration */
1508   //if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1509   //                                                       "ALPHA",
1510   //                                                       &alpha))
1511   //{
1512   //  LOG(GNUNET_ERROR_TYPE_DEBUG, "No ALPHA specified in the config\n");
1513   //}
1514   //LOG(GNUNET_ERROR_TYPE_DEBUG, "ALPHA is %f\n", alpha);
1515  
1516   ///* Get beta from the configuration */
1517   //if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1518   //                                                       "BETA",
1519   //                                                       &beta))
1520   //{
1521   //  LOG(GNUNET_ERROR_TYPE_DEBUG, "No BETA specified in the config\n");
1522   //}
1523   //LOG(GNUNET_ERROR_TYPE_DEBUG, "BETA is %f\n", beta);
1524
1525
1526   peer_map = GNUNET_CONTAINER_multipeermap_create(est_size, GNUNET_NO);
1527
1528
1529   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1530     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        , 0},
1531     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST, 0},
1532     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1533     {NULL, 0, 0}
1534   };
1535
1536   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1537   cadet_handle = GNUNET_CADET_connect(cfg,
1538                                     cls,
1539                                     &handle_inbound_channel,
1540                                     &cleanup_channel,
1541                                     cadet_handlers,
1542                                     ports);
1543   LOG(GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1544
1545
1546   /* Initialise sampler and gossip list */
1547
1548   sampler_list = SAMPLER_samplers_init(est_size, own_identity, insertCB, NULL, removeCB, NULL);
1549
1550   push_list = NULL;
1551   push_list_size = 0;
1552   pull_list = NULL;
1553   pull_list_size = 0;
1554
1555
1556   LOG(GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1557   GNUNET_CADET_get_peers(cadet_handle, &init_peer_cb, server);
1558   // FIXME use magic 0000 PeerID to _start_ the service
1559
1560   // TODO send push/pull to each of those peers?
1561 }
1562
1563
1564 /**
1565  * The main function for the rps service.
1566  *
1567  * @param argc number of arguments from the command line
1568  * @param argv command line arguments
1569  * @return 0 ok, 1 on error
1570  */
1571 int
1572 main (int argc, char *const *argv)
1573 {
1574   return (GNUNET_OK ==
1575           GNUNET_SERVICE_run (argc,
1576                               argv,
1577                               "rps",
1578                               GNUNET_SERVICE_OPTION_NONE,
1579                               &run, NULL)) ? 0 : 1;
1580 }
1581
1582 /* end of gnunet-service-rps.c */