-using "view" helper in rps service
[oweals/gnunet.git] / src / rps / gnunet-service-rps_sampler.c
index f851ac9656e9756682b0d38fee5b571b4ed9da89..b65dd7c47f3cdbaca29d4cccf78f9f67feab55f9 100644 (file)
@@ -14,8 +14,8 @@
 
      You should have received a copy of the GNU General Public License
      along with GNUnet; see the file COPYING.  If not, write to the
-     Free Software Foundation, Inc., 59 Temple Place - Suite 330,
-     Boston, MA 02111-1307, USA.
+     Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+     Boston, MA 02110-1301, USA.
 */
 
 /**
 #include "rps.h"
 
 #include "gnunet-service-rps_sampler.h"
+#include "gnunet-service-rps_sampler_elem.h"
 
 #include <math.h>
 #include <inttypes.h>
 
+#include "rps-test_util.h"
+
 #define LOG(kind, ...) GNUNET_log_from(kind,"rps-sampler",__VA_ARGS__)
 
+
 // multiple 'clients'?
 
 // TODO check for overflows
 
 // TODO care about invalid input of the caller (size 0 or less...)
 
-enum RPS_SamplerEmpty
-{
-  NOT_EMPTY = 0x0,
-      EMPTY = 0x1
-};
+/**
+ * Callback that is called from _get_rand_peer() when the PeerID is ready.
+ *
+ * @param cls the closure given alongside this function.
+ * @param id the PeerID that was returned
+ */
+typedef void
+(*RPS_sampler_rand_peer_ready_cont) (void *cls,
+                                     const struct GNUNET_PeerIdentity *id);
+
 
 /**
- * A sampler element sampling one PeerID at a time.
+ * Closure for #sampler_mod_get_rand_peer() and #sampler_get_rand_peer
  */
-struct RPS_SamplerElement
+struct GetPeerCls
 {
   /**
-   * Min-wise linear permutation used by this sampler.
-   *
-   * This is an key later used by a hmac.
+   * DLL
    */
-  struct GNUNET_CRYPTO_AuthKey auth_key;
+  struct GetPeerCls *next;
+  struct GetPeerCls *prev;
 
   /**
-   * The PeerID this sampler currently samples.
+   * The #RPS_SamplerRequestHandle this single request belongs to.
    */
-  struct GNUNET_PeerIdentity peer_id;
+  struct RPS_SamplerRequestHandle *req_handle;
 
   /**
-   * The according hash value of this PeerID.
+   * The task for this function.
    */
-  struct GNUNET_HashCode peer_id_hash;
-
+  struct GNUNET_SCHEDULER_Task *get_peer_task;
 
   /**
-   * Time of last request.
+   * The callback
    */
-  struct GNUNET_TIME_Absolute last_client_request;
+  RPS_sampler_rand_peer_ready_cont cont;
 
   /**
-   * Flag that indicates that we are not holding a valid PeerID right now.
+   * The closure to the callback @e cont
    */
-  enum RPS_SamplerEmpty is_empty;
+  void *cont_cls;
 
   /**
-   * 'Birth'
+   * The address of the id to be stored at
    */
-  struct GNUNET_TIME_Absolute birth;
+  struct GNUNET_PeerIdentity *id;
+};
 
-  /**
-   * How many times a PeerID was put in this sampler.
-   */
-  uint32_t num_peers;
 
-  /**
-   * How many times this sampler changed the peer_id.
-   */
-  uint32_t num_change;
+/**
+ * Type of function used to differentiate between modified and not modified
+ * Sampler.
+ */
+typedef void
+(*RPS_get_peers_type) (void *cls,
+                       const struct GNUNET_SCHEDULER_TaskContext *tc);
 
-  /**
-   * The file name this sampler element should log to
-   */
-  #ifdef TO_FILE
-  char *file_name;
-  #endif /* TO_FILE */
-};
+/**
+ * Get one random peer out of the sampled peers.
+ *
+ * We might want to reinitialise this sampler after giving the
+ * corrsponding peer to the client.
+ * Only used internally
+ */
+static void
+sampler_get_rand_peer (void *cls,
+                        const struct GNUNET_SCHEDULER_TaskContext *tc);
+
+/**
+ * Get one random peer out of the sampled peers.
+ *
+ * We might want to reinitialise this sampler after giving the
+ * corrsponding peer to the client.
+ */
+static void
+sampler_mod_get_rand_peer (void *cls,
+                       const struct GNUNET_SCHEDULER_TaskContext *tc);
 
 
 /**
@@ -124,17 +144,29 @@ struct RPS_Sampler
   //size_t size;
 
   /**
-   * All Samplers in one array.
+   * All sampler elements in one array.
    */
   struct RPS_SamplerElement **sampler_elements;
 
   /**
-   * Max time a round takes
+   * Maximum time a round takes
    *
    * Used in the context of RPS
    */
   struct GNUNET_TIME_Relative max_round_interval;
 
