-clarify logic
[oweals/gnunet.git] / src / dht / gnunet_dht_profiler.c
index 0fb7ab7dfecf9b0c08caf81ff3c0a6c1535e864b..f6223b3ddefb930851b5991272abd8811f747704 100644 (file)
  */
 #define PUT_PROBABILITY 50
 
+#if ENABLE_MALICIOUS
+/**
+ * Number of peers which should act as malicious peers
+ */
+#define MALICIOUS_PROBABILITY 20
+
+/**
+ * Context for a peer which should act maliciously.
+ */
+struct MaliciousContext;
+#endif
+
+
 /**
  * Configuration
  */
@@ -60,7 +73,6 @@ struct ActiveContext;
  */
 struct Context
 {
-
   /**
    * The testbed peer this context belongs to
    */
@@ -75,8 +87,70 @@ struct Context
    * Active context; NULL if this peer is not an active peer
    */
   struct ActiveContext *ac;
+
+#if ENABLE_MALICIOUS
+  /**
+   * Malicious context; NULL if this peer is NOT malicious.
+   */
+  struct MaliciousContext *mc;
+#endif
+};
+
+
+#if ENABLE_MALICIOUS
+/**
+ * Context for a peer which should act maliciously.
+ */
+struct MaliciousContext
+{
+  /**
+   * The linked peer context
+   */
+  struct Context *ctx;
+
+  /**
+   * Handler to the DHT service
+   */
+  struct GNUNET_DHT_Handle *dht;
+
+  /**
+   * Handler to malicious api
+   */
+  struct GNUNET_DHT_ActMaliciousHandle *dht_malicious;
+};
+
+/**
+ * List of all the malicious peers contexts.
+ */
+struct Context **malicious_peer_contexts = NULL;
+
+/**
+ * Context for a peer which should act maliciously.
+ */
+struct Malicious_Context
+{
+  /**
+   * The linked peer context
+   */
+  struct Context *ctx;
+
+  /**
+   * Handler to the DHT service
+   */
+  struct GNUNET_DHT_Handle *dht;
 };
 
+/**
+ * Array of malicious peers.
+ */
+static struct MaliciousContext *a_mc;
+
+/**
+ * Number or malicious peers.
+ */
+static unsigned int n_malicious;
+
+#endif
 
 /**
  * Context for a peer which actively does DHT PUT/GET
@@ -146,9 +220,19 @@ static struct Context *a_ctx;
 static struct ActiveContext *a_ac;
 
 /**
- * The delay between starting to do PUTS and GETS
+ * The delay between rounds for collecting statistics
+ */
+static struct GNUNET_TIME_Relative delay_stats;
+
+/**
+ * The delay to start puts.
+ */
+static struct GNUNET_TIME_Relative delay_put;
+
+/**
+ * The delay to start puts.
  */
-static struct GNUNET_TIME_Relative delay;
+static struct GNUNET_TIME_Relative delay_get;
 
 /**
  * The timeout for GET and PUT
@@ -226,7 +310,7 @@ static struct GNUNET_TESTBED_Operation *successor_stats_op;
 static struct GNUNET_TESTBED_Peer **testbed_handles;
 
 /**
- * Total number of messages sent by peer. 
+ * Total number of messages sent by peer.
  */
 static uint64_t outgoing_bandwidth;
 
@@ -238,30 +322,30 @@ static uint64_t incoming_bandwidth;
 /**
  * Average number of hops taken to do put.
  */
-static unsigned int average_put_path_length;
+static double average_put_path_length;
 
 /**
- * Average number of hops taken to do get. 
+ * Average number of hops taken to do get.
  */
-static unsigned int average_get_path_length;
+static double average_get_path_length;
 
 /**
- * Total put path length across all peers. 
+ * Total put path length across all peers.
  */
 static unsigned int total_put_path_length;
 
 /**
- * Total get path length across all peers. 
+ * Total get path length across all peers.
  */
 static unsigned int total_get_path_length;
 
 /**
- * Hashmap to store pair of peer and its corresponding successor. 
+ * Hashmap to store pair of peer and its corresponding successor.
  */
 static struct GNUNET_CONTAINER_MultiHashMap *successor_peer_hashmap;
 
 /**
- * Key to start the lookup on successor_peer_hashmap. 
+ * Key to start the lookup on successor_peer_hashmap.
  */
 static struct GNUNET_HashCode *start_key;
 
