fixed integer sizes and _get_rand_peer()
[oweals/gnunet.git] / src / rps / gnunet-service-rps_sampler.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_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 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
36
37 // multiple 'clients'?
38
39 // TODO check for overflows
40
41 // TODO align message structs
42
43 // hist_size_init, hist_size_max
44
45 /***********************************************************************
46  * WARNING: This section needs to be reviewed regarding the use of
47  * functions providing (pseudo)randomness!
48 ***********************************************************************/
49
50 // TODO care about invalid input of the caller (size 0 or less...)
51
52 enum RPS_SamplerEmpty
53 {
54   NOT_EMPTY = 0x0,
55       EMPTY = 0x1
56 };
57
58 /**
59  * A sampler element sampling one PeerID at a time.
60  */
61 struct RPS_SamplerElement
62 {
63   /**
64    * Min-wise linear permutation used by this sampler.
65    *
66    * This is an key later used by a hmac.
67    */
68   struct GNUNET_CRYPTO_AuthKey auth_key;
69
70   /**
71    * The PeerID this sampler currently samples.
72    */
73   struct GNUNET_PeerIdentity peer_id;
74
75   /**
76    * The according hash value of this PeerID.
77    */
78   struct GNUNET_HashCode peer_id_hash;
79
80
81   /**
82    * Time of last request.
83    */
84   struct GNUNET_TIME_Absolute last_client_request;
85   
86   /**
87    * Flag that indicates that we are not holding a valid PeerID right now.
88    */
89   enum RPS_SamplerEmpty is_empty;
90
91   /**
92    * 'Birth'
93    */
94   struct GNUNET_TIME_Absolute birth;
95
96   /**
97    * How many times a PeerID was put in this sampler.
98    */
99   uint32_t num_peers;
100
101   /**
102    * How many times this sampler changed the peer_id.
103    */
104   uint32_t num_change;
105 };
106
107 /**
108  * Sampler with its own array of SamplerElements
109  */
110 struct RPS_Sampler
111 {
112   /**
113    * Number of sampler elements we hold.
114    */
115   unsigned int sampler_size;
116   //size_t size;
117
118   /**
119    * All Samplers in one array.
120    */
121   struct RPS_SamplerElement **sampler_elements;
122
123   /**
124    * Max time a round takes
125    *
126    * Used in the context of RPS
127    */
128   struct GNUNET_TIME_Relative max_round_interval;
129
130   /**
131    * Callback to be called when a peer gets inserted into a sampler.
132    */
133   RPS_sampler_insert_cb insert_cb;
134
135   /**
136    * Closure to the insert_cb.
137    */
138   void *insert_cls;
139
140   /**
141    * Callback to be called when a peer gets inserted into a sampler.
142    */
143   RPS_sampler_remove_cb remove_cb;
144
145   /**
146    * Closure to the remove_cb.
147    */
148   void *remove_cls;
149 };
150
151 /**
152  * Closure to _get_n_rand_peers_ready_cb()
153  */
154 struct RPS_GetNRandPeersReadyCls
155 {
156   /**
157    * Number of peers we are waiting for.
158    */
159   uint32_t num_peers;
160
161   /**
162    * Number of peers we currently have.
163    */
164   uint32_t cur_num_peers;
165
166   /**
167    * Pointer to the array holding the ids.
168    */
169   struct GNUNET_PeerIdentity *ids;
170
171   /**
172    * Callback to be called when all ids are available.
173    */
174   RPS_sampler_n_rand_peers_ready_cb callback;
175
176   /**
177    * Closure given to the callback
178    */
179   void *cls;
180 };
181
182 /**
183  * Callback that is called from _get_rand_peer() when the PeerID is ready.
184  *
185  * @param cls the closure given alongside this function.
186  * @param id the PeerID that was returned
187  */
188 typedef void
189 (*RPS_sampler_rand_peer_ready_cb) (void *cls,
190         const struct GNUNET_PeerIdentity *id);
191
192 /**
193  * Closure to #RPS_sampler_get_rand_peer()
194  */
195 struct GetPeerCls
196 {
197   /**
198    * The task for this function.
199    */
200   struct GNUNET_SCHEDULER_Task *get_peer_task;
201
202   /**
203    * The callback
204    */
205   RPS_sampler_rand_peer_ready_cb cb;
206
207   /**
208    * The closure to the callback
209    */
210   void *cb_cls;
211
212   /**
213    * The address of the id to be stored at
214    */
215   struct GNUNET_PeerIdentity *id;
216 };
217
218 /**
219  * Multihashmap that keeps track of all get_peer_tasks that are still scheduled.
220  */
221 struct GNUNET_CONTAINER_MultiHashMap *get_peer_tasks;
222
223
224 /**
225  * Global sampler variable.
226  */
227 struct RPS_Sampler *sampler;
228
229
230 /**
231  * The minimal size for the extended sampler elements.
232  */
233 static size_t min_size;
234
235 /**
236  * The maximal size the extended sampler elements should grow to.
237  */
238 static size_t max_size;
239
240 /**
241  * The size the extended sampler elements currently have.
242  */
243 //static size_t extra_size;
244
245 /**
246  * Inedex to the sampler element that is the next to be returned
247  */
248 static uint32_t client_get_index;
249
250
251 /**
252  * Callback to _get_rand_peer() used by _get_n_rand_peers().
253  *
254  * Checks whether all n peers are available. If they are, 
255  * give those back.
256  */
257   void
258 RPS_sampler_get_n_rand_peers_ready_cb (void *cls,
259     const struct GNUNET_PeerIdentity *id)
260 {
261   struct RPS_GetNRandPeersReadyCls *n_peers_cls;
262
263   n_peers_cls = (struct RPS_GetNRandPeersReadyCls *) cls;
264
265   LOG (GNUNET_ERROR_TYPE_DEBUG,
266       "SAMPLER: Got %" PRIX32 "th of %" PRIX32 " peers\n",
267       n_peers_cls->cur_num_peers, n_peers_cls->num_peers);
268
269   if (n_peers_cls->num_peers - 1 == n_peers_cls->cur_num_peers)
270   { /* All peers are ready -- return those to the client */
271     GNUNET_assert (NULL != n_peers_cls->callback);
272
273     LOG (GNUNET_ERROR_TYPE_DEBUG,
274         "SAMPLER: returning %" PRIX32 " peers to the client\n",
275         n_peers_cls->num_peers);
276     n_peers_cls->callback (n_peers_cls->cls, n_peers_cls->ids, n_peers_cls->num_peers);
277     
278     GNUNET_free (n_peers_cls);
279   }
280 }
281
282
283 /**
284  * Reinitialise a previously initialised sampler element.
285  *
286  * @param sampler pointer to the memory that keeps the value.
287  */
288   static void
289 RPS_sampler_elem_reinit (struct RPS_SamplerElement *sampler_el)
290 {
291   sampler_el->is_empty = EMPTY;
292
293   // I guess I don't need to call GNUNET_CRYPTO_hmac_derive_key()...
294   GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_STRONG,
295                              &(sampler_el->auth_key.key),
296                              GNUNET_CRYPTO_HASH_LENGTH);
297
298   sampler_el->last_client_request = GNUNET_TIME_UNIT_FOREVER_ABS;
299
300   /* We might want to keep the previous peer */
301
302   //GNUNET_CRYPTO_hmac(&sampler_el->auth_key, sampler_el->peer_id,
303   //                   sizeof(struct GNUNET_PeerIdentity),
304   //                   &sampler_el->peer_id_hash);
305
306   sampler_el->birth = GNUNET_TIME_absolute_get ();
307   sampler_el->num_peers = 0;
308   sampler_el->num_change = 0;
309 }
310
311
312 /**
313  * (Re)Initialise given Sampler with random min-wise independent function.
314  *
315  * In this implementation this means choosing an auth_key for later use in
316  * a hmac at random.
317  *
318  * @return a newly created RPS_SamplerElement which currently holds no id.
319  */
320   struct RPS_SamplerElement *
321 RPS_sampler_elem_create (void)
322 {
323   struct RPS_SamplerElement *s;
324   
325   s = GNUNET_new (struct RPS_SamplerElement);
326
327   RPS_sampler_elem_reinit (s);
328   LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: initialised with empty PeerID\n");
329
330   return s;
331 }
332
333
334 /**
335  * Input an PeerID into the given sampler.
336  */
337   static void
338 RPS_sampler_elem_next (struct RPS_SamplerElement *s_elem, const struct GNUNET_PeerIdentity *other,
339     RPS_sampler_insert_cb insert_cb, void *insert_cls,
340     RPS_sampler_remove_cb remove_cb, void *remove_cls)
341 {
342   struct GNUNET_HashCode other_hash;
343
344   s_elem->num_peers++;
345
346   if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (other, &(s_elem->peer_id)) )
347   {
348     LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:          Got PeerID %s\n",
349         GNUNET_i2s (other));
350     LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Have already PeerID %s\n",
351         GNUNET_i2s (&(s_elem->peer_id)));
352   }
353   else
354   {
355     GNUNET_CRYPTO_hmac(&s_elem->auth_key,
356         other,
357         sizeof(struct GNUNET_PeerIdentity),
358         &other_hash);
359
360     if ( EMPTY == s_elem->is_empty )
361     { 
362       LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Got PeerID %s; Simply accepting (was empty previously).\n",
363           GNUNET_i2s(other));
364       s_elem->peer_id = *other;
365       s_elem->peer_id_hash = other_hash;
366
367       if (NULL != sampler->insert_cb)
368         sampler->insert_cb (sampler->insert_cls, &(s_elem->peer_id));
369
370       s_elem->num_change++;
371     }
372     else if ( 0 > GNUNET_CRYPTO_hash_cmp (&other_hash, &s_elem->peer_id_hash) )
373     {
374       LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:            Got PeerID %s\n",
375           GNUNET_i2s (other));
376       LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Discarding old PeerID %s\n",
377           GNUNET_i2s (&s_elem->peer_id));
378
379       if ( NULL != sampler->remove_cb )
380       {
381         LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Removing old PeerID %s with the remove callback.\n",
382             GNUNET_i2s (&s_elem->peer_id));
383         sampler->remove_cb (sampler->remove_cls, &s_elem->peer_id);
384       }
385
386       s_elem->peer_id = *other;
387       s_elem->peer_id_hash = other_hash;
388
389       if ( NULL != sampler->insert_cb )
390       {
391         LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Inserting new PeerID %s with the insert callback.\n",
392             GNUNET_i2s (&s_elem->peer_id));
393         sampler->insert_cb(sampler->insert_cls, &s_elem->peer_id);
394       }
395
396       s_elem->num_change++;
397     }
398     else
399     {
400       LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:         Got PeerID %s\n",
401           GNUNET_i2s(other));
402       LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Keeping old PeerID %s\n",
403           GNUNET_i2s(&s_elem->peer_id));
404     }
405   }
406   s_elem->is_empty = NOT_EMPTY;
407 }
408
409
410 /**
411  * Grow or shrink the size of the sampler.
412  *
413  * @param new_size the new size of the sampler
414  */
415   void
416 RPS_sampler_resize (unsigned int new_size)
417 {
418   unsigned int old_size;
419   uint32_t i;
420   struct RPS_SamplerElement **rem_list;
421
422   // TODO check min and max size
423
424   old_size = sampler->sampler_size;
425
426   if (old_size > new_size)
427   { /* Shrinking */
428     /* Temporary store those to properly call the removeCB on those later */
429     rem_list = GNUNET_malloc ((old_size - new_size) * sizeof (struct RPS_SamplerElement *));
430     memcpy (rem_list,
431         &sampler->sampler_elements[new_size],
432         (old_size - new_size) * sizeof (struct RPS_SamplerElement *));
433
434     LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Shrinking sampler %d -> %d\n", old_size, new_size);
435     GNUNET_array_grow (sampler->sampler_elements, sampler->sampler_size, new_size);
436     LOG (GNUNET_ERROR_TYPE_DEBUG,
437         "SAMPLER: sampler->sampler_elements now points to %p\n",
438         sampler->sampler_elements);
439
440     for (i = 0 ; i < old_size - new_size ; i++)
441     {/* Remove unneeded rest */
442       LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Removing %" PRIX32 ". sampler\n", i);
443       if (NULL != sampler->remove_cb)
444         sampler->remove_cb (sampler->remove_cls, &rem_list[i]->peer_id);
445       GNUNET_free (rem_list[i]);
446     }
447     GNUNET_free (rem_list);
448   }
449   else if (old_size < new_size)
450   { /* Growing */
451     LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Growing sampler %d -> %d\n", old_size, new_size);
452     GNUNET_array_grow (sampler->sampler_elements, sampler->sampler_size, new_size);
453     LOG (GNUNET_ERROR_TYPE_DEBUG,
454         "SAMPLER: sampler->sampler_elements now points to %p\n",
455         sampler->sampler_elements);
456
457     for ( i = old_size ; i < new_size ; i++ )
458     { /* Add new sampler elements */
459       sampler->sampler_elements[i] = RPS_sampler_elem_create ();
460       if (NULL != sampler->insert_cb)
461         sampler->insert_cb (sampler->insert_cls, &sampler->sampler_elements[i]->peer_id);
462       LOG (GNUNET_ERROR_TYPE_DEBUG,
463           "SAMPLER: Added %" PRIX32 ". sampler, now pointing to %p, contains %s\n",
464           i, &sampler->sampler_elements[i], GNUNET_i2s (&sampler->sampler_elements[i]->peer_id));
465     }
466   }
467   else
468   {
469     LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Size remains the same -- nothing to do\n");
470     return;
471   }
472
473   GNUNET_assert(sampler->sampler_size == new_size);
474   LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Finished growing/shrinking.\n"); // remove
475 }
476
477
478 /**
479  * Initialise a tuple of sampler elements.
480  *
481  * @param init_size the size the sampler is initialised with
482  * @param id with which all newly created sampler elements are initialised
483  * @param ins_cb the callback that will be called on every PeerID that is 
484  *               newly inserted into a sampler element
485  * @param ins_cls the closure given to #ins_cb
486  * @param rem_cb the callback that will be called on every PeerID that is
487  *               removed from a sampler element
488  * @param rem_cls the closure given to #rem_cb
489  */
490   void
491 RPS_sampler_init (size_t init_size,
492     const struct GNUNET_PeerIdentity *id,
493     struct GNUNET_TIME_Relative max_round_interval,
494     RPS_sampler_insert_cb ins_cb, void *ins_cls,
495     RPS_sampler_remove_cb rem_cb, void *rem_cls)
496 {
497   //struct RPS_Sampler *sampler;
498   //uint32_t i;
499
500   /* Initialise context around extended sampler */
501   min_size = 10; // TODO make input to _samplers_init()
502   max_size = 1000; // TODO make input to _samplers_init()
503
504   sampler = GNUNET_new (struct RPS_Sampler);
505   sampler->sampler_size = 0;
506   sampler->sampler_elements = NULL;
507   sampler->max_round_interval = max_round_interval;
508   sampler->insert_cb = ins_cb;
509   sampler->insert_cls = ins_cls;
510   sampler->remove_cb = rem_cb;
511   sampler->remove_cls = rem_cls;
512   get_peer_tasks = GNUNET_CONTAINER_multihashmap_create (4, GNUNET_NO);
513   //sampler->sampler_elements = GNUNET_new_array(init_size, struct GNUNET_PeerIdentity);
514   //GNUNET_array_grow (sampler->sampler_elements, sampler->sampler_size, min_size);
515   RPS_sampler_resize (init_size);
516   RPS_sampler_update_list (id); // no super nice desing but ok for the moment
517
518   client_get_index = 0;
519
520   //GNUNET_assert (init_size == sampler->sampler_size);
521 }
522
523
524 /**
525  * A fuction to update every sampler in the given list
526  *
527  * @param id the PeerID that is put in the sampler
528  */
529   void
530 RPS_sampler_update_list (const struct GNUNET_PeerIdentity *id)
531 {
532   uint32_t i;
533
534   for ( i = 0 ; i < sampler->sampler_size ; i++ )
535     RPS_sampler_elem_next (sampler->sampler_elements[i], id,
536         sampler->insert_cb, sampler->insert_cls,
537         sampler->remove_cb, sampler->remove_cls);
538 }
539
540
541 /**
542  * Reinitialise all previously initialised sampler elements with the given value.
543  *
544  * Used to get rid of a PeerID.
545  *
546  * @param id the id of the sampler elements to update.
547  */
548   void
549 RPS_sampler_reinitialise_by_value (const struct GNUNET_PeerIdentity *id)
550 {
551   uint32_t i;
552
553   for ( i = 0 ; i < sampler->sampler_size ; i++ )
554   {
555     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity(id, &(sampler->sampler_elements[i]->peer_id)) )
556     {
557       LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Reinitialising sampler\n");
558       RPS_sampler_elem_reinit (sampler->sampler_elements[i]);
559     }
560   }
561 }
562
563
564 /**
565  * Get one random peer out of the sampled peers.
566  *
567  * We might want to reinitialise this sampler after giving the
568  * corrsponding peer to the client.
569  * Only used internally
570  */
571   const struct GNUNET_PeerIdentity * 
572 RPS_sampler_get_rand_peer_ ()
573 {
574   uint32_t r_index;
575   const struct GNUNET_PeerIdentity *peer; // do we have to malloc that?
576
577   // TODO implement extra logic
578
579   /**;
580    * Choose the r_index of the peer we want to return
581    * at random from the interval of the gossip list
582    */
583   r_index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
584       sampler->sampler_size);
585
586   //if ( EMPTY == sampler->sampler_elements[r_index]->is_empty )
587   //  // TODO schedule for later
588   //  peer = NULL;
589   //else
590     peer = &(sampler->sampler_elements[r_index]->peer_id);
591   //sampler->sampler_elements[r_index]->last_client_request = GNUNET_TIME_absolute_get();
592   LOG (GNUNET_ERROR_TYPE_DEBUG, "Sgrp: Returning PeerID %s\n", GNUNET_i2s(peer));
593
594   return peer;
595 }
596
597
598 /**
599  * Get n random peers out of the sampled peers.
600  *
601  * We might want to reinitialise this sampler after giving the
602  * corrsponding peer to the client.
603  * Random with or without consumption?
604  * Only used internally
605  */
606   const struct GNUNET_PeerIdentity *
607 RPS_sampler_get_n_rand_peers_ (uint32_t n)
608 {
609   if ( 0 == sampler->sampler_size )
610   {
611     LOG (GNUNET_ERROR_TYPE_DEBUG,
612         "Sgrp: List empty - Returning NULL\n");
613     return NULL;
614   }
615   else
616   {
617     // TODO check if we have too much (distinct) sampled peers
618     // If we are not ready yet maybe schedule for later
619     struct GNUNET_PeerIdentity *peers;
620     uint32_t i;
621
622     peers = GNUNET_malloc (n * sizeof(struct GNUNET_PeerIdentity));
623
624     for ( i = 0 ; i < n ; i++ ) {
625       //peers[i] = RPS_sampler_get_rand_peer_(sampler->sampler_elements);
626       memcpy (&peers[i], RPS_sampler_get_rand_peer_ (), sizeof (struct GNUNET_PeerIdentity));
627     }
628     return peers;
629   }
630 }
631
632
633 /**
634  * Get one random peer out of the sampled peers.
635  *
636  * We might want to reinitialise this sampler after giving the
637  * corrsponding peer to the client.
638  *
639  * @return a random PeerID of the PeerIDs previously put into the sampler.
640  */
641   void
642 //RPS_sampler_get_rand_peer (RPS_sampler_rand_peer_ready_cb cb,
643 //    void *cls, struct GNUNET_PeerIdentity *id)
644 RPS_sampler_get_rand_peer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
645 {
646   struct GetPeerCls *gpc;
647   struct RPS_SamplerElement *s_elem;
648   struct GNUNET_TIME_Relative last_request_diff;
649   struct GNUNET_HashCode *hash;
650   uint32_t tmp_client_get_index;
651   //struct GNUNET_TIME_Relative inv_last_request_diff;
652
653   LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Single peer was requested\n");
654
655   gpc = (struct GetPeerCls *) cls;
656   hash = GNUNET_new (struct GNUNET_HashCode);
657   if (0 < client_get_index)
658     tmp_client_get_index = client_get_index - 1;
659   else
660     tmp_client_get_index = sampler->sampler_size - 1;
661
662   LOG (GNUNET_ERROR_TYPE_DEBUG,
663       "SAMPLER: scheduling for later if index reaches %" PRIX32 " (sampler size: %" PRIX32 ".\n",
664       tmp_client_get_index, sampler->sampler_size);
665
666   do
667   { /* Get first non empty sampler */
668     if (tmp_client_get_index == client_get_index)
669     {
670       LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: reached tmp_index %" PRIX32 ".\n", client_get_index);
671       gpc->get_peer_task = GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
672                                                          &RPS_sampler_get_rand_peer,
673                                                          cls);
674       return;
675     }
676
677     *gpc->id = sampler->sampler_elements[client_get_index]->peer_id;
678
679     RPS_sampler_elem_reinit (sampler->sampler_elements[client_get_index]);
680     if ( client_get_index == sampler->sampler_size - 1 )
681       client_get_index = 0;
682     else
683       client_get_index++;
684     LOG (GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: incremented index to %" PRIX32 ".\n", client_get_index);
685   } while (EMPTY == sampler->sampler_elements[client_get_index]->is_empty);
686
687   s_elem = sampler->sampler_elements[client_get_index];
688
689   /* Check whether we may use this sampler to give it back to the client */
690   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us != s_elem->last_client_request.abs_value_us)
691   {
692     last_request_diff = GNUNET_TIME_absolute_get_difference (s_elem->last_client_request,
693                                                              GNUNET_TIME_absolute_get ());
694     /* We're not going to give it back now if it was already requested by a client this round */
695     if (last_request_diff.rel_value_us < sampler->max_round_interval.rel_value_us)
696     {
697       LOG (GNUNET_ERROR_TYPE_DEBUG,
698           "SAMPLER: Last client request on this sampler was less than max round interval ago -- scheduling for later\n");
699       ///* How many time remains untile the next round has started? */
700       //inv_last_request_diff = GNUNET_TIME_absolute_get_difference (last_request_diff,
701       //                                                             sampler->max_round_interval);
702       // add a little delay
703       /* Schedule it one round later */
704       gpc->get_peer_task = GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
705                                               &RPS_sampler_get_rand_peer,
706                                               cls);
707       return;
708     }
709     // TODO add other reasons to wait here
710   }
711
712   GNUNET_CRYPTO_hash (&gpc->get_peer_task, sizeof (struct GNUNET_SCHEDULER_Task *), hash);
713   if (GNUNET_NO == GNUNET_CONTAINER_multihashmap_remove (get_peer_tasks, hash, gpc->get_peer_task))
714       LOG (GNUNET_ERROR_TYPE_WARNING, "SAMPLER: Key to remove is not in the hashmap\n");
715   GNUNET_free (gpc->get_peer_task);
716
717   s_elem->last_client_request = GNUNET_TIME_absolute_get ();
718
719   gpc->cb (gpc->cb_cls, gpc->id);
720 }
721
722
723 /**
724  * Get n random peers out of the sampled peers.
725  *
726  * We might want to reinitialise this sampler after giving the
727  * corrsponding peer to the client.
728  * Random with or without consumption?
729  *
730  * @param cb callback that will be called once the ids are ready.
731  * @param cls closure given to @a cb
732  * @param num_peers the number of peers requested
733  */
734   void
735 RPS_sampler_get_n_rand_peers (RPS_sampler_n_rand_peers_ready_cb cb,
736     void *cls, uint32_t num_peers)
737 {
738   if ( 0 == sampler->sampler_size )
739   {
740     LOG (GNUNET_ERROR_TYPE_DEBUG,
741         "Sgrp: List empty - Returning NULL\n");
742     cb (cls, NULL, 0);
743   }
744   else
745   {
746     // TODO check if we have too much (distinct) sampled peers
747     // If we are not ready yet maybe schedule for later
748     uint32_t i;
749     struct RPS_GetNRandPeersReadyCls *cb_cls;
750     struct GetPeerCls *gpc;
751     struct GNUNET_HashCode *hash;
752     
753     hash = GNUNET_new (struct GNUNET_HashCode);
754
755     cb_cls = GNUNET_new (struct RPS_GetNRandPeersReadyCls);
756     cb_cls->num_peers = num_peers;
757     cb_cls->cur_num_peers = 0;
758     cb_cls->ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
759     cb_cls->callback = cb;
760     cb_cls->cls = cls;
761
762     LOG (GNUNET_ERROR_TYPE_DEBUG,
763         "SAMPLER: Scheduling requests for %" PRIX32 " peers\n", num_peers);
764
765     for ( i = 0 ; i < num_peers ; i++ )
766     {
767       gpc = GNUNET_new (struct GetPeerCls);
768       gpc->cb = RPS_sampler_get_n_rand_peers_ready_cb;
769       gpc->cb_cls = cb_cls;
770       gpc->id = &cb_cls->ids[i];
771
772       // maybe add a little delay
773       gpc->get_peer_task = GNUNET_SCHEDULER_add_now (&RPS_sampler_get_rand_peer, gpc);
774       GNUNET_CRYPTO_hash (&gpc->get_peer_task, sizeof (struct GNUNET_SCHEDULER_Task *), hash);
775       (void) GNUNET_CONTAINER_multihashmap_put (get_peer_tasks, hash, gpc->get_peer_task,
776                                                 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE);
777       //RPS_sampler_get_rand_peer (RPS_sampler_get_n_rand_peers_ready_cb,
778       //    cb_cls, &peers[i]);
779     }
780   }
781 }
782
783
784 /**
785  * Counts how many Samplers currently hold a given PeerID.
786  *
787  * @param id the PeerID to count.
788  *
789  * @return the number of occurrences of id.
790  */
791   uint32_t
792 RPS_sampler_count_id (const struct GNUNET_PeerIdentity *id)
793 {
794   uint32_t count;
795   uint32_t i;
796
797   count = 0;
798   for ( i = 0 ; i < sampler->sampler_size ; i++ )
799   {
800     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity (&sampler->sampler_elements[i]->peer_id, id) 
801         && EMPTY != sampler->sampler_elements[i]->is_empty)
802       count++;
803   }
804   return count;
805 }
806
807
808 /**
809  * Callback to iterate over the hashmap to cancle the get_peer_tasks.
810  */
811   int
812 clear_get_peer_tasks (void *cls, const struct GNUNET_HashCode *key, void *value)
813 {
814   struct GNUNET_SCHEDULER_Task *task;
815
816   task = (struct GNUNET_SCHEDULER_Task *) value;
817   GNUNET_SCHEDULER_cancel (task);
818
819   GNUNET_CONTAINER_multihashmap_remove (get_peer_tasks, key, value);
820   
821   return GNUNET_YES;
822 }
823
824
825 /**
826  * Cleans the sampler.
827  */
828   void
829 RPS_sampler_destroy ()
830 {
831   if (GNUNET_SYSERR == GNUNET_CONTAINER_multihashmap_iterate (get_peer_tasks,
832                                                               clear_get_peer_tasks,
833                                                               NULL))
834     LOG (GNUNET_ERROR_TYPE_WARNING, "SAMPLER: iteration over hashmap was cancelled\n");
835   GNUNET_CONTAINER_multihashmap_destroy (get_peer_tasks);
836   RPS_sampler_resize (0);
837   GNUNET_array_grow (sampler->sampler_elements, sampler->sampler_size, 0);
838 }
839
840 /* end of gnunet-service-rps.c */