+  /**
+   * Stores the function to return peers. Which one it is depends on whether
+   * the Sampler is the modified one or not.
+   */
+  RPS_get_peers_type get_peers;
+
+  /**
+   * Head and tail for the DLL to store the #RPS_SamplerRequestHandle
+   */
+  struct RPS_SamplerRequestHandle *req_handle_head;
+  struct RPS_SamplerRequestHandle *req_handle_tail;
+
   #ifdef TO_FILE
   /**
    * File name to log to
@@ -146,8 +178,14 @@ struct RPS_Sampler
 /**
  * Closure to _get_n_rand_peers_ready_cb()
  */
-struct NRandPeersReadyCls
+struct RPS_SamplerRequestHandle
 {
+  /**
+   * DLL
+   */
+  struct RPS_SamplerRequestHandle *next;
+  struct RPS_SamplerRequestHandle *prev;
+
   /**
    * Number of peers we are waiting for.
    */
@@ -164,68 +202,27 @@ struct NRandPeersReadyCls
   struct GNUNET_PeerIdentity *ids;
 
   /**
-   * Callback to be called when all ids are available.
-   */
-  RPS_sampler_n_rand_peers_ready_cb callback;
-
-  /**
-   * Closure given to the callback
-   */
-  void *cls;
-};
-
-/**
- * Callback that is called from _get_rand_peer() when the PeerID is ready.
- *
- * @param cls the closure given alongside this function.
- * @param id the PeerID that was returned
- */
-typedef void
-(*RPS_sampler_rand_peer_ready_cont) (void *cls,
-        const struct GNUNET_PeerIdentity *id);
-
-/**
- * Closure for #sampler_get_rand_peer()
- */
-struct GetPeerCls
-{
-  /**
-   * DLL
-   */
-  struct GetPeerCls *next;
-
-  /**
-   * DLL
+   * Head and tail for the DLL to store the tasks for single requests
    */
-  struct GetPeerCls *prev;
+  struct GetPeerCls *gpc_head;
+  struct GetPeerCls *gpc_tail;
 
   /**
-   * The sampler this function operates on.
+   * Sampler.
    */
   struct RPS_Sampler *sampler;
 
   /**
-   * The task for this function.
-   */
-  struct GNUNET_SCHEDULER_Task *get_peer_task;
-
-  /**
-   * The callback
-   */
-  RPS_sampler_rand_peer_ready_cont cont;
-
-  /**
-   * The closure to the callback @e cont
+   * Callback to be called when all ids are available.
    */
-  void *cont_cls;
+  RPS_sampler_n_rand_peers_ready_cb callback;
 
   /**
-   * The address of the id to be stored at
+   * Closure given to the callback
    */
-  struct GNUNET_PeerIdentity *id;
+  void *cls;
 };
 
-
 ///**
 // * Global sampler variable.
 // */
@@ -253,76 +250,6 @@ static size_t max_size;
 static uint32_t client_get_index;
 
 
