f382786a4ba8b6111025acd92bf1a9c8886bb6a8
[oweals/gnunet.git] / src / rps / gnunet-service-rps_sampler.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file rps/gnunet-service-rps_sampler.c
23  * @brief sampler implementation
24  * @author Julius Bünger
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "rps.h"
29
30 #include "gnunet-service-rps_sampler.h"
31
32 #include <math.h>
33 #include <inttypes.h>
34
35 #include "rps-test_util.h"
36
37 #define LOG(kind, ...) GNUNET_log_from(kind,"rps-sampler",__VA_ARGS__)
38
39
40 // multiple 'clients'?
41
42 // TODO check for overflows
43
44 // TODO align message structs
45
46 // hist_size_init, hist_size_max
47
48 /***********************************************************************
49  * WARNING: This section needs to be reviewed regarding the use of
50  * functions providing (pseudo)randomness!
51 ***********************************************************************/
52
53 // TODO care about invalid input of the caller (size 0 or less...)
54
55 enum RPS_SamplerEmpty
56 {
57   NOT_EMPTY = 0x0,
58       EMPTY = 0x1
59 };
60
61 /**
62  * A sampler element sampling one PeerID at a time.
63  */
64 struct RPS_SamplerElement
65 {
66   /**
67    * Min-wise linear permutation used by this sampler.
68    *
69    * This is an key later used by a hmac.
70    */
71   struct GNUNET_CRYPTO_AuthKey auth_key;
72
73   /**
74    * The PeerID this sampler currently samples.
75    */
76   struct GNUNET_PeerIdentity peer_id;
77
78   /**
79    * The according hash value of this PeerID.
80    */
81   struct GNUNET_HashCode peer_id_hash;
82
83
84   /**
85    * Time of last request.
86    */
87   struct GNUNET_TIME_Absolute last_client_request;
88
89   /**
90    * Flag that indicates that we are not holding a valid PeerID right now.
91    */
92   enum RPS_SamplerEmpty is_empty;
93
94   /**
95    * 'Birth'
96    */
97   struct GNUNET_TIME_Absolute birth;
98
99   /**
100    * How many times a PeerID was put in this sampler.
101    */
102   uint32_t num_peers;
103
104   /**
105    * How many times this sampler changed the peer_id.
106    */
107   uint32_t num_change;
108
109   /**
110    * The file name this sampler element should log to
111    */
112   #ifdef TO_FILE
113   char *file_name;
114   #endif /* TO_FILE */
115 };
116
117 /**
118  * Callback that is called from _get_rand_peer() when the PeerID is ready.
119  *
120  * @param cls the closure given alongside this function.
121  * @param id the PeerID that was returned
122  */
123 typedef void
124 (*RPS_sampler_rand_peer_ready_cont) (void *cls,
125                                      const struct GNUNET_PeerIdentity *id);
126
127
128 /**
129  * Closure for #sampler_mod_get_rand_peer() and #sampler_get_rand_peer
130  */
131 struct GetPeerCls
132 {
133   /**
134    * DLL
135    */
136   struct GetPeerCls *next;
137
138   /**
139    * DLL
140    */
141   struct GetPeerCls *prev;
142
143   /**
144    * The sampler this function operates on.
145    */
146   struct RPS_Sampler *sampler;
147
148   /**
149    * The task for this function.
150    */
151   struct GNUNET_SCHEDULER_Task *get_peer_task;
152
153   /**
154    * The callback
155    */
156   RPS_sampler_rand_peer_ready_cont cont;
157
158   /**
159    * The closure to the callback @e cont
160    */
161   void *cont_cls;
162
163   /**
164    * The address of the id to be stored at
165    */
166   struct GNUNET_PeerIdentity *id;
167 };
168
169
170 /**
171  * Type of function used to differentiate between modified and not modified
172  * Sampler.
173  */
174 typedef void
175 (*RPS_get_peers_type) (void *cls,
176                        const struct GNUNET_SCHEDULER_TaskContext *tc);
177
178 /**
179  * Get one random peer out of the sampled peers.
180  *
181  * We might want to reinitialise this sampler after giving the
182  * corrsponding peer to the client.
183  * Only used internally
184  */
185 static void
186 sampler_get_rand_peer (void *cls,
187                         const struct GNUNET_SCHEDULER_TaskContext *tc);
188
189 /**
190  * Get one random peer out of the sampled peers.
191  *
192  * We might want to reinitialise this sampler after giving the
193  * corrsponding peer to the client.
194  */
195 static void
196 sampler_mod_get_rand_peer (void *cls,
197                        const struct GNUNET_SCHEDULER_TaskContext *tc);
198
199
200 /**
201  * Sampler with its own array of SamplerElements
202  */
203 struct RPS_Sampler
204 {
205   /**
206    * Number of sampler elements we hold.
207    */
208   unsigned int sampler_size;
209   //size_t size;
210
211   /**
212    * All Samplers in one array.
213    */
214   struct RPS_SamplerElement **sampler_elements;
215
216   /**
217    * Maximum time a round takes
218    *
219    * Used in the context of RPS
220    */
221   struct GNUNET_TIME_Relative max_round_interval;
222
223   /**
224    * Stores the function to return peers. Which one it is depends on whether
225    * the Sampler is the modified one or not.
226    */
227   RPS_get_peers_type get_peers;
228
229   /**
230    * Head for the DLL to store the closures to pending requests.
231    */
232   struct GetPeerCls *gpc_head;
233
234   /**
235    * Tail for the DLL to store the closures to pending requests.
236    */
237   struct GetPeerCls *gpc_tail;
238
239   #ifdef TO_FILE
240   /**
241    * File name to log to
242    */
243   char *file_name;
244   #endif /* TO_FILE */
245 };
246
247 /**
248  * Closure to _get_n_rand_peers_ready_cb()
249  */
250 struct NRandPeersReadyCls
251 {
252   /**
253    * Number of peers we are waiting for.
254    */
255   uint32_t num_peers;
256
257   /**
258    * Number of peers we currently have.
259    */
260   uint32_t cur_num_peers;
261
262   /**
263    * Pointer to the array holding the ids.
264    */
265   struct GNUNET_PeerIdentity *ids;
266
267   /**
268    * Callback to be called when all ids are available.
269    */
270   RPS_sampler_n_rand_peers_ready_cb callback;
271
272   /**
273    * Closure given to the callback
274    */
275   void *cls;
276 };
277
278 ///**
279 // * Global sampler variable.
280 // */
281 //struct RPS_Sampler *sampler;
282
283
284 /**
285  * The minimal size for the extended sampler elements.
286  */
287 static size_t min_size;
288
289 /**
290  * The maximal size the extended sampler elements should grow to.
291  */
292 static size_t max_size;
293
294 /**
295  * The size the extended sampler elements currently have.
296  */
297 //static size_t extra_size;
298
299 /**
300  * Inedex to the sampler element that is the next to be returned
301  */
302 static uint32_t client_get_index;
303
304
305 /**
306  * Callback to _get_rand_peer() used by _get_n_rand_peers().
307  *
308  * Checks whether all n peers are available. If they are,
309  * give those back.
310  */
311 static void
312 check_n_peers_ready (void *cls,
313     const struct GNUNET_PeerIdentity *id)
314 {
315   struct NRandPeersReadyCls *n_peers_cls = cls;
316
317   n_peers_cls->cur_num_peers++;
318   LOG (GNUNET_ERROR_TYPE_DEBUG,
319       "Got %" PRIX32 ". of %" PRIX32 " peers\n",
320       n_peers_cls->cur_num_peers, n_peers_cls->num_peers);
321
322   if (n_peers_cls->num_peers == n_peers_cls->cur_num_peers)
323   { /* All peers are ready -- return those to the client */
324     GNUNET_assert (NULL != n_peers_cls->callback);
325
326     LOG (GNUNET_ERROR_TYPE_DEBUG,
327         "returning %" PRIX32 " peers to the client\n",
328         n_peers_cls->num_peers);
329     n_peers_cls->callback (n_peers_cls->cls, n_peers_cls->ids, n_peers_cls->num_peers);
330
331     GNUNET_free (n_peers_cls);
332   }
333 }
334
335
336 /**
337  * Reinitialise a previously initialised sampler element.
338  *
339  * @param sampler pointer to the memory that keeps the value.
340  */
341   static void
342 RPS_sampler_elem_reinit (struct RPS_SamplerElement *sampler_el)
343 {
344   sampler_el->is_empty = EMPTY;
345
346   // I guess I don't need to call GNUNET_CRYPTO_hmac_derive_key()...
347   GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_STRONG,
348                              &(sampler_el->auth_key.key),
349                              GNUNET_CRYPTO_HASH_LENGTH);
350
351   #ifdef TO_FILE
352   /* Create a file(-name) to store internals to */
353   char *name_buf;
354   name_buf = auth_key_to_string (sampler_el->auth_key);
355
356   sampler_el->file_name = create_file (name_buf);
357   GNUNET_free (name_buf);
358   #endif /* TO_FILE */
359
360   sampler_el->last_client_request = GNUNET_TIME_UNIT_FOREVER_ABS;
361
362   sampler_el->birth = GNUNET_TIME_absolute_get ();
363   sampler_el->num_peers = 0;
364   sampler_el->num_change = 0;
365 }
366
367
368 /**
369  * (Re)Initialise given Sampler with random min-wise independent function.
370  *
371  * In this implementation this means choosing an auth_key for later use in
372  * a hmac at random.
373  *
374  * @return a newly created RPS_SamplerElement which currently holds no id.
375  */
376   struct RPS_SamplerElement *
377 RPS_sampler_elem_create (void)
378 {
379   struct RPS_SamplerElement *s;
380
381   s = GNUNET_new (struct RPS_SamplerElement);
382
383   RPS_sampler_elem_reinit (s);
384
385   return s;
386 }
387
388
389 /**
390  * Input an PeerID into the given sampler element.
391  *
392  * @param sampler the sampler the @a s_elem belongs to.
393  *                Needed to know the
394  */
395 static void
396 RPS_sampler_elem_next (struct RPS_SamplerElement *s_elem,
397                        struct RPS_Sampler *sampler,
398                        const struct GNUNET_PeerIdentity *other)
399 {
400   struct GNUNET_HashCode other_hash;
401
402   s_elem->num_peers++;
403
404   to_file (s_elem->file_name,
405            "Got id %s",
406            GNUNET_i2s_full (other));
407
408   if (0 == GNUNET_CRYPTO_cmp_peer_identity (other, &(s_elem->peer_id)))
409   {
410     LOG (GNUNET_ERROR_TYPE_DEBUG, "         Got PeerID %s\n",
411         GNUNET_i2s (other));
412     LOG (GNUNET_ERROR_TYPE_DEBUG, "Have already PeerID %s\n",
413         GNUNET_i2s (&(s_elem->peer_id)));
414   }
415   else
416   {
417     GNUNET_CRYPTO_hmac(&s_elem->auth_key,
418         other,
419         sizeof(struct GNUNET_PeerIdentity),
420         &other_hash);
421
422     if (EMPTY == s_elem->is_empty)
423     {
424       LOG (GNUNET_ERROR_TYPE_DEBUG,
425            "Got PeerID %s; Simply accepting (was empty previously).\n",
426            GNUNET_i2s(other));
427       s_elem->peer_id = *other;
428       s_elem->peer_id_hash = other_hash;
429
430       s_elem->num_change++;
431     }
432     else if (0 > GNUNET_CRYPTO_hash_cmp (&other_hash, &s_elem->peer_id_hash))
433     {
434       LOG (GNUNET_ERROR_TYPE_DEBUG, "           Got PeerID %s\n",
435           GNUNET_i2s (other));
436       LOG (GNUNET_ERROR_TYPE_DEBUG, "Discarding old PeerID %s\n",
437           GNUNET_i2s (&s_elem->peer_id));
438       s_elem->peer_id = *other;
439       s_elem->peer_id_hash = other_hash;
440
441       s_elem->num_change++;
442     }
443     else
444     {
445       LOG (GNUNET_ERROR_TYPE_DEBUG, "        Got PeerID %s\n",
446           GNUNET_i2s (other));
447       LOG (GNUNET_ERROR_TYPE_DEBUG, "Keeping old PeerID %s\n",
448           GNUNET_i2s (&s_elem->peer_id));
449     }
450   }
451   s_elem->is_empty = NOT_EMPTY;
452
453   to_file (s_elem->file_name,
454            "Now holding %s",
455            GNUNET_i2s_full (&s_elem->peer_id));
456 }
457
458
459 /**
460  * Get the size of the sampler.
461  *
462  * @param sampler the sampler to return the size of.
463  * @return the size of the sampler
464  */
465 unsigned int
466 RPS_sampler_get_size (struct RPS_Sampler *sampler)
467 {
468   return sampler->sampler_size;
469 }
470
471
472 /**
473  * Grow or shrink the size of the sampler.
474  *
475  * @param sampler the sampler to resize.
476  * @param new_size the new size of the sampler
477  */
478 static void
479 sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
480 {
481   unsigned int old_size;
482   uint32_t i;
483
484   // TODO check min and max size
485
486   old_size = sampler->sampler_size;
487
488   if (old_size > new_size)
489   { /* Shrinking */
490     /* Temporary store those to properly call the removeCB on those later */
491
492     LOG (GNUNET_ERROR_TYPE_DEBUG,
493          "Shrinking sampler %d -> %d\n",
494          old_size,
495          new_size);
496
497     to_file (sampler->file_name,
498          "Shrinking sampler %d -> %d",
499          old_size,
500          new_size);
501
502     for (i = new_size ; i < old_size ; i++)
503     {
504       to_file (sampler->file_name,
505                "-%" PRIu32 ": %s",
506                i,
507                sampler->sampler_elements[i]->file_name);
508     }
509
510     GNUNET_array_grow (sampler->sampler_elements,
511         sampler->sampler_size,
512         new_size);
513     LOG (GNUNET_ERROR_TYPE_DEBUG,
514         "sampler->sampler_elements now points to %p\n",
515         sampler->sampler_elements);
516
517   }
518   else if (old_size < new_size)
519   { /* Growing */
520     LOG (GNUNET_ERROR_TYPE_DEBUG,
521          "Growing sampler %d -> %d\n",
522          old_size,
523          new_size);
524
525     to_file (sampler->file_name,
526          "Growing sampler %d -> %d",
527          old_size,
528          new_size);
529
530     GNUNET_array_grow (sampler->sampler_elements,
531         sampler->sampler_size,
532         new_size);
533
534     for (i = old_size ; i < new_size ; i++)
535     { /* Add new sampler elements */
536       sampler->sampler_elements[i] = RPS_sampler_elem_create ();
537
538       to_file (sampler->file_name,
539                "+%" PRIu32 ": %s",
540                i,
541                sampler->sampler_elements[i]->file_name);
542     }
543   }
544   else
545   {
546     LOG (GNUNET_ERROR_TYPE_DEBUG, "Size remains the same -- nothing to do\n");
547     return;
548   }
549
550   GNUNET_assert (sampler->sampler_size == new_size);
551 }
552
553
554 /**
555  * Grow or shrink the size of the sampler.
556  *
557  * @param sampler the sampler to resize.
558  * @param new_size the new size of the sampler
559  */
560 void
561 RPS_sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
562 {
563   GNUNET_assert (0 < new_size);
564   sampler_resize (sampler, new_size);
565 }
566
567
568 /**
569  * Empty the sampler.
570  *
571  * @param sampler the sampler to empty.
572  * @param new_size the new size of the sampler
573  */
574 static void
575 sampler_empty (struct RPS_Sampler *sampler)
576 {
577   sampler_resize (sampler, 0);
578 }
579
580
581 /**
582  * Initialise a tuple of sampler elements.
583  *
584  * @param init_size the size the sampler is initialised with
585  * @param max_round_interval maximum time a round takes
586  * @return a handle to a sampler that consists of sampler elements.
587  */
588 struct RPS_Sampler *
589 RPS_sampler_init (size_t init_size,
590                   struct GNUNET_TIME_Relative max_round_interval)
591 {
592   struct RPS_Sampler *sampler;
593
594   /* Initialise context around extended sampler */
595   min_size = 10; // TODO make input to _samplers_init()
596   max_size = 1000; // TODO make input to _samplers_init()
597
598   sampler = GNUNET_new (struct RPS_Sampler);
599
600   #ifdef TO_FILE
601   sampler->file_name = create_file ("sampler-");
602
603   LOG (GNUNET_ERROR_TYPE_DEBUG,
604        "Initialised sampler %s\n",
605        sampler->file_name);
606   #endif /* TO_FILE */
607
608   sampler->sampler_size = 0;
609   sampler->sampler_elements = NULL;
610   sampler->max_round_interval = max_round_interval;
611   sampler->get_peers = sampler_get_rand_peer;
612   sampler->gpc_head = NULL;
613   sampler->gpc_tail = NULL;
614   //sampler->sampler_elements = GNUNET_new_array(init_size, struct GNUNET_PeerIdentity);
615   //GNUNET_array_grow (sampler->sampler_elements, sampler->sampler_size, min_size);
616   RPS_sampler_resize (sampler, init_size);
617
618   client_get_index = 0;
619
620   //GNUNET_assert (init_size == sampler->sampler_size);
621   return sampler;
622 }
623
624 /**
625  * Initialise a modified tuple of sampler elements.
626  *
627  * @param init_size the size the sampler is initialised with
628  * @param max_round_interval maximum time a round takes
629  * @return a handle to a sampler that consists of sampler elements.
630  */
631 struct RPS_Sampler *
632 RPS_sampler_mod_init (size_t init_size,
633                       struct GNUNET_TIME_Relative max_round_interval)
634 {
635   struct RPS_Sampler *sampler;
636
637   sampler = RPS_sampler_init (init_size, max_round_interval);
638   sampler->get_peers = sampler_mod_get_rand_peer;
639
640   LOG (GNUNET_ERROR_TYPE_DEBUG,
641        "Initialised modified sampler %s\n",
642        sampler->file_name);
643   to_file (sampler->file_name,
644            "This is a modified sampler");
645
646   return sampler;
647 }
648
649
650 /**
651  * A fuction to update every sampler in the given list
652  *
653  * @param sampler the sampler to update.
654  * @param id the PeerID that is put in the sampler
655  */
656   void
657 RPS_sampler_update (struct RPS_Sampler *sampler,
658                     const struct GNUNET_PeerIdentity *id)
659 {
660   uint32_t i;
661
662   to_file (sampler->file_name,
663            "Got %s",
664            GNUNET_i2s_full (id));
665
666   for (i = 0 ; i < sampler->sampler_size ; i++)
667   {
668     RPS_sampler_elem_next (sampler->sampler_elements[i],
669                            sampler,
670                            id);
671   }
672 }
673
674
675 /**
676  * Reinitialise all previously initialised sampler elements with the given value.
677  *
678  * Used to get rid of a PeerID.
679  *
680  * @param sampler the sampler to reinitialise a sampler element in.
681  * @param id the id of the sampler elements to update.
682  */
683   void
684 RPS_sampler_reinitialise_by_value (struct RPS_Sampler *sampler,
685                                    const struct GNUNET_PeerIdentity *id)
686 {
687   uint32_t i;
688
689   for ( i = 0 ; i < sampler->sampler_size ; i++ )
690   {
691     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity(id, &(sampler->sampler_elements[i]->peer_id)) )
692     {
693       LOG (GNUNET_ERROR_TYPE_DEBUG, "Reinitialising sampler\n");
694       RPS_sampler_elem_reinit (sampler->sampler_elements[i]);
695     }
696   }
697 }
698
699
700 /**
701  * Get one random peer out of the sampled peers.
702  *
703  * We might want to reinitialise this sampler after giving the
704  * corrsponding peer to the client.
705  * Only used internally
706  */
707 static void
708 sampler_get_rand_peer (void *cls,
709                         const struct GNUNET_SCHEDULER_TaskContext *tc)
710 {
711   struct GetPeerCls *gpc = cls;
712   uint32_t r_index;
713
714   gpc->get_peer_task = NULL;
715   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
716     return;
717
718   /**;
719    * Choose the r_index of the peer we want to return
720    * at random from the interval of the gossip list
721    */
722   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
723       gpc->sampler->sampler_size);
724
725   if (EMPTY == gpc->sampler->sampler_elements[r_index]->is_empty)
726   {
727     //LOG (GNUNET_ERROR_TYPE_DEBUG,
728     //     "Not returning randomly selected, empty PeerID. - Rescheduling.\n");
729
730     /* FIXME no active wait - get notified, when new id arrives?
731      * Might also be a freshly emptied one. Others might still contain ids.
732      * Counter?
733      */
734     gpc->get_peer_task =
735       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (
736                                         GNUNET_TIME_UNIT_SECONDS, 0.1),
737                                     &sampler_get_rand_peer,
738                                     cls);
739     return;
740   }
741
742   *gpc->id = gpc->sampler->sampler_elements[r_index]->peer_id;
743
744   gpc->cont (gpc->cont_cls, gpc->id);
745
746   GNUNET_CONTAINER_DLL_remove (gpc->sampler->gpc_head,
747                                gpc->sampler->gpc_tail,
748                                gpc);
749
750   GNUNET_free (gpc);
751 }
752
753
754 /**
755  * Get one random peer out of the sampled peers.
756  *
757  * We might want to reinitialise this sampler after giving the
758  * corrsponding peer to the client.
759  */
760 static void
761 sampler_mod_get_rand_peer (void *cls,
762                        const struct GNUNET_SCHEDULER_TaskContext *tc)
763 {
764   struct GetPeerCls *gpc = cls;
765   struct GNUNET_PeerIdentity tmp_id;
766   unsigned int empty_flag;
767   struct RPS_SamplerElement *s_elem;
768   struct GNUNET_TIME_Relative last_request_diff;
769   uint32_t tmp_client_get_index;
770
771   gpc->get_peer_task = NULL;
772   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
773     return;
774
775   LOG (GNUNET_ERROR_TYPE_DEBUG, "Single peer was requested\n");
776
777
778   /* Store the next #client_get_index to check whether we cycled over the whole list */
779   if (0 < client_get_index)
780     tmp_client_get_index = client_get_index - 1;
781   else
782     tmp_client_get_index = gpc->sampler->sampler_size - 1;
783
784   LOG (GNUNET_ERROR_TYPE_DEBUG,
785       "sched for later if index reaches %" PRIX32 " (sampler size: %" PRIX32 ").\n",
786       tmp_client_get_index, gpc->sampler->sampler_size);
787
788   do
789   { /* Get first non empty sampler */
790     if (tmp_client_get_index == client_get_index)
791     { /* We once cycled over the whole list */
792       LOG (GNUNET_ERROR_TYPE_DEBUG, "reached tmp_index %" PRIX32 ".\n",
793            client_get_index);
794       GNUNET_assert (NULL == gpc->get_peer_task);
795       gpc->get_peer_task =
796         GNUNET_SCHEDULER_add_delayed (gpc->sampler->max_round_interval,
797                                       &sampler_mod_get_rand_peer,
798                                       cls);
799       return;
800     }
801
802     tmp_id = gpc->sampler->sampler_elements[client_get_index]->peer_id;
803     empty_flag = gpc->sampler->sampler_elements[client_get_index]->is_empty;
804     RPS_sampler_elem_reinit (gpc->sampler->sampler_elements[client_get_index]);
805     if (EMPTY != empty_flag)
806       RPS_sampler_elem_next (gpc->sampler->sampler_elements[client_get_index],
807                              gpc->sampler,
808                              &tmp_id);
809
810     /* Cycle the #client_get_index one step further */
811     if ( client_get_index == gpc->sampler->sampler_size - 1 )
812       client_get_index = 0;
813     else
814       client_get_index++;
815
816     LOG (GNUNET_ERROR_TYPE_DEBUG, "incremented index to %" PRIX32 ".\n",
817          client_get_index);
818   } while (EMPTY == gpc->sampler->sampler_elements[client_get_index]->is_empty);
819
820   s_elem = gpc->sampler->sampler_elements[client_get_index];
821   *gpc->id = s_elem->peer_id;
822
823   /* Check whether we may use this sampler to give it back to the client */
824   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us != s_elem->last_client_request.abs_value_us)
825   {
826     last_request_diff =
827       GNUNET_TIME_absolute_get_difference (s_elem->last_client_request,
828                                            GNUNET_TIME_absolute_get ());
829     /* We're not going to give it back now if it was
830      * already requested by a client this round */
831     if (last_request_diff.rel_value_us < gpc->sampler->max_round_interval.rel_value_us)
832     {
833       LOG (GNUNET_ERROR_TYPE_DEBUG,
834           "Last client request on this sampler was less than max round interval ago -- scheduling for later\n");
835       ///* How many time remains untile the next round has started? */
836       //inv_last_request_diff =
837       //  GNUNET_TIME_absolute_get_difference (last_request_diff,
838       //                                       sampler->max_round_interval);
839       // add a little delay
840       /* Schedule it one round later */
841       GNUNET_assert (NULL == gpc->get_peer_task);
842       gpc->get_peer_task =
843         GNUNET_SCHEDULER_add_delayed (gpc->sampler->max_round_interval,
844                                       &sampler_mod_get_rand_peer,
845                                       cls);
846       return;
847     }
848     // TODO add other reasons to wait here
849   }
850
851   s_elem->last_client_request = GNUNET_TIME_absolute_get ();
852
853   GNUNET_CONTAINER_DLL_remove (gpc->sampler->gpc_head,
854                                gpc->sampler->gpc_tail,
855                                gpc);
856   gpc->cont (gpc->cont_cls, gpc->id);
857   GNUNET_free (gpc);
858 }
859
860
861 /**
862  * Get n random peers out of the sampled peers.
863  *
864  * We might want to reinitialise this sampler after giving the
865  * corrsponding peer to the client.
866  * Random with or without consumption?
867  *
868  * @param sampler the sampler to get peers from.
869  * @param cb callback that will be called once the ids are ready.
870  * @param cls closure given to @a cb
871  * @param for_client #GNUNET_YES if result is used for client,
872  *                   #GNUNET_NO if used internally
873  * @param num_peers the number of peers requested
874  */
875   void
876 RPS_sampler_get_n_rand_peers (struct RPS_Sampler *sampler,
877                               RPS_sampler_n_rand_peers_ready_cb cb,
878                               void *cls, uint32_t num_peers)
879 {
880   GNUNET_assert (0 != sampler->sampler_size);
881
882   // TODO check if we have too much (distinct) sampled peers
883   uint32_t i;
884   struct NRandPeersReadyCls *cb_cls;
885   struct GetPeerCls *gpc;
886
887   cb_cls = GNUNET_new (struct NRandPeersReadyCls);
888   cb_cls->num_peers = num_peers;
889   cb_cls->cur_num_peers = 0;
890   cb_cls->ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
891   cb_cls->callback = cb;
892   cb_cls->cls = cls;
893
894   LOG (GNUNET_ERROR_TYPE_DEBUG,
895       "Scheduling requests for %" PRIu32 " peers\n", num_peers);
896
897   for (i = 0 ; i < num_peers ; i++)
898   {
899     gpc = GNUNET_new (struct GetPeerCls);
900     gpc->sampler = sampler;
901     gpc->cont = check_n_peers_ready;
902     gpc->cont_cls = cb_cls;
903     gpc->id = &cb_cls->ids[i];
904
905     // maybe add a little delay
906     gpc->get_peer_task = GNUNET_SCHEDULER_add_now (sampler->get_peers, gpc);
907
908     GNUNET_CONTAINER_DLL_insert (sampler->gpc_head,
909                                  sampler->gpc_tail,
910                                  gpc);
911   }
912 }
913
914
915 /**
916  * Counts how many Samplers currently hold a given PeerID.
917  *
918  * @param sampler the sampler to count ids in.
919  * @param id the PeerID to count.
920  *
921  * @return the number of occurrences of id.
922  */
923   uint32_t
924 RPS_sampler_count_id (struct RPS_Sampler *sampler,
925                       const struct GNUNET_PeerIdentity *id)
926 {
927   uint32_t count;
928   uint32_t i;
929
930   count = 0;
931   for ( i = 0 ; i < sampler->sampler_size ; i++ )
932   {
933     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (&sampler->sampler_elements[i]->peer_id, id)
934         && EMPTY != sampler->sampler_elements[i]->is_empty)
935       count++;
936   }
937   return count;
938 }
939
940
941 /**
942  * Cleans the sampler.
943  */
944   void
945 RPS_sampler_destroy (struct RPS_Sampler *sampler)
946 {
947   struct GetPeerCls *i;
948
949   for (i = sampler->gpc_head; NULL != i; i = sampler->gpc_head)
950   {
951     GNUNET_CONTAINER_DLL_remove (sampler->gpc_head,
952                                  sampler->gpc_tail,
953                                  i);
954     GNUNET_SCHEDULER_cancel (i->get_peer_task);
955     GNUNET_free (i);
956   }
957
958   sampler_empty (sampler);
959   GNUNET_free (sampler);
960 }
961
962 /* end of gnunet-service-rps.c */