@@ -281,10 +365,10 @@ static GNUNET_SCHEDULER_TaskIdentifier successor_stats_task;
 struct Collect_Stat_Context
 {
   /**
-   * Current Peer Context. 
+   * Current Peer Context.
    */
   struct Context *service_connect_ctx;
-  
+
   /**
    * Testbed operation acting on this peer
    */
@@ -297,18 +381,44 @@ struct Collect_Stat_Context
 struct Context **peer_contexts = NULL;
 
 /**
- * Counter to keep track of peers added to peer_context lists. 
+ * Counter to keep track of peers added to peer_context lists.
  */
 static int peers_started = 0;
 
 /**
- * Task that collects successor statistics from all the peers. 
+ * Should we do a PUT (mode = 0) or GET (mode = 1);
+ */
+static enum
+{
+  MODE_PUT = 0,
+
+  MODE_GET = 1
+} mode;
+
+
+/**
+ * Are we shutting down
+ */
+static int in_shutdown = 0;
+
+/**
+ * Total number of times to check if circle is formed or not.
+ */
+static unsigned int tries;
+
+/**
+ * Task that collects successor statistics from all the peers.
  * @param cls
  * @param tc
  */
 static void
 collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
 
+/**
+ * Connect to DHT services of active peers
+ */
+static void
+start_profiling();
 
 /**
  * Shutdown task.  Cleanup all resources and operations.
@@ -322,29 +432,33 @@ do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
   struct ActiveContext *ac;
   unsigned int cnt;
 
+  in_shutdown = GNUNET_YES;
   if (NULL != a_ctx)
   {
     for (cnt=0; cnt < num_peers; cnt++)
     {
-      if (NULL != a_ctx[cnt].op)
-        GNUNET_TESTBED_operation_done (a_ctx[cnt].op);
-
       /* Cleanup active context if this peer is an active peer */
       ac = a_ctx[cnt].ac;
-      if (NULL == ac)
-        continue;
-      if (GNUNET_SCHEDULER_NO_TASK != ac->delay_task)
-        GNUNET_SCHEDULER_cancel (ac->delay_task);
-      if (NULL != ac->put_data)
-        GNUNET_free (ac->put_data);
-      if (NULL != ac->dht_put)
-        GNUNET_DHT_put_cancel (ac->dht_put);
-      if (NULL != ac->dht_get)
-        GNUNET_DHT_get_stop (ac->dht_get);
+      if (NULL != ac)
+      {
+        if (GNUNET_SCHEDULER_NO_TASK != ac->delay_task)
+          GNUNET_SCHEDULER_cancel (ac->delay_task);
+        if (NULL != ac->put_data)
+          GNUNET_free (ac->put_data);
+        if (NULL != ac->dht_put)
+          GNUNET_DHT_put_cancel (ac->dht_put);
+        if (NULL != ac->dht_get)
+          GNUNET_DHT_get_stop (ac->dht_get);
+      }
+      /* Cleanup testbed operation handle at the last as this operation may
+         contain service connection to DHT */
+      if (NULL != a_ctx[cnt].op)
+        GNUNET_TESTBED_operation_done (a_ctx[cnt].op);
     }
     GNUNET_free (a_ctx);
     a_ctx = NULL;
   }
+  //FIXME: Should we collect stats only for put/get not for other messages.
   if(NULL != bandwidth_stats_op)
     GNUNET_TESTBED_operation_done (bandwidth_stats_op);
   bandwidth_stats_op = NULL;