-#ifdef TO_FILE
-/**
- * This function is used to facilitate writing important information to disk
- */
-#define to_file(file_name, ...) do {char tmp_buf[512];\
-  int size;\
-  size = GNUNET_snprintf(tmp_buf,sizeof(tmp_buf),__VA_ARGS__);\
-  if (0 > size)\
-    LOG (GNUNET_ERROR_TYPE_WARNING,\
-         "Failed to create tmp_buf\n");\
-  else\
-    to_file_(file_name,tmp_buf);\
-} while (0);
-
-static void
-to_file_ (char *file_name, char *line)
-{
-  struct GNUNET_DISK_FileHandle *f;
-  char output_buffer[512];
-  //size_t size;
-  int size;
-  size_t size2;
-
-
-  if (NULL == (f = GNUNET_DISK_file_open (file_name,
-                                          GNUNET_DISK_OPEN_APPEND |
-                                          GNUNET_DISK_OPEN_WRITE |
-                                          GNUNET_DISK_OPEN_CREATE,
-                                          GNUNET_DISK_PERM_USER_WRITE)))
-  {
-    LOG (GNUNET_ERROR_TYPE_WARNING,
-         "Not able to open file %s\n",
-         file_name);
-    return;
-  }
-  size = GNUNET_snprintf (output_buffer,
-                          sizeof (output_buffer),
-                          "%llu %s\n",
-                          GNUNET_TIME_absolute_get ().abs_value_us,
-                          line);
-  if (0 > size)
-  {
-    LOG (GNUNET_ERROR_TYPE_WARNING,
-         "Failed to write string to buffer (size: %i)\n",
-         size);
-    return;
-  }
-
-  size2 = GNUNET_DISK_file_write (f, output_buffer, size);
-  if (size != size2)
-  {
-    LOG (GNUNET_ERROR_TYPE_WARNING,
-         "Unable to write to file! (Size: %u, size2: %u)\n",
-         size,
-         size2);
-    return;
-  }
-
-  if (GNUNET_YES != GNUNET_DISK_file_close (f))
-    LOG (GNUNET_ERROR_TYPE_WARNING,
-         "Unable to close file\n");
-}
-#endif /* TO_FILE */
-
-
-/** FIXME document */
-static struct GetPeerCls *gpc_head;
-static struct GetPeerCls *gpc_tail;
-
-
 /**
  * Callback to _get_rand_peer() used by _get_n_rand_peers().
  *
@@ -333,177 +260,24 @@ static void
 check_n_peers_ready (void *cls,
     const struct GNUNET_PeerIdentity *id)
 {
-  struct NRandPeersReadyCls *n_peers_cls = cls;
+  struct RPS_SamplerRequestHandle *req_handle = cls;
 
-  n_peers_cls->cur_num_peers++;
+  req_handle->cur_num_peers++;
   LOG (GNUNET_ERROR_TYPE_DEBUG,
       "Got %" PRIX32 ". of %" PRIX32 " peers\n",
-      n_peers_cls->cur_num_peers, n_peers_cls->num_peers);
+      req_handle->cur_num_peers, req_handle->num_peers);
 
-  if (n_peers_cls->num_peers == n_peers_cls->cur_num_peers)
+  if (req_handle->num_peers == req_handle->cur_num_peers)
   { /* All peers are ready -- return those to the client */
-    GNUNET_assert (NULL != n_peers_cls->callback);
+    GNUNET_assert (NULL != req_handle->callback);
 
     LOG (GNUNET_ERROR_TYPE_DEBUG,
         "returning %" PRIX32 " peers to the client\n",
-        n_peers_cls->num_peers);
-    n_peers_cls->callback (n_peers_cls->cls, n_peers_cls->ids, n_peers_cls->num_peers);
-
-    GNUNET_free (n_peers_cls);
-  }
-}
-
-
-/**
- * Reinitialise a previously initialised sampler element.
- *
- * @param sampler pointer to the memory that keeps the value.
- */
-  static void
-RPS_sampler_elem_reinit (struct RPS_SamplerElement *sampler_el)
-{
-  sampler_el->is_empty = EMPTY;
-
-  // I guess I don't need to call GNUNET_CRYPTO_hmac_derive_key()...
-  GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_STRONG,
-                             &(sampler_el->auth_key.key),
-                             GNUNET_CRYPTO_HASH_LENGTH);
+        req_handle->num_peers);
+    req_handle->callback (req_handle->cls, req_handle->ids, req_handle->num_peers);
 
-  #ifdef TO_FILE
-  /* Create a file(-name) to store internals to */
-  int size;
-  char *end;
-  char *buf;
-  char name_buf[512];
-  size_t keylen = (sizeof (struct GNUNET_CRYPTO_AuthKey)) * 8;
-
-  if (keylen % 5 > 0)
-    keylen += 5 - keylen % 5;
-  keylen /= 5;
-  buf = GNUNET_malloc (keylen + 1);
-
-  end = GNUNET_STRINGS_data_to_string (&(sampler_el->auth_key.key),
-                                       sizeof (struct GNUNET_CRYPTO_AuthKey),
-                                       buf,
-                                       keylen);
-
-  if (NULL == end)
-  {
-    GNUNET_free (buf);
-    GNUNET_break (0);
-  }
-  else
-  {
-    *end = '\0';
+    RPS_sampler_request_cancel (req_handle);
   }
-
-  size = GNUNET_snprintf (name_buf, sizeof (name_buf), "sampler_el-%s-", buf);
-  if (0 > size)
-    LOG (GNUNET_ERROR_TYPE_WARNING, "Failed to create name_buf\n");
-
-  if (NULL == (sampler_el->file_name = GNUNET_DISK_mktemp (name_buf)))
-    LOG (GNUNET_ERROR_TYPE_WARNING, "Could not create file\n");
-  #endif /* TO_FILE */
-
-  sampler_el->last_client_request = GNUNET_TIME_UNIT_FOREVER_ABS;
-
-  sampler_el->birth = GNUNET_TIME_absolute_get ();
-  sampler_el->num_peers = 0;
-  sampler_el->num_change = 0;
-}
-
-
-/**
- * (Re)Initialise given Sampler with random min-wise independent function.
- *
- * In this implementation this means choosing an auth_key for later use in
- * a hmac at random.
- *
- * @return a newly created RPS_SamplerElement which currently holds no id.
- */
-  struct RPS_SamplerElement *
-RPS_sampler_elem_create (void)
-{
-  struct RPS_SamplerElement *s;
-
-  s = GNUNET_new (struct RPS_SamplerElement);
-
-  RPS_sampler_elem_reinit (s);
-
-  return s;
-}
-
-
-/**
- * Input an PeerID into the given sampler element.
- *
- * @param sampler the sampler the @a s_elem belongs to.
- *                Needed to know the
- */
-static void
-RPS_sampler_elem_next (struct RPS_SamplerElement *s_elem,
-                       struct RPS_Sampler *sampler,
-                       const struct GNUNET_PeerIdentity *other)
-{
-  struct GNUNET_HashCode other_hash;
-
-  s_elem->num_peers++;
-
-  #ifdef TO_FILE
-  to_file (s_elem->file_name,
-           "Got id %s",
-           GNUNET_i2s_full (other));
-  #endif /* TO_FILE */
-
-  if (0 == GNUNET_CRYPTO_cmp_peer_identity (other, &(s_elem->peer_id)))
-  {
-    LOG (GNUNET_ERROR_TYPE_DEBUG, "         Got PeerID %s\n",
-        GNUNET_i2s (other));
-    LOG (GNUNET_ERROR_TYPE_DEBUG, "Have already PeerID %s\n",
-        GNUNET_i2s (&(s_elem->peer_id)));
-  }
-  else
-  {
-    GNUNET_CRYPTO_hmac(&s_elem->auth_key,
-        other,
-        sizeof(struct GNUNET_PeerIdentity),
-        &other_hash);
-
-    if (EMPTY == s_elem->is_empty)
-    {
-      LOG (GNUNET_ERROR_TYPE_DEBUG,
-           "Got PeerID %s; Simply accepting (was empty previously).\n",
-           GNUNET_i2s(other));
-      s_elem->peer_id = *other;
-      s_elem->peer_id_hash = other_hash;
-
-      s_elem->num_change++;
-    }
-    else if (0 > GNUNET_CRYPTO_hash_cmp (&other_hash, &s_elem->peer_id_hash))
-    {
-      LOG (GNUNET_ERROR_TYPE_DEBUG, "           Got PeerID %s\n",
-          GNUNET_i2s (other));
-      LOG (GNUNET_ERROR_TYPE_DEBUG, "Discarding old PeerID %s\n",
-          GNUNET_i2s (&s_elem->peer_id));
-      s_elem->peer_id = *other;
-      s_elem->peer_id_hash = other_hash;
-
-      s_elem->num_change++;
-    }
-    else
-    {
-      LOG (GNUNET_ERROR_TYPE_DEBUG, "        Got PeerID %s\n",
-          GNUNET_i2s (other));
-      LOG (GNUNET_ERROR_TYPE_DEBUG, "Keeping old PeerID %s\n",
-          GNUNET_i2s (&s_elem->peer_id));
-    }
-  }
-  s_elem->is_empty = NOT_EMPTY;
-  #ifdef TO_FILE
-  to_file (s_elem->file_name,
-           "Now holding %s",
-           GNUNET_i2s_full (&s_elem->peer_id));
-  #endif /* TO_FILE */
 }
 
 
@@ -538,13 +312,12 @@ sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
 
   if (old_size > new_size)
   { /* Shrinking */
-    /* Temporary store those to properly call the removeCB on those later */
 
     LOG (GNUNET_ERROR_TYPE_DEBUG,
          "Shrinking sampler %d -> %d\n",
          old_size,
          new_size);
-    #ifdef TO_FILE
+
     to_file (sampler->file_name,
          "Shrinking sampler %d -> %d",
          old_size,
@@ -557,13 +330,13 @@ sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
                i,
                sampler->sampler_elements[i]->file_name);
     }
-    #endif /* TO_FILE */
+
     GNUNET_array_grow (sampler->sampler_elements,
-        sampler->sampler_size,
-        new_size);
+                       sampler->sampler_size,
+                       new_size);
     LOG (GNUNET_ERROR_TYPE_DEBUG,
-        "sampler->sampler_elements now points to %p\n",
-        sampler->sampler_elements);
+         "sampler->sampler_elements now points to %p\n",
+         sampler->sampler_elements);
 
   }
   else if (old_size < new_size)