@@ -362,13 +476,13 @@ do_shutdown (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
  *          operation has executed successfully.
  */
 static void
-bandwidth_stats_cont (void *cls, 
-                      struct GNUNET_TESTBED_Operation *op, 
+bandwidth_stats_cont (void *cls,
+                      struct GNUNET_TESTBED_Operation *op,
                       const char *emsg)
 {
   INFO ("# Outgoing bandwidth: %u\n", outgoing_bandwidth);
   INFO ("# Incoming bandwidth: %u\n", incoming_bandwidth);
-  GNUNET_SCHEDULER_shutdown (); 
+  GNUNET_SCHEDULER_shutdown ();
 }
 
 
@@ -384,11 +498,11 @@ bandwidth_stats_cont (void *cls,
  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
  */
 static int
-bandwidth_stats_iterator (void *cls, 
+bandwidth_stats_iterator (void *cls,
                           const struct GNUNET_TESTBED_Peer *peer,
-                          const char *subsystem, 
+                          const char *subsystem,
                           const char *name,
-                          uint64_t value, 
+                          uint64_t value,
                           int is_persistent)
 {
    static const char *s_sent = "# Bytes transmitted to other peers";
@@ -398,12 +512,8 @@ bandwidth_stats_iterator (void *cls,
      outgoing_bandwidth = outgoing_bandwidth + value;
    else if (0 == strncmp(s_recv, name, strlen (s_recv)))
      incoming_bandwidth = incoming_bandwidth + value;
-   else
-     return GNUNET_OK;
-   DEBUG ("Bandwith - Out: %lu; In: %lu\n",
-          (unsigned long) outgoing_bandwidth,
-          (unsigned long) incoming_bandwidth);
-   return GNUNET_OK;
+
+    return GNUNET_OK;
 }
 
 
@@ -416,9 +526,9 @@ summarize ()
   INFO ("# GETS made: %u\n", n_gets);
   INFO ("# GETS succeeded: %u\n", n_gets_ok);
   INFO ("# GETS failed: %u\n", n_gets_fail);
-  INFO ("# average_put_path_length: %u\n", average_put_path_length);
-  INFO ("# average_get_path_length: %u\n", average_get_path_length);
-  
+  INFO ("# average_put_path_length: %f\n", average_put_path_length);
+  INFO ("# average_get_path_length: %f\n", average_get_path_length);
+
   if (NULL == testbed_handles)
   {
     INFO ("No peers found\n");
@@ -427,7 +537,7 @@ summarize ()
   /* Collect Stats*/
   bandwidth_stats_op = GNUNET_TESTBED_get_statistics (n_active, testbed_handles,
                                                       "dht", NULL,
-                                                       bandwidth_stats_iterator, 
+                                                       bandwidth_stats_iterator,
                                                        bandwidth_stats_cont, NULL);
 }
 
@@ -442,17 +552,24 @@ static void
 cancel_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
   struct ActiveContext *ac = cls;
+  struct Context *ctx = ac->ctx;
 
   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
   GNUNET_assert (NULL != ac->dht_get);
   GNUNET_DHT_get_stop (ac->dht_get);
   ac->dht_get = NULL;
   n_gets_fail++;
+  GNUNET_assert (NULL != ctx->op);
+  GNUNET_TESTBED_operation_done (ctx->op);
+  ctx->op = NULL;
 
   /* If profiling is complete, summarize */
   if (n_active == n_gets_fail + n_gets_ok)
+  {
+    average_put_path_length = (double)total_put_path_length/(double)n_active;
+    average_get_path_length = (double)total_get_path_length/(double )n_gets_ok;
     summarize ();
-
+  }
 }
 
 
@@ -486,26 +603,31 @@ get_iter (void *cls,
 {
   struct ActiveContext *ac = cls;
   struct ActiveContext *get_ac = ac->get_ac;
+  struct Context *ctx = ac->ctx;
 
   /* Check the keys of put and get match or not. */
   GNUNET_assert (0 == memcmp (key, &get_ac->hash, sizeof (struct GNUNET_HashCode)));
   /* we found the data we are looking for */
-  DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok));
+  DEBUG ("We found a GET request; %u remaining\n", n_gets - (n_gets_fail + n_gets_ok)); //FIXME: It always prints 1.
   n_gets_ok++;
   get_ac->nrefs--;
   GNUNET_DHT_get_stop (ac->dht_get);
   ac->dht_get = NULL;
-  GNUNET_SCHEDULER_cancel (ac->delay_task);
+  if (ac->delay_task != GNUNET_SCHEDULER_NO_TASK)
+    GNUNET_SCHEDULER_cancel (ac->delay_task);
   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
-  
-  total_put_path_length = total_put_path_length + put_path_length;
-  total_get_path_length = total_get_path_length + get_path_length;
-  
+  GNUNET_assert (NULL != ctx->op);
+  GNUNET_TESTBED_operation_done (ctx->op);
+  ctx->op = NULL;
+
+  total_put_path_length = total_put_path_length + (double)put_path_length;
+  total_get_path_length = total_get_path_length + (double)get_path_length;
+  DEBUG ("total_put_path_length = %f,put_path \n",total_put_path_length);
   /* Summarize if profiling is complete */
   if (n_active == n_gets_fail + n_gets_ok)
   {
-    average_put_path_length = total_put_path_length/n_active;
-    average_get_path_length = total_get_path_length/n_active;
+    average_put_path_length = (double)total_put_path_length/(double)n_active;
+    average_get_path_length = (double)total_get_path_length/(double )n_gets_ok;
     summarize ();
   }
 }
@@ -535,7 +657,7 @@ delayed_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
   }
   get_ac->nrefs++;
   ac->get_ac = get_ac;
-  DEBUG ("Doing a DHT GET for data of size %u\n", get_ac->put_data_size);
+  DEBUG ("GET_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
   ac->dht_get = GNUNET_DHT_get_start (ac->dht,
                                       GNUNET_BLOCK_TYPE_TEST,
                                       &get_ac->hash,
@@ -551,6 +673,31 @@ delayed_get (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
 }
 
 
+/**
+ * Task to teardown the dht connection.  We do it as a task because calling
+ * GNUNET_DHT_disconnect() from put_continutation_callback seems illegal (the
+ * put_continuation_callback() is getting called again synchronously).  Also,
+ * only free the operation when we are not shutting down; the shutdown task will
+ * clear the operation during shutdown.
+ *
+ * @param cls the context
+ * @return tc scheduler task context.
+ */
+static void
+teardown_dht_connection (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
+{
+  struct Context *ctx = cls;
+  struct GNUNET_TESTBED_Operation *op;
+
+  if (0 != (GNUNET_SCHEDULER_REASON_SHUTDOWN & tc->reason))
+    return;
+  GNUNET_assert (NULL != ctx);
+  GNUNET_assert (NULL != (op = ctx->op));
+  ctx->op = NULL;
+  GNUNET_TESTBED_operation_done (op);
+}
+
+
 /**
  * Queue up a delayed task for doing DHT GET
  *
@@ -565,13 +712,15 @@ static void
 put_cont (void *cls, int success)
 {
   struct ActiveContext *ac = cls;
+  struct Context *ctx = ac->ctx;
 
   ac->dht_put = NULL;
   if (success)
     n_puts_ok++;
   else
     n_puts_fail++;
-  ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_get, ac);
+  GNUNET_assert (NULL != ctx);
+  (void) GNUNET_SCHEDULER_add_now (&teardown_dht_connection, ctx);
 }
 
 
@@ -585,7 +734,7 @@ static void
 delayed_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
   struct ActiveContext *ac = cls;
-  DEBUG("PUT SUPU \n");
+
   ac->delay_task = GNUNET_SCHEDULER_NO_TASK;
   /* Generate and DHT PUT some random data */
   ac->put_data_size = 16;       /* minimum */
@@ -595,10 +744,10 @@ delayed_put (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
   GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK,
                               ac->put_data, ac->put_data_size);
   GNUNET_CRYPTO_hash (ac->put_data, ac->put_data_size, &ac->hash);
-  DEBUG ("Doing a DHT PUT with data of size %u\n", ac->put_data_size);
+  DEBUG ("PUT_REQUEST_START key %s \n", GNUNET_h2s((struct GNUNET_HashCode *)ac->put_data));
   ac->dht_put = GNUNET_DHT_put (ac->dht, &ac->hash,
                                 replication,
-                                GNUNET_DHT_RO_NONE,
+                                GNUNET_DHT_RO_RECORD_ROUTE,
                                 GNUNET_BLOCK_TYPE_TEST,
                                 ac->put_data_size,
                                 ac->put_data,
@@ -627,7 +776,7 @@ dht_connected (void *cls,
   struct ActiveContext *ac = cls;
   struct Context *ctx = ac->ctx;
 
-  GNUNET_assert (NULL != ctx);
+  GNUNET_assert (NULL != ctx); //FIXME: Fails
   GNUNET_assert (NULL != ctx->op);
   GNUNET_assert (ctx->op == op);
   ac->dht = (struct GNUNET_DHT_Handle *) ca_result;
@@ -638,8 +787,28 @@ dht_connected (void *cls,
     ctx->op = NULL;
     return;
   }
-   
-  ac->delay_task = GNUNET_SCHEDULER_add_delayed (delay, &delayed_put, ac);
+  switch (mode)
+  {
+  case MODE_PUT:
+  {
+    struct GNUNET_TIME_Relative peer_delay_put;
+    peer_delay_put.rel_value_us =
+      GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
+                                delay_put.rel_value_us);
+    ac->delay_task = GNUNET_SCHEDULER_add_delayed (peer_delay_put, &delayed_put, ac);
+    break;
+  }
+  case MODE_GET:
+  {
+    struct GNUNET_TIME_Relative peer_delay_get;
+    peer_delay_get.rel_value_us =
+      delay_get.rel_value_us +
+      GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
+                                delay_get.rel_value_us);
+    ac->delay_task = GNUNET_SCHEDULER_add_delayed (peer_delay_get, &delayed_get, ac);
+    break;
+  }
+  }
 }
 
 
@@ -675,37 +844,206 @@ dht_disconnect (void *cls, void *op_result)
   GNUNET_assert (NULL != ac->dht);
   GNUNET_assert (ac->dht == op_result);
   GNUNET_DHT_disconnect (ac->dht);
+  ac->dht = NULL;
   n_dht--;
-  if (0 == n_dht)
-    GNUNET_SCHEDULER_shutdown ();
+  if (0 != n_dht)
+    return;
+  if (GNUNET_YES == in_shutdown)
+    return;
+  switch (mode)
+  {
+  case MODE_PUT:
+    if ((n_puts_ok + n_puts_fail) != n_active)
+      return;
+    /* Start GETs if all PUTs have been made */
+    mode = MODE_GET;
+    //(void) GNUNET_SCHEDULER_add_now (&call_start_profiling, NULL);
+    start_profiling ();
+    return;
+  case MODE_GET:
+    if ((n_gets_ok + n_gets_fail) != n_active)
+      return;
+    break;
+  }
+}
+
+/**
+ * Connect to DHT services of active peers
+ */
+static void
+start_profiling()
+{
+  struct Context *ctx;
+  unsigned int i;
+
+  DEBUG("GNUNET_TESTBED_service_connect \n");
+  GNUNET_break (GNUNET_YES != in_shutdown);
+  for(i = 0; i < n_active; i++)
+  {
+    struct ActiveContext *ac = &a_ac[i];
+    GNUNET_assert (NULL != (ctx = ac->ctx));
+    GNUNET_assert (NULL == ctx->op);
+    ctx->op =
+        GNUNET_TESTBED_service_connect (ctx,
+                                        ctx->peer,
+                                        "dht",
+                                        &dht_connected, ac,
+                                        &dht_connect,
+                                        &dht_disconnect,
+                                        ac);
+  }
+}
+
+#if ENABLE_MALICIOUS
+/**
+ * Count of total number of malicious peers.
+ */
+static unsigned int count_malicious;
+
+/**
+ * Continuation of GNUNET_DHT_act_malicious
+ * @param cls Malicious context
+  * @param success #GNUNET_OK if the ACT_MALICIOUS was transmitted,
+ *                 #GNUNET_NO on timeout,
+ *                 #GNUNET_SYSERR on disconnect from service
+ *                 after the ACT_MALICIOUS message was transmitted
+ *                 (so we don't know if it was received or not)
+ */
+static void
+act_malicious_cont (void *cls, int success)
+{
+  struct MaliciousContext *mc = cls;
+  struct Context *ctx = mc->ctx;
+
+  GNUNET_TESTBED_operation_done (ctx->op);
+  ctx->op = NULL;
+  return;
+}
+
+
+/**
+ * Call malicious API for all the malicious peers.
+ * @param cls the malicious context.
+ * @param op the operation that has been finished
+ * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
+ * @param emsg error message in case the operation has failed; will be NULL if
+ *          operation has executed successfully.
+ */
+static void
+dht_set_malicious(void *cls,
+                  struct GNUNET_TESTBED_Operation *op,
+                  void *ca_result,
+                  const char *emsg)
+{
+  struct MaliciousContext *mc = cls;
+  struct Context *ctx = mc->ctx;
+
+  GNUNET_assert (NULL != ctx);
+  GNUNET_assert (NULL != ctx->op);
+  GNUNET_assert (ctx->op == op);
+  mc->dht = (struct GNUNET_DHT_Handle *) ca_result;
+  if (NULL != emsg)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Connection to DHT service failed: %s\n", emsg);
+    GNUNET_TESTBED_operation_done (ctx->op); /* Calls dht_disconnect_malicious() */
+    ctx->op = NULL;
+    return;
+  }
+  mc->dht_malicious = GNUNET_DHT_act_malicious(mc->dht, 1, act_malicious_cont, mc);
 }
 
 
 /**
- * FIXME:Verify where is n_active used. Should this service be started only
- * for n_active peers?
- * Start testbed service for all the peers. 
+ * Adapter function called to destroy a connection to
+ * a service.
+ *
+ * @param cls the active context
+ * @param op_result service handle returned from the connect adapter
  */
 static void
-start_testbed_service_on_all_peers()
+dht_disconnect_malicious (void *cls, void *op_result)
+{
+  struct MaliciousContext *mc = cls;
+  count_malicious++;
+  GNUNET_assert (NULL != mc->dht);
+  GNUNET_assert (mc->dht == op_result);
+  GNUNET_DHT_disconnect (mc->dht);
+  mc->dht = NULL;
+  mc->ctx->op = NULL;
+  n_dht--;
+
+  if (0 != n_dht)
+    return;
+
+  if(n_malicious == count_malicious)
+  {
+    DEBUG("\n Call start_profiling()");
+    start_profiling();
+  }
+}
+
+
+/**
+ * Set the malicious variable in peer malicious context.
+ */
+static void
+set_malicious()
 {
   unsigned int i;
-  for(i = 0; i < peers_started; i++)
+
+  DEBUG ("Setting %u peers malicious",
+         n_malicious);
+  for(i = 0; i < n_malicious; i++)
   {
-      struct Context *ctx = peer_contexts[i];
-      DEBUG("GNUNET_TESTBED_service_connect \n");
-      ctx->op = 
-              GNUNET_TESTBED_service_connect (ctx, 
-                                              ctx->peer,
-                                              "dht",
-                                              &dht_connected, ctx->ac,
-                                              &dht_connect,
-                                              &dht_disconnect,
-                                              ctx->ac);
-     
+    struct MaliciousContext *mc = &a_mc[i];
+    mc->ctx->op =
+        GNUNET_TESTBED_service_connect (mc->ctx,
+                                        mc->ctx->peer,
+                                        "dht",
+                                        &dht_set_malicious, mc,
+                                        &dht_connect,
+                                        &dht_disconnect_malicious,
+                                        mc);
   }
 }
 
+#endif
+
+
+/**
+ * Start collecting relevant statistics. If ENABLE_MALICIOUS set, first
+ * set the malicious peers. If not, then start with PUT operation on active
+ * peers.
+ */
+static void
+start_func()
+{
+#if ENABLE_MALICIOUS
+  set_malicious();
+#else
+  start_profiling();
+#endif
+}
+
+
+/**
+ * Remove entry from successor peer hashmap.
+ * @param cls closure
+ * @param key current public key
+ * @param value value in the hash map
+ * @return #GNUNET_YES if we should continue to iterate,
+ *         #GNUNET_NO if not.
+ */
+static int
+hashmap_iterate_remove(void *cls,
+                       const struct GNUNET_HashCode *key,
+                       void *value)
+{
+  GNUNET_assert (GNUNET_YES ==
+                GNUNET_CONTAINER_multihashmap_remove(successor_peer_hashmap, key, value));
+  return GNUNET_YES;
+}
+
 
 /**
  * Stats callback. Iterate over the hashmap and check if all th peers form
@@ -717,75 +1055,91 @@ start_testbed_service_on_all_peers()
  *          operation has executed successfully.
  */
 static void
-successor_stats_cont (void *cls, 
-                      struct GNUNET_TESTBED_Operation *op, 
+successor_stats_cont (void *cls,
+                      struct GNUNET_TESTBED_Operation *op,
                       const char *emsg)
 {
   struct GNUNET_HashCode *val;
   struct GNUNET_HashCode *start_val;
-  int count = 0;
   struct GNUNET_HashCode *key;
-  
-  start_val =(struct GNUNET_HashCode *) GNUNET_CONTAINER_multihashmap_get(successor_peer_hashmap,
-                                                start_key);
+  int count;
 
-  val = GNUNET_new(struct GNUNET_HashCode);
+  /* Don't schedule the task till we are looking for circle here. */
+  successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
+  GNUNET_TESTBED_operation_done (successor_stats_op);
+  successor_stats_op = NULL;
+  if (0 == max_searches)
+  {
+    start_func();
+    return;
+  }
+
+  GNUNET_assert (NULL != start_key);
+  start_val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
+                                                 start_key);
+  GNUNET_assert (NULL != start_val);
   val = start_val;
-  while (count < num_peers)
+  for (count = 0; count < num_peers; count++)
   {
-    key = GNUNET_new(struct GNUNET_HashCode);
     key = val;
     val = GNUNET_CONTAINER_multihashmap_get (successor_peer_hashmap,
                                              key);
-    GNUNET_assert(NULL != val);
-    count++;
-  }
-  
-  if (start_val == val)
-  {
-    DEBUG("Circle completed\n");
-    if (GNUNET_SCHEDULER_NO_TASK != successor_stats_task)
+    if (NULL == val)
+      break;
+    /* Remove the entry from hashmap. This is done to take care of loop. */
+    if (GNUNET_NO ==
+        GNUNET_CONTAINER_multihashmap_remove (successor_peer_hashmap,
+                                              key, val))
     {
-      successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
-      //FIXME: free hashmap. 
+      DEBUG ("Failed to remove entry from hashmap\n");
+      break;
     }
-    successor_stats_op = NULL;
-    
+    /* If a peer has its own identity as its successor. */
+    if (0 == memcmp(key, val, sizeof (struct GNUNET_HashCode)))
+      break;
+  }
+
+  GNUNET_assert (GNUNET_SYSERR !=
+                 GNUNET_CONTAINER_multihashmap_iterate (successor_peer_hashmap,
+                                                        &hashmap_iterate_remove,
+                                                        NULL));
+
+  successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers,
+                                                                 GNUNET_NO);
+  if ((start_val == val) && (count == num_peers))
+  {
+    DEBUG("CIRCLE COMPLETED after %u tries", tries);
     if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
     {
-      start_testbed_service_on_all_peers();
+      start_func();
     }
-    
     return;
   }
   else
   {
-    static unsigned int tries;
-
-    DEBUG("Circle not complete\n");
     if (max_searches == ++tries)
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                   "Maximum tries %u exceeded while checking successor TOTAL TRIES %u"
-                  " cirle formation.  Exiting\n",
+                  " circle formation.  Exiting\n",
                   max_searches,tries);
       if (GNUNET_SCHEDULER_NO_TASK != successor_stats_task)
       {
         successor_stats_task = GNUNET_SCHEDULER_NO_TASK;
-        //FIXME: free hashmap
       }
-      successor_stats_op = NULL;
-      
       if(GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
       {
-        start_testbed_service_on_all_peers();
+        start_func();
       }
-      
+
       return;
     }
-    
-    //FIXME: change delay use exponential back off. 
-    successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay, &collect_stats, cls);
+    else
+    {
+      flag = 0;
+      successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay_stats,
+                                                           &collect_stats, cls);
+    }
   }
 }
 