@@ -572,12 +345,12 @@ sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
          "Growing sampler %d -> %d\n",
          old_size,
          new_size);
-    #ifdef TO_FILE
+
     to_file (sampler->file_name,
          "Growing sampler %d -> %d",
          old_size,
          new_size);
-    #endif /* TO_FILE */
+
     GNUNET_array_grow (sampler->sampler_elements,
         sampler->sampler_size,
         new_size);
@@ -585,12 +358,11 @@ sampler_resize (struct RPS_Sampler *sampler, unsigned int new_size)
     for (i = old_size ; i < new_size ; i++)
     { /* Add new sampler elements */
       sampler->sampler_elements[i] = RPS_sampler_elem_create ();
-      #ifdef TO_FILE
+
       to_file (sampler->file_name,
                "+%" PRIu32 ": %s",
                i,
                sampler->sampler_elements[i]->file_name);
-      #endif /* TO_FILE */
     }
   }
   else
@@ -634,20 +406,14 @@ sampler_empty (struct RPS_Sampler *sampler)
  * Initialise a tuple of sampler elements.
  *
  * @param init_size the size the sampler is initialised with
- * @param ins_cb the callback that will be called on every PeerID that is
- *               newly inserted into a sampler element
- * @param ins_cls the closure given to #ins_cb
- * @param rem_cb the callback that will be called on every PeerID that is
- *               removed from a sampler element
- * @param rem_cls the closure given to #rem_cb
+ * @param max_round_interval maximum time a round takes
  * @return a handle to a sampler that consists of sampler elements.
  */
 struct RPS_Sampler *
 RPS_sampler_init (size_t init_size,
-    struct GNUNET_TIME_Relative max_round_interval)
+                  struct GNUNET_TIME_Relative max_round_interval)
 {
   struct RPS_Sampler *sampler;
-  //uint32_t i;
 
   /* Initialise context around extended sampler */
   min_size = 10; // TODO make input to _samplers_init()
@@ -656,14 +422,15 @@ RPS_sampler_init (size_t init_size,
   sampler = GNUNET_new (struct RPS_Sampler);
 
   #ifdef TO_FILE
-  if (NULL == (sampler->file_name = GNUNET_DISK_mktemp ("sampler-")))
-    LOG (GNUNET_ERROR_TYPE_WARNING,
-         "Could not create file\n");
+  sampler->file_name = create_file ("sampler-");
+
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+       "Initialised sampler %s\n",
+       sampler->file_name);
   #endif /* TO_FILE */
 
-  sampler->sampler_size = 0;
-  sampler->sampler_elements = NULL;
   sampler->max_round_interval = max_round_interval;
+  sampler->get_peers = sampler_get_rand_peer;
   //sampler->sampler_elements = GNUNET_new_array(init_size, struct GNUNET_PeerIdentity);
   //GNUNET_array_grow (sampler->sampler_elements, sampler->sampler_size, min_size);
   RPS_sampler_resize (sampler, init_size);
@@ -674,6 +441,31 @@ RPS_sampler_init (size_t init_size,
   return sampler;
 }
 
+/**
+ * Initialise a modified tuple of sampler elements.
+ *
+ * @param init_size the size the sampler is initialised with
+ * @param max_round_interval maximum time a round takes
+ * @return a handle to a sampler that consists of sampler elements.
+ */
+struct RPS_Sampler *
+RPS_sampler_mod_init (size_t init_size,
+                      struct GNUNET_TIME_Relative max_round_interval)
+{
+  struct RPS_Sampler *sampler;
+
+  sampler = RPS_sampler_init (init_size, max_round_interval);
+  sampler->get_peers = sampler_mod_get_rand_peer;
+
+  LOG (GNUNET_ERROR_TYPE_DEBUG,
+       "Initialised modified sampler %s\n",
+       sampler->file_name);
+  to_file (sampler->file_name,
+           "This is a modified sampler");
+
+  return sampler;
+}
+
 
 /**
  * A fuction to update every sampler in the given list
@@ -687,18 +479,16 @@ RPS_sampler_update (struct RPS_Sampler *sampler,
 {
   uint32_t i;
 
-  #ifdef TO_FILE
   to_file (sampler->file_name,
            "Got %s",
            GNUNET_i2s_full (id));
-  #endif /* TO_FILE */
 
   for (i = 0 ; i < sampler->sampler_size ; i++)
   {
     RPS_sampler_elem_next (sampler->sampler_elements[i],
-                           sampler,
                            id);
   }
+
 }
 
 
@@ -715,12 +505,17 @@ RPS_sampler_reinitialise_by_value (struct RPS_Sampler *sampler,
                                    const struct GNUNET_PeerIdentity *id)
 {
   uint32_t i;
+  struct RPS_SamplerElement *trash_entry;
 
   for ( i = 0 ; i < sampler->sampler_size ; i++ )
   {
     if ( 0 == GNUNET_CRYPTO_cmp_peer_identity(id, &(sampler->sampler_elements[i]->peer_id)) )
     {
       LOG (GNUNET_ERROR_TYPE_DEBUG, "Reinitialising sampler\n");
+      trash_entry = GNUNET_new (struct RPS_SamplerElement);
+      *trash_entry = *(sampler->sampler_elements[i]);
+      to_file (trash_entry->file_name,
+               "--- non-active");
       RPS_sampler_elem_reinit (sampler->sampler_elements[i]);
     }
   }
@@ -735,36 +530,48 @@ RPS_sampler_reinitialise_by_value (struct RPS_Sampler *sampler,
  * Only used internally
  */
 static void
-sampler_get_rand_peer2 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
+sampler_get_rand_peer (void *cls,
+                        const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
   struct GetPeerCls *gpc = cls;
   uint32_t r_index;
+  struct RPS_Sampler *sampler;
 
   gpc->get_peer_task = NULL;
-  GNUNET_CONTAINER_DLL_remove (gpc_head, gpc_tail, gpc);
   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
     return;
+  sampler = gpc->req_handle->sampler;
 
   /**;
    * Choose the r_index of the peer we want to return
    * at random from the interval of the gossip list
    */
   r_index = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_STRONG,
-      gpc->sampler->sampler_size);
+      sampler->sampler_size);
 
-  if ( EMPTY == gpc->sampler->sampler_elements[r_index]->is_empty )
+  if (EMPTY == sampler->sampler_elements[r_index]->is_empty)
   {
-    gpc->get_peer_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply(
-                                                                   GNUNET_TIME_UNIT_SECONDS,
-                                                                   .1),
-                                                       &sampler_get_rand_peer2,
-                                                       cls);
+    //LOG (GNUNET_ERROR_TYPE_DEBUG,
+    //     "Not returning randomly selected, empty PeerID. - Rescheduling.\n");
+
+    /* FIXME no active wait - get notified, when new id arrives?
+     * Might also be a freshly emptied one. Others might still contain ids.
+     * Counter?
+     */
+    gpc->get_peer_task =
+      GNUNET_SCHEDULER_add_delayed (
+          GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 1),
+          &sampler_get_rand_peer,
+          cls);
     return;
   }
 
-  *gpc->id = gpc->sampler->sampler_elements[r_index]->peer_id;
-
+  GNUNET_CONTAINER_DLL_remove (gpc->req_handle->gpc_head,
+                               gpc->req_handle->gpc_tail,
+                               gpc);
+  *gpc->id = sampler->sampler_elements[r_index]->peer_id;
   gpc->cont (gpc->cont_cls, gpc->id);
+
   GNUNET_free (gpc);
 }
 