@@ -802,15 +1156,17 @@ successor_stats_cont (void *cls,
  * @return GNUNET_OK to continue, GNUNET_SYSERR to abort iteration
  */
 static int
-successor_stats_iterator (void *cls, 
+successor_stats_iterator (void *cls,
                           const struct GNUNET_TESTBED_Peer *peer,
-                          const char *subsystem, 
+                          const char *subsystem,
                           const char *name,
-                          uint64_t value, 
+                          uint64_t value,
                           int is_persistent)
 {
   static const char *key_string = "XDHT";
-  
+  if (0 == max_searches)
+    return GNUNET_OK;
+
   if (0 == strncmp (key_string, name, strlen (key_string)))
   {
     char *my_id_str;
@@ -819,39 +1175,40 @@ successor_stats_iterator (void *cls,
     char truncated_successor_str[13];
     struct GNUNET_HashCode *my_id_key;
     struct GNUNET_HashCode *succ_key;
-    
+
     strtok((char *)name,":");
     my_id_str = strtok(NULL,":");
-    
+
     strncpy(truncated_my_id_str, my_id_str, 12);
     truncated_my_id_str[12] = '\0';
-    
     my_id_key = GNUNET_new(struct GNUNET_HashCode);
     GNUNET_CRYPTO_hash (truncated_my_id_str, sizeof(truncated_my_id_str),my_id_key);
-    
     GNUNET_STRINGS_data_to_string(&value, sizeof(uint64_t), successor_str, 13);
     strncpy(truncated_successor_str, successor_str, 12);
     truncated_successor_str[12] ='\0';
-   
+
     succ_key = GNUNET_new(struct GNUNET_HashCode);
     GNUNET_CRYPTO_hash (truncated_successor_str, sizeof(truncated_successor_str),succ_key);
-    
+
     if (0 == flag)
     {
+      GNUNET_assert(NULL != my_id_key);
       start_key = my_id_key;
+      GNUNET_assert(NULL != start_key);
       flag = 1;
     }
     GNUNET_CONTAINER_multihashmap_put (successor_peer_hashmap,
                                        my_id_key, (void *)succ_key,
                                        GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE);
   }
+
   return GNUNET_OK;
 }
 
 
-/* 
- * Task that collects peer and its corresponding successors. 
- * 
+/*
+ * Task that collects peer and its corresponding successors.
+ *
  * @param cls Closure (NULL).
  * @param tc Task Context.
  */
@@ -862,16 +1219,21 @@ collect_stats (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
     return;
 
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Start collecting statistics...\n");
-  
- /* Check for successor pointer, don't start put till the virtual ring topology
-   is not created. */
-  successor_stats_op = 
+  GNUNET_assert(NULL != testbed_handles);
+
+  if (0 != max_searches)
+  successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers,
+                                                                    GNUNET_NO);
+  successor_stats_op =
           GNUNET_TESTBED_get_statistics (num_peers, testbed_handles,
                                          "dht", NULL,
-                                          successor_stats_iterator, 
+                                          successor_stats_iterator,
                                           successor_stats_cont, cls);
+
+  GNUNET_assert(NULL != successor_stats_op);
 }
 
+
 /**
  * Callback called when DHT service on the peer is started
  *
@@ -886,34 +1248,22 @@ service_started (void *cls,
                  const char *emsg)
 {
   struct Context *ctx = cls;
-  
+
   GNUNET_assert (NULL != ctx);
   GNUNET_assert (NULL != ctx->op);
   GNUNET_TESTBED_operation_done (ctx->op);
   ctx->op = NULL;
-  if (NULL == ctx->ac)
-    return;
-  
-  if (NULL == peer_contexts)
-  {
-    peer_contexts = GNUNET_malloc(num_peers * sizeof(struct Context *));
-  }
-  
-  peer_contexts[peers_started] = ctx;
   peers_started++;
-  DEBUG("Peers Started = %d \n", peers_started);
-    
-  if (GNUNET_SCHEDULER_NO_TASK == successor_stats_task)
+  DEBUG("Peers Started = %d; num_peers = %d \n", peers_started, num_peers);
+  if (GNUNET_SCHEDULER_NO_TASK == successor_stats_task && peers_started == num_peers)
   {
      DEBUG("successor_stats_task \n");
      struct Collect_Stat_Context *collect_stat_cls = GNUNET_new(struct Collect_Stat_Context);
      collect_stat_cls->service_connect_ctx = cls;
      collect_stat_cls->op = op;
-     
-     successor_peer_hashmap = GNUNET_CONTAINER_multihashmap_create (num_peers, 
-                                                                    GNUNET_NO);
-     successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay, 
-                                                          &collect_stats, 
+
+     successor_stats_task = GNUNET_SCHEDULER_add_delayed (delay_stats,
+                                                          &collect_stats,
                                                           collect_stat_cls);
   }
 }
@@ -939,8 +1289,7 @@ test_run (void *cls,
 {
   unsigned int cnt;
   unsigned int ac_cnt;
-  
-  testbed_handles = peers;  
+  testbed_handles = peers;
   if (NULL == peers)
   {
     /* exit */
@@ -957,20 +1306,58 @@ test_run (void *cls,
     GNUNET_free (a_ctx);
     return;
   }
-  
+
   a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
   ac_cnt = 0;
-  for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
+
+#if ENABLE_MALICIOUS
+  unsigned int malicious_peers;
+  if(PUT_PROBABILITY + MALICIOUS_PROBABILITY > 100)
+  {
+    DEBUG ("Reduce either number of malicious peer or active peers. ");
+    GNUNET_SCHEDULER_shutdown ();
+    GNUNET_free (a_ctx);
+    return;
+  }
+
+  /* Select the peers which should act maliciously. */
+  n_malicious = num_peers * MALICIOUS_PROBABILITY / 100;
+
+  a_mc = GNUNET_malloc (n_malicious * sizeof (struct MaliciousContext));
+  malicious_peers = 0;
+
+  for (cnt = 0; cnt < num_peers && malicious_peers < n_malicious; cnt++)
   {
     if (GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
-        PUT_PROBABILITY)
+        MALICIOUS_PROBABILITY)
+      continue;
+    a_ctx[cnt].mc = &a_mc[malicious_peers];
+    a_mc[malicious_peers].ctx = &a_ctx[cnt];
+    malicious_peers++;
+  }
+  n_malicious = malicious_peers;
+  INFO ("Malicious Peers: %u\n",malicious_peers);
+
+#endif
+
+  a_ac = GNUNET_malloc (n_active * sizeof (struct ActiveContext));
+  ac_cnt = 0;
+  for (cnt = 0; cnt < num_peers && ac_cnt < n_active; cnt++)
+  {
+    if ((GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 100) >=
+        PUT_PROBABILITY))
+      continue;
+
+#if ENABLE_MALICIOUS
+    if(a_ctx[ac_cnt].mc != NULL)
       continue;
+#endif
+
     a_ctx[cnt].ac = &a_ac[ac_cnt];
     a_ac[ac_cnt].ctx = &a_ctx[cnt];
     ac_cnt++;
   }
   n_active = ac_cnt;