@@ -776,66 +583,38 @@ sampler_get_rand_peer2 (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc
  * corrsponding peer to the client.
  */
 static void
-sampler_get_rand_peer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
+sampler_mod_get_rand_peer (void *cls,
+                       const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
   struct GetPeerCls *gpc = cls;
-  struct GNUNET_PeerIdentity tmp_id;
-  unsigned int empty_flag;
   struct RPS_SamplerElement *s_elem;
   struct GNUNET_TIME_Relative last_request_diff;
-  uint32_t tmp_client_get_index;
+  struct RPS_Sampler *sampler;
 
   gpc->get_peer_task = NULL;
   if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
     return;
+  sampler = gpc->req_handle->sampler;
 
   LOG (GNUNET_ERROR_TYPE_DEBUG, "Single peer was requested\n");
 
+  /* Cycle the #client_get_index one step further */
+  client_get_index = (client_get_index + 1) % sampler->sampler_size;
 
-  /* Store the next #client_get_index to check whether we cycled over the whole list */
-  if (0 < client_get_index)
-    tmp_client_get_index = client_get_index - 1;
-  else
-    tmp_client_get_index = gpc->sampler->sampler_size - 1;
-
-  LOG (GNUNET_ERROR_TYPE_DEBUG,
-      "sched for later if index reaches %" PRIX32 " (sampler size: %" PRIX32 ").\n",
-      tmp_client_get_index, gpc->sampler->sampler_size);
-
-  do
-  { /* Get first non empty sampler */
-    if (tmp_client_get_index == client_get_index)
-    { /* We once cycled over the whole list */
-      LOG (GNUNET_ERROR_TYPE_DEBUG, "reached tmp_index %" PRIX32 ".\n",
-           client_get_index);
-      GNUNET_assert (NULL == gpc->get_peer_task);
-      gpc->get_peer_task =
-        GNUNET_SCHEDULER_add_delayed (gpc->sampler->max_round_interval,
-                                      &sampler_get_rand_peer,
-                                      cls);
-      return;
-    }
-
-    tmp_id = gpc->sampler->sampler_elements[client_get_index]->peer_id;
-    empty_flag = gpc->sampler->sampler_elements[client_get_index]->is_empty;
-    RPS_sampler_elem_reinit (gpc->sampler->sampler_elements[client_get_index]);
-    if (EMPTY != empty_flag)
-      RPS_sampler_elem_next (gpc->sampler->sampler_elements[client_get_index],
-                             gpc->sampler,
-                             &tmp_id);
-
-    /* Cycle the #client_get_index one step further */
-    if ( client_get_index == gpc->sampler->sampler_size - 1 )
-      client_get_index = 0;
-    else
-      client_get_index++;
-
-    LOG (GNUNET_ERROR_TYPE_DEBUG, "incremented index to %" PRIX32 ".\n",
-         client_get_index);
-  } while (EMPTY == gpc->sampler->sampler_elements[client_get_index]->is_empty);
-
-  s_elem = gpc->sampler->sampler_elements[client_get_index];
+  s_elem = sampler->sampler_elements[client_get_index];
   *gpc->id = s_elem->peer_id;
+  GNUNET_assert (NULL != s_elem);
+
+  if (EMPTY == s_elem->is_empty)
+  {
+    LOG (GNUNET_ERROR_TYPE_DEBUG, "Sampler_mod element empty, rescheduling.\n");
+    GNUNET_assert (NULL == gpc->get_peer_task);
+    gpc->get_peer_task =
+      GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
+                                    &sampler_mod_get_rand_peer,
+                                    cls);
+    return;
+  }
 
   /* Check whether we may use this sampler to give it back to the client */
   if (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us != s_elem->last_client_request.abs_value_us)
@@ -845,7 +624,7 @@ sampler_get_rand_peer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
                                            GNUNET_TIME_absolute_get ());
     /* We're not going to give it back now if it was
      * already requested by a client this round */
-    if (last_request_diff.rel_value_us < gpc->sampler->max_round_interval.rel_value_us)
+    if (last_request_diff.rel_value_us < sampler->max_round_interval.rel_value_us)
     {
       LOG (GNUNET_ERROR_TYPE_DEBUG,
           "Last client request on this sampler was less than max round interval ago -- scheduling for later\n");
@@ -857,8 +636,8 @@ sampler_get_rand_peer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
       /* Schedule it one round later */
       GNUNET_assert (NULL == gpc->get_peer_task);
       gpc->get_peer_task =
-        GNUNET_SCHEDULER_add_delayed (gpc->sampler->max_round_interval,
-                                      &sampler_get_rand_peer,
+        GNUNET_SCHEDULER_add_delayed (sampler->max_round_interval,
+                                      &sampler_mod_get_rand_peer,
                                       cls);
       return;
     }
@@ -867,7 +646,9 @@ sampler_get_rand_peer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
 
   s_elem->last_client_request = GNUNET_TIME_absolute_get ();
 
-  GNUNET_CONTAINER_DLL_remove (gpc_head, gpc_tail, gpc);
+  GNUNET_CONTAINER_DLL_remove (gpc->req_handle->gpc_head,
+                               gpc->req_handle->gpc_tail,
+                               gpc);
   gpc->cont (gpc->cont_cls, gpc->id);
   GNUNET_free (gpc);
 }
@@ -887,65 +668,74 @@ sampler_get_rand_peer (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
  *                   #GNUNET_NO if used internally
  * @param num_peers the number of peers requested
  */
-  void
+struct RPS_SamplerRequestHandle *
 RPS_sampler_get_n_rand_peers (struct RPS_Sampler *sampler,
                               RPS_sampler_n_rand_peers_ready_cb cb,
-                              void *cls, uint32_t num_peers, int for_client)
+                              void *cls, uint32_t num_peers)
 {
   GNUNET_assert (0 != sampler->sampler_size);
+  if (0 == num_peers)
+    return NULL;
 
   // TODO check if we have too much (distinct) sampled peers
   uint32_t i;
-  struct NRandPeersReadyCls *cb_cls;
+  struct RPS_SamplerRequestHandle *req_handle;
   struct GetPeerCls *gpc;
 
-  cb_cls = GNUNET_new (struct NRandPeersReadyCls);
-  cb_cls->num_peers = num_peers;
-  cb_cls->cur_num_peers = 0;
-  cb_cls->ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
-  cb_cls->callback = cb;
-  cb_cls->cls = cls;
-
-  #ifdef TO_FILE
-  if (GNUNET_NO == for_client)
-  {
-    to_file (sampler->file_name,
-             "This sampler is probably for Brahms itself");
-  }
-  else if (GNUNET_YES == for_client)
-  {
-    to_file (sampler->file_name,
-             "This sampler is probably for the client");
-  }
-  else
-  {
-    to_file (sampler->file_name,
-             "This shouldn't happen: for_client is %i",
-             for_client);
-  }
-  #endif /* TO_FILE */
+  req_handle = GNUNET_new (struct RPS_SamplerRequestHandle);
+  req_handle->num_peers = num_peers;
+  req_handle->cur_num_peers = 0;
+  req_handle->ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
+  req_handle->sampler = sampler;
+  req_handle->callback = cb;
+  req_handle->cls = cls;
+  GNUNET_CONTAINER_DLL_insert (sampler->req_handle_head,
+                               sampler->req_handle_tail,
+                               req_handle);
 
   LOG (GNUNET_ERROR_TYPE_DEBUG,
-      "Scheduling requests for %" PRIX32 " peers\n", num_peers);
+      "Scheduling requests for %" PRIu32 " peers\n", num_peers);
 
   for (i = 0 ; i < num_peers ; i++)
   {
     gpc = GNUNET_new (struct GetPeerCls);
-    gpc->sampler = sampler;
+    gpc->req_handle = req_handle;
     gpc->cont = check_n_peers_ready;
-    gpc->cont_cls = cb_cls;
-    gpc->id = &cb_cls->ids[i];
+    gpc->cont_cls = req_handle;
+    gpc->id = &req_handle->ids[i];
 
+    GNUNET_CONTAINER_DLL_insert (req_handle->gpc_head,
+                                 req_handle->gpc_tail,
+                                 gpc);
     // maybe add a little delay
-    if (GNUNET_YES == for_client)
-      gpc->get_peer_task = GNUNET_SCHEDULER_add_now (&sampler_get_rand_peer, gpc);
-    else if (GNUNET_NO == for_client)
-      gpc->get_peer_task = GNUNET_SCHEDULER_add_now (&sampler_get_rand_peer2, gpc);
-    else
-      GNUNET_assert (0);
-
-    GNUNET_CONTAINER_DLL_insert (gpc_head, gpc_tail, gpc);
+    gpc->get_peer_task = GNUNET_SCHEDULER_add_now (sampler->get_peers, gpc);
   }
+  return req_handle;
+}
+
+/**
+ * Cancle a request issued through #RPS_sampler_n_rand_peers_ready_cb.
+ *
+ * @param req_handle the handle to the request
+ */
+void
+RPS_sampler_request_cancel (struct RPS_SamplerRequestHandle *req_handle)
+{
+  struct GetPeerCls *i;
+
+  while (NULL != (i = req_handle->gpc_head) )
+  {
+    GNUNET_CONTAINER_DLL_remove (req_handle->gpc_head,
+                                 req_handle->gpc_tail,
+                                 i);
+    if (NULL != i->get_peer_task)
+      GNUNET_SCHEDULER_cancel (i->get_peer_task);
+    GNUNET_free (i);
+  }
+  GNUNET_CONTAINER_DLL_remove (req_handle->sampler->req_handle_head,
+                               req_handle->sampler->req_handle_tail,
+                               req_handle);
+  GNUNET_free (req_handle);
 }
 
 
@@ -981,15 +771,13 @@ RPS_sampler_count_id (struct RPS_Sampler *sampler,
   void
 RPS_sampler_destroy (struct RPS_Sampler *sampler)
 {
-  struct GetPeerCls *i;
-
-  for (i = gpc_head; NULL != i; i = gpc_head)
+  if (NULL != sampler->req_handle_head)
   {
-    GNUNET_CONTAINER_DLL_remove (gpc_head, gpc_tail, i);
-    GNUNET_SCHEDULER_cancel (i->get_peer_task);
-    GNUNET_free (i);
+    LOG (GNUNET_ERROR_TYPE_WARNING,
+        "There are still pending requests. Going to remove them.\n");
+    while (NULL != sampler->req_handle_head)
+      RPS_sampler_request_cancel (sampler->req_handle_head);
   }
-
   sampler_empty (sampler);
   GNUNET_free (sampler);
 }