-  a_ac = GNUNET_realloc (a_ac, n_active * sizeof (struct ActiveContext));
   INFO ("Active peers: %u\n", n_active);
 
   /* start DHT service on all peers */
@@ -1031,28 +1418,37 @@ main (int argc, char *const *argv)
      gettext_noop ("number of peers to start"),
      1, &GNUNET_GETOPT_set_uint, &num_peers},
     {'s', "searches", "COUNT",
-     gettext_noop ("maximum number of times we try to search for successor circle formation (default is 1)"),
+     gettext_noop ("maximum number of times we try to search for successor circle formation (0 for R5N)"),
      1, &GNUNET_GETOPT_set_uint, &max_searches},
     {'H', "hosts", "FILENAME",
      gettext_noop ("name of the file with the login information for the testbed"),
      1, &GNUNET_GETOPT_set_string, &hosts_file},
-    {'d', "delay", "DELAY",
-     gettext_noop ("delay for starting DHT PUT and GET"),
-     1, &GNUNET_GETOPT_set_relative_time, &delay},
+    {'D', "delay", "DELAY",
+     gettext_noop ("delay between rounds for collecting statistics (default: 30 sec)"),
+     1, &GNUNET_GETOPT_set_relative_time, &delay_stats},
+    {'P', "PUT-delay", "DELAY",
+     gettext_noop ("delay to start doing PUTs (default: 1 sec)"),
+     1, &GNUNET_GETOPT_set_relative_time, &delay_put},
+    {'G', "GET-delay", "DELAY",
+     gettext_noop ("delay to start doing GETs (default: 5 min)"),
+     1, &GNUNET_GETOPT_set_relative_time, &delay_get},
     {'r', "replication", "DEGREE",
      gettext_noop ("replication degree for DHT PUTs"),
      1, &GNUNET_GETOPT_set_uint, &replication},
     {'t', "timeout", "TIMEOUT",
-     gettext_noop ("timeout for DHT PUT and GET requests"),
+     gettext_noop ("timeout for DHT PUT and GET requests (default: 1 min)"),
      1, &GNUNET_GETOPT_set_relative_time, &timeout},
     GNUNET_GETOPT_OPTION_END
   };
 
-  max_searches = 10;
+  max_searches = 5;
   if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv))
     return 2;
-  delay = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2); /* default delay */
-  timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 1); /* default timeout */
+  /* set default delays */
+  delay_stats = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
+  delay_put = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
+  delay_get = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
+  timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 10);
   replication = 1;      /* default replication */
   rc = 0;
   if (GNUNET_OK !=