Merge branch 'master' of ssh://gnunet.org/gnunet
[oweals/gnunet.git] / src / rps / gnunet-rps-profiler.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2009, 2012 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14     
15      You should have received a copy of the GNU Affero General Public License
16      along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 */
18 /**
19  * @file rps/test_rps.c
20  * @brief Testcase for the random peer sampling service.  Starts
21  *        a peergroup with a given number of peers, then waits to
22  *        receive size pushes/pulls from each peer.  Expects to wait
23  *        for one message from each peer.
24  */
25 #include "platform.h"
26 //#include "rps_test_lib.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_testbed_service.h"
29
30 #include "gnunet_rps_service.h"
31 #include "rps-test_util.h"
32 #include "gnunet-service-rps_sampler_elem.h"
33
34 #include <inttypes.h>
35
36
37 #define BIT(n) (1 << (n))
38
39 /**
40  * How many peers do we start?
41  */
42 static uint32_t num_peers;
43
44 /**
45  * @brief numer of bits required to represent the largest peer id
46  */
47 static unsigned bits_needed;
48
49 /**
50  * How long do we run the test?
51  */
52 static struct GNUNET_TIME_Relative duration;
53
54 /**
55  * When do we do a hard shutdown?
56  */
57 static struct GNUNET_TIME_Relative timeout;
58
59
60 /**
61  * Portion of malicious peers
62  */
63 static double portion = .1;
64
65 /**
66  * Type of malicious peer to test
67  */
68 static unsigned int mal_type = 0;
69
70 /**
71  * Handles to all of the running peers
72  */
73 static struct GNUNET_TESTBED_Peer **testbed_peers;
74
75 enum STAT_TYPE
76 {
77   STAT_TYPE_ROUNDS,                   /*   0 */
78   STAT_TYPE_BLOCKS,                   /*   1 */
79   STAT_TYPE_BLOCKS_MANY_PUSH,         /*   2 */
80   STAT_TYPE_BLOCKS_NO_PUSH,           /*   3 */
81   STAT_TYPE_BLOCKS_NO_PULL,           /*   4 */
82   STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL, /*   5 */
83   STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL,   /*   6 */
84   STAT_TYPE_ISSUED_PUSH_SEND,         /*   7 */
85   STAT_TYPE_ISSUED_PULL_REQ,          /*   8 */
86   STAT_TYPE_ISSUED_PULL_REP,          /*  9 */
87   STAT_TYPE_SENT_PUSH_SEND,           /*  10 */
88   STAT_TYPE_SENT_PULL_REQ,            /*  11 */
89   STAT_TYPE_SENT_PULL_REP,            /*  12 */
90   STAT_TYPE_RECV_PUSH_SEND,           /*  13 */
91   STAT_TYPE_RECV_PULL_REQ,            /*  14 */
92   STAT_TYPE_RECV_PULL_REP,            /*  15 */
93   STAT_TYPE_MAX,                      /*  16 */
94 };
95
96 static char* stat_type_strings[] = {
97   "# rounds",
98   "# rounds blocked",
99   "# rounds blocked - too many pushes",
100   "# rounds blocked - no pushes",
101   "# rounds blocked - no pull replies",
102   "# rounds blocked - too many pushes, no pull replies",
103   "# rounds blocked - no pushes, no pull replies",
104   "# push send issued",
105   "# pull request send issued",
106   "# pull reply send issued",
107   "# pushes sent",
108   "# pull requests sent",
109   "# pull replys sent",
110   "# push message received",
111   "# pull request message received",
112   "# pull reply messages received",
113 };
114
115 struct STATcls
116 {
117   struct RPSPeer *rps_peer;
118   enum STAT_TYPE stat_type;
119 };
120
121
122 /**
123  * @brief Converts string representation to the corresponding #STAT_TYPE enum.
124  *
125  * @param stat_str string representation of statistics specifier
126  *
127  * @return corresponding enum
128  */
129 enum STAT_TYPE stat_str_2_type (const char *stat_str)
130 {
131   if (0 == strncmp (stat_type_strings[STAT_TYPE_BLOCKS_NO_PULL],
132                     stat_str,
133                     strlen (stat_type_strings[STAT_TYPE_BLOCKS_NO_PULL])))
134   {
135     return STAT_TYPE_BLOCKS_NO_PULL;
136   }
137   else if (0 == strncmp (stat_type_strings[STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL],
138                          stat_str,
139                          strlen (stat_type_strings[STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL])))
140   {
141     return STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL;
142   }
143   else if (0 == strncmp (stat_type_strings[STAT_TYPE_BLOCKS_MANY_PUSH],
144                          stat_str,
145                          strlen (stat_type_strings[STAT_TYPE_BLOCKS_MANY_PUSH])))
146   {
147     return STAT_TYPE_BLOCKS_MANY_PUSH;
148   }
149   else if (0 == strncmp (stat_type_strings[STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL],
150                          stat_str,
151                          strlen (stat_type_strings[STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL])))
152   {
153     return STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL;
154   }
155   else if (0 == strncmp (stat_type_strings[STAT_TYPE_BLOCKS_NO_PUSH],
156                          stat_str,
157                          strlen (stat_type_strings[STAT_TYPE_BLOCKS_NO_PUSH])))
158   {
159     return STAT_TYPE_BLOCKS_NO_PUSH;
160   }
161   else if (0 == strncmp (stat_type_strings[STAT_TYPE_BLOCKS],
162                          stat_str,
163                          strlen (stat_type_strings[STAT_TYPE_BLOCKS])))
164   {
165     return STAT_TYPE_BLOCKS;
166   }
167   else if (0 == strncmp (stat_type_strings[STAT_TYPE_ROUNDS],
168                          stat_str,
169                          strlen (stat_type_strings[STAT_TYPE_ROUNDS])))
170   {
171     return STAT_TYPE_ROUNDS;
172   }
173   else if (0 == strncmp (stat_type_strings[STAT_TYPE_ISSUED_PUSH_SEND],
174                          stat_str,
175                          strlen (stat_type_strings[STAT_TYPE_ISSUED_PUSH_SEND])))
176   {
177     return STAT_TYPE_ISSUED_PUSH_SEND;
178   }
179   else if (0 == strncmp (stat_type_strings[STAT_TYPE_ISSUED_PULL_REQ],
180                          stat_str,
181                          strlen (stat_type_strings[STAT_TYPE_ISSUED_PULL_REQ])))
182   {
183     return STAT_TYPE_ISSUED_PULL_REQ;
184   }
185   else if (0 == strncmp (stat_type_strings[STAT_TYPE_ISSUED_PULL_REP],
186                          stat_str,
187                          strlen (stat_type_strings[STAT_TYPE_ISSUED_PULL_REP])))
188   {
189     return STAT_TYPE_ISSUED_PULL_REP;
190   }
191   else if (0 == strncmp (stat_type_strings[STAT_TYPE_SENT_PUSH_SEND],
192                          stat_str,
193                          strlen (stat_type_strings[STAT_TYPE_SENT_PUSH_SEND])))
194   {
195     return STAT_TYPE_SENT_PUSH_SEND;
196   }
197   else if (0 == strncmp (stat_type_strings[STAT_TYPE_SENT_PULL_REQ],
198                          stat_str,
199                          strlen (stat_type_strings[STAT_TYPE_SENT_PULL_REQ])))
200   {
201     return STAT_TYPE_SENT_PULL_REQ;
202   }
203   else if (0 == strncmp (stat_type_strings[STAT_TYPE_SENT_PULL_REP],
204                          stat_str,
205                          strlen (stat_type_strings[STAT_TYPE_SENT_PULL_REP])))
206   {
207     return STAT_TYPE_SENT_PULL_REP;
208   }
209   else if (0 == strncmp (stat_type_strings[STAT_TYPE_RECV_PUSH_SEND],
210                          stat_str,
211                          strlen (stat_type_strings[STAT_TYPE_RECV_PUSH_SEND])))
212   {
213     return STAT_TYPE_RECV_PUSH_SEND;
214   }
215   else if (0 == strncmp (stat_type_strings[STAT_TYPE_RECV_PULL_REQ],
216                          stat_str,
217                          strlen (stat_type_strings[STAT_TYPE_RECV_PULL_REQ])))
218   {
219     return STAT_TYPE_RECV_PULL_REQ;
220   }
221   else if (0 == strncmp (stat_type_strings[STAT_TYPE_RECV_PULL_REP],
222                          stat_str,
223                          strlen (stat_type_strings[STAT_TYPE_RECV_PULL_REP])))
224   {
225     return STAT_TYPE_RECV_PULL_REP;
226   }
227   return STAT_TYPE_MAX;
228 }
229
230
231 /**
232  * @brief Indicates whether peer should go off- or online
233  */
234 enum PEER_ONLINE_DELTA {
235   /**
236    * @brief Indicates peer going online
237    */
238   PEER_GO_ONLINE = 1,
239   /**
240    * @brief Indicates peer going offline
241    */
242   PEER_GO_OFFLINE = -1,
243 };
244
245 /**
246  * Operation map entry
247  */
248 struct OpListEntry
249 {
250   /**
251    * DLL next ptr
252    */
253   struct OpListEntry *next;
254
255   /**
256    * DLL prev ptr
257    */
258   struct OpListEntry *prev;
259
260   /**
261    * The testbed operation
262    */
263   struct GNUNET_TESTBED_Operation *op;
264
265   /**
266    * Depending on whether we start or stop RPS service at the peer, set this to
267    * #PEER_GO_ONLINE (1) or #PEER_GO_OFFLINE (-1)
268    */
269   enum PEER_ONLINE_DELTA delta;
270
271   /**
272    * Index of the regarding peer
273    */
274   unsigned int index;
275 };
276
277 /**
278  * OpList DLL head
279  */
280 static struct OpListEntry *oplist_head;
281
282 /**
283  * OpList DLL tail
284  */
285 static struct OpListEntry *oplist_tail;
286
287
288 /**
289  * A pending reply: A request was sent and the reply is pending.
290  */
291 struct PendingReply
292 {
293   /**
294    * DLL next,prev ptr
295    */
296   struct PendingReply *next;
297   struct PendingReply *prev;
298
299   /**
300    * Handle to the request we are waiting for
301    */
302   struct GNUNET_RPS_Request_Handle *req_handle;
303
304   /**
305    * The peer that requested
306    */
307   struct RPSPeer *rps_peer;
308 };
309
310
311 /**
312  * A pending request: A request was not made yet but is scheduled for later.
313  */
314 struct PendingRequest
315 {
316   /**
317    * DLL next,prev ptr
318    */
319   struct PendingRequest *next;
320   struct PendingRequest *prev;
321
322   /**
323    * Handle to the request we are waiting for
324    */
325   struct GNUNET_SCHEDULER_Task *request_task;
326
327   /**
328    * The peer that requested
329    */
330   struct RPSPeer *rps_peer;
331 };
332
333
334 /**
335  * Information we track for each peer.
336  */
337 struct RPSPeer
338 {
339   /**
340    * Index of the peer.
341    */
342   unsigned int index;
343
344   /**
345    * Handle for RPS connect operation.
346    */
347   struct GNUNET_TESTBED_Operation *op;
348
349   /**
350    * Handle to RPS service.
351    */
352   struct GNUNET_RPS_Handle *rps_handle;
353
354   /**
355    * ID of the peer.
356    */
357   struct GNUNET_PeerIdentity *peer_id;
358
359   /**
360    * A request handle to check for an request
361    */
362   //struct GNUNET_RPS_Request_Handle *req_handle;
363
364   /**
365    * Peer on- or offline?
366    */
367   int online;
368
369   /**
370    * Number of Peer IDs to request during the whole test
371    */
372   unsigned int num_ids_to_request;
373
374   /**
375    * Pending requests DLL
376    */
377   struct PendingRequest *pending_req_head;
378   struct PendingRequest *pending_req_tail;
379
380   /**
381    * Number of pending requests
382    */
383   unsigned int num_pending_reqs;
384
385   /**
386    * Pending replies DLL
387    */
388   struct PendingReply *pending_rep_head;
389   struct PendingReply *pending_rep_tail;
390
391   /**
392    * Number of pending replies
393    */
394   unsigned int num_pending_reps;
395
396   /**
397    * Number of received PeerIDs
398    */
399   unsigned int num_recv_ids;
400
401   /**
402    * Pending operation on that peer
403    */
404   const struct OpListEntry *entry_op_manage;
405
406   /**
407    * Testbed operation to connect to statistics service
408    */
409   struct GNUNET_TESTBED_Operation *stat_op;
410
411   /**
412    * Handle to the statistics service
413    */
414   struct GNUNET_STATISTICS_Handle *stats_h;
415
416   /**
417    * @brief flags to indicate which statistics values have been already
418    * collected from the statistics service.
419    * Used to check whether we are able to shutdown.
420    */
421   uint32_t stat_collected_flags;
422
423   /**
424    * @brief File name of the file the stats are finally written to
425    */
426   const char *file_name_stats;
427
428   /**
429    * @brief File name of the file the stats are finally written to
430    */
431   const char *file_name_probs;
432
433   /**
434    * @brief The current view
435    */
436   struct GNUNET_PeerIdentity *cur_view;
437
438   /**
439    * @brief Number of peers in the #cur_view.
440    */
441   uint32_t cur_view_count;
442
443   /**
444    * @brief Number of occurrences in other peer's view
445    */
446   uint32_t count_in_views;
447
448   /**
449    * @brief statistics values
450    */
451   uint64_t stats[STAT_TYPE_MAX];
452   /**
453    * @brief Handle for the statistics get request
454    */
455   struct GNUNET_STATISTICS_GetHandle *h_stat_get[STAT_TYPE_MAX];
456 };
457
458 /**
459  * Information for all the peers.
460  */
461 static struct RPSPeer *rps_peers;
462
463 /**
464  * Peermap to get the index of a given peer ID quick.
465  */
466 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
467
468 /**
469  * IDs of the peers.
470  */
471 static struct GNUNET_PeerIdentity *rps_peer_ids;
472
473 /**
474  * ID of the targeted peer.
475  */
476 static struct GNUNET_PeerIdentity *target_peer;
477
478 /**
479  * Number of online peers.
480  */
481 static unsigned int num_peers_online;
482
483 /**
484  * @brief The added sizes of the peer's views
485  */
486 static unsigned int view_sizes;
487
488 /**
489  * Return value from 'main'.
490  */
491 static int ok;
492
493 /**
494  * Identifier for the task that runs after the test to collect results
495  */
496 static struct GNUNET_SCHEDULER_Task *post_test_task;
497
498 /**
499  * Identifier for the shutdown task
500  */
501 static struct GNUNET_SCHEDULER_Task *shutdown_task;
502
503
504 /**
505  * Identifier for the churn task that runs periodically
506  */
507 static struct GNUNET_SCHEDULER_Task *churn_task;
508
509 /**
510  * Called to initialise the given RPSPeer
511  */
512 typedef void (*InitPeer) (struct RPSPeer *rps_peer);
513
514 /**
515  * @brief Called directly after connecting to the service
516  *
517  * @param rps_peer Specific peer the function is called on
518  * @param h the handle to the rps service
519  */
520 typedef void (*PreTest) (struct RPSPeer *rps_peer, struct GNUNET_RPS_Handle *h);
521
522 /**
523  * @brief Executes functions to test the api/service for a given peer
524  *
525  * Called from within #rps_connect_complete_cb ()
526  * Implemented by #churn_test_cb, #profiler_cb, #mal_cb, #single_req_cb,
527  * #delay_req_cb, #seed_big_cb, #single_peer_seed_cb, #seed_cb, #req_cancel_cb
528  *
529  * @param rps_peer the peer the task runs on
530  */
531 typedef void (*MainTest) (struct RPSPeer *rps_peer);
532
533 /**
534  * Callback called once the requested random peers are available
535  */
536 typedef void (*ReplyHandle) (void *cls,
537                              uint64_t n,
538                              const struct GNUNET_PeerIdentity *recv_peers);
539
540 /**
541  * Called directly before disconnecting from the service
542  */
543 typedef void (*PostTest) (struct RPSPeer *peer);
544
545 /**
546  * Function called after disconnect to evaluate test success
547  */
548 typedef int (*EvaluationCallback) (void);
549
550 /**
551  * @brief Do we have Churn?
552  */
553 enum OPTION_CHURN {
554   /**
555    * @brief If we have churn this is set
556    */
557   HAVE_CHURN,
558   /**
559    * @brief If we have no churn this is set
560    */
561   HAVE_NO_CHURN,
562 };
563
564 /**
565  * @brief Is it ok to quit the test before the timeout?
566  */
567 enum OPTION_QUICK_QUIT {
568   /**
569    * @brief It is ok for the test to quit before the timeout triggers
570    */
571   HAVE_QUICK_QUIT,
572
573   /**
574    * @brief It is NOT ok for the test to quit before the timeout triggers
575    */
576   HAVE_NO_QUICK_QUIT,
577 };
578
579 /**
580  * @brief Do we collect statistics at the end?
581  */
582 enum OPTION_COLLECT_STATISTICS {
583   /**
584    * @brief We collect statistics at the end
585    */
586   COLLECT_STATISTICS,
587
588   /**
589    * @brief We do not collect statistics at the end
590    */
591   NO_COLLECT_STATISTICS,
592 };
593
594 /**
595  * @brief Do we collect views during run?
596  */
597 enum OPTION_COLLECT_VIEW {
598   /**
599    * @brief We collect view during run
600    */
601   COLLECT_VIEW,
602
603   /**
604    * @brief We do not collect the view during run
605    */
606   NO_COLLECT_VIEW,
607 };
608
609 /**
610  * Structure to define a single test
611  */
612 struct SingleTestRun
613 {
614   /**
615    * Name of the test
616    */
617   char *name;
618
619   /**
620    * Called with a single peer in order to initialise that peer
621    */
622   InitPeer init_peer;
623
624   /**
625    * Called directly after connecting to the service
626    */
627   PreTest pre_test;
628
629   /**
630    * Main function for each peer
631    */
632   MainTest main_test;
633
634   /**
635    * Callback called once the requested peers are available
636    */
637   ReplyHandle reply_handle;
638
639   /**
640    * Called directly before disconnecting from the service
641    */
642   PostTest post_test;
643
644   /**
645    * Function to evaluate the test results
646    */
647   EvaluationCallback eval_cb;
648
649   /**
650    * Request interval
651    */
652   uint32_t request_interval;
653
654   /**
655    * Number of Requests to make.
656    */
657   uint32_t num_requests;
658
659   /**
660    * Run with (-out) churn
661    */
662   enum OPTION_CHURN have_churn;
663
664   /**
665    * Quit test before timeout?
666    */
667   enum OPTION_QUICK_QUIT have_quick_quit;
668
669   /**
670    * Collect statistics at the end?
671    */
672   enum OPTION_COLLECT_STATISTICS have_collect_statistics;
673
674   /**
675    * Collect view during run?
676    */
677   enum OPTION_COLLECT_VIEW have_collect_view;
678
679   /**
680    * @brief Mark which values from the statistics service to collect at the end
681    * of the run
682    */
683   uint32_t stat_collect_flags;
684 } cur_test_run;
685
686 /**
687  * Did we finish the test?
688  */
689 static int post_test;
690
691 /**
692  * Are we shutting down?
693  */
694 static int in_shutdown;
695
696 /**
697  * Append arguments to file
698  */
699 static void
700 tofile_ (const char *file_name, const char *line)
701 {
702   struct GNUNET_DISK_FileHandle *f;
703   /* char output_buffer[512]; */
704   size_t size;
705   /* int size; */
706   size_t size2;
707
708   if (NULL == (f = GNUNET_DISK_file_open (file_name,
709                                           GNUNET_DISK_OPEN_APPEND |
710                                           GNUNET_DISK_OPEN_WRITE |
711                                           GNUNET_DISK_OPEN_CREATE,
712                                           GNUNET_DISK_PERM_USER_READ |
713                                           GNUNET_DISK_PERM_USER_WRITE |
714                                           GNUNET_DISK_PERM_GROUP_READ |
715                                           GNUNET_DISK_PERM_OTHER_READ)))
716   {
717     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
718                 "Not able to open file %s\n",
719                 file_name);
720     return;
721   }
722   /* size = GNUNET_snprintf (output_buffer,
723                           sizeof (output_buffer),
724                           "%llu %s\n",
725                           GNUNET_TIME_absolute_get ().abs_value_us,
726                           line);
727   if (0 > size)
728   {
729     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
730                 "Failed to write string to buffer (size: %i)\n",
731                 size);
732     return;
733   } */
734
735   size = strlen (line) * sizeof (char);
736
737   size2 = GNUNET_DISK_file_write (f, line, size);
738   if (size != size2)
739   {
740     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
741                 "Unable to write to file! (Size: %lu, size2: %lu)\n",
742                 size,
743                 size2);
744     if (GNUNET_YES != GNUNET_DISK_file_close (f))
745     {
746       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
747                   "Unable to close file\n");
748     }
749     return;
750   }
751
752   if (GNUNET_YES != GNUNET_DISK_file_close (f))
753   {
754     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
755                 "Unable to close file\n");
756   }
757 }
758
759 /**
760  * This function is used to facilitate writing important information to disk
761  */
762 #define tofile(file_name, ...) do {\
763   char tmp_buf[512];\
764     int size;\
765     size = GNUNET_snprintf(tmp_buf,sizeof(tmp_buf),__VA_ARGS__);\
766     if (0 > size)\
767       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,\
768                      "Failed to create tmp_buf\n");\
769     else\
770       tofile_(file_name,tmp_buf);\
771   } while (0);
772
773
774 /**
775  * Write the ids and their according index in the given array to a file
776  * Unused
777  */
778 /* static void
779 ids_to_file (char *file_name,
780              struct GNUNET_PeerIdentity *peer_ids,
781              unsigned int num_peer_ids)
782 {
783   unsigned int i;
784
785   for (i=0 ; i < num_peer_ids ; i++)
786   {
787     to_file (file_name,
788              "%u\t%s",
789              i,
790              GNUNET_i2s_full (&peer_ids[i]));
791   }
792 } */
793
794 /**
795  * Test the success of a single test
796  */
797 static int
798 evaluate (void)
799 {
800   unsigned int i;
801   int tmp_ok;
802
803   tmp_ok = 1;
804
805   for (i = 0; i < num_peers; i++)
806   {
807     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
808         "%u. peer [%s] received %u of %u expected peer_ids: %i\n",
809         i,
810         GNUNET_i2s (rps_peers[i].peer_id),
811         rps_peers[i].num_recv_ids,
812         rps_peers[i].num_ids_to_request,
813         (rps_peers[i].num_ids_to_request == rps_peers[i].num_recv_ids));
814     tmp_ok &= (rps_peers[i].num_ids_to_request == rps_peers[i].num_recv_ids);
815   }
816   return tmp_ok? 0 : 1;
817 }
818
819
820 /**
821  * Creates an oplist entry and adds it to the oplist DLL
822  */
823 static struct OpListEntry *
824 make_oplist_entry ()
825 {
826   struct OpListEntry *entry;
827
828   entry = GNUNET_new (struct OpListEntry);
829   GNUNET_CONTAINER_DLL_insert_tail (oplist_head, oplist_tail, entry);
830   return entry;
831 }
832
833
834 /**
835  * @brief Checks if given peer already received its statistics value from the
836  * statistics service.
837  *
838  * @param rps_peer the peer to check for
839  *
840  * @return #GNUNET_YES if so
841  *         #GNUNET_NO otherwise
842  */
843 static int check_statistics_collect_completed_single_peer (
844     const struct RPSPeer *rps_peer)
845 {
846   if (cur_test_run.stat_collect_flags !=
847         (cur_test_run.stat_collect_flags &
848           rps_peer->stat_collected_flags))
849   {
850     return GNUNET_NO;
851   }
852   return GNUNET_YES;
853 }
854 /**
855  * @brief Checks if all peers already received their statistics value from the
856  * statistics service.
857  *
858  * @return #GNUNET_YES if so
859  *         #GNUNET_NO otherwise
860  */
861 static int check_statistics_collect_completed ()
862 {
863   uint32_t i;
864
865   for (i = 0; i < num_peers; i++)
866   {
867     if (GNUNET_NO == check_statistics_collect_completed_single_peer (&rps_peers[i]))
868     {
869       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
870           "At least Peer %" PRIu32 " did not yet receive all statistics values\n",
871           i);
872       return GNUNET_NO;
873     }
874   }
875   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
876       "All peers received their statistics values\n");
877   return GNUNET_YES;
878 }
879
880 static void
881 rps_disconnect_adapter (void *cls,
882                         void *op_result);
883
884 static void
885 cancel_pending_req (struct PendingRequest *pending_req)
886 {
887   struct RPSPeer *rps_peer;
888
889   rps_peer = pending_req->rps_peer;
890   GNUNET_CONTAINER_DLL_remove (rps_peer->pending_req_head,
891                                rps_peer->pending_req_tail,
892                                pending_req);
893   rps_peer->num_pending_reqs--;
894   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
895               "Cancelling pending rps get request\n");
896   GNUNET_SCHEDULER_cancel (pending_req->request_task);
897   GNUNET_free (pending_req);
898 }
899
900 static void
901 cancel_request (struct PendingReply *pending_rep)
902 {
903   struct RPSPeer *rps_peer;
904
905   rps_peer = pending_rep->rps_peer;
906   GNUNET_CONTAINER_DLL_remove (rps_peer->pending_rep_head,
907                                rps_peer->pending_rep_tail,
908                                pending_rep);
909   rps_peer->num_pending_reps--;
910   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
911               "Cancelling rps get reply\n");
912   GNUNET_RPS_request_cancel (pending_rep->req_handle);
913   GNUNET_free (pending_rep);
914 }
915
916 void
917 clean_peer (unsigned peer_index)
918 {
919   struct PendingRequest *pending_req;
920
921   while (NULL != (pending_req = rps_peers[peer_index].pending_req_head))
922   {
923     cancel_pending_req (pending_req);
924   }
925   pending_req = rps_peers[peer_index].pending_req_head;
926   rps_disconnect_adapter (&rps_peers[peer_index],
927                           &rps_peers[peer_index].rps_handle);
928   for (unsigned stat_type = STAT_TYPE_ROUNDS;
929        stat_type < STAT_TYPE_MAX;
930        stat_type++)
931   {
932     if (NULL != rps_peers[peer_index].h_stat_get[stat_type])
933     {
934       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
935                   "(%u) did not yet receive stat value for `%s'\n",
936                   rps_peers[peer_index].index,
937                   stat_type_strings[stat_type]);
938       GNUNET_STATISTICS_get_cancel (
939           rps_peers[peer_index].h_stat_get[stat_type]);
940     }
941   }
942   if (NULL != rps_peers[peer_index].op)
943   {
944     GNUNET_TESTBED_operation_done (rps_peers[peer_index].op);
945     rps_peers[peer_index].op = NULL;
946   }
947 }
948
949 /**
950  * Task run on timeout to shut everything down.
951  */
952 static void
953 shutdown_op (void *cls)
954 {
955   unsigned int i;
956   struct OpListEntry *entry;
957   (void) cls;
958
959   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
960               "Shutdown task scheduled, going down.\n");
961   in_shutdown = GNUNET_YES;
962
963   if (NULL != shutdown_task)
964   {
965     GNUNET_SCHEDULER_cancel (shutdown_task);
966     shutdown_task = NULL;
967   }
968   if (NULL != post_test_task)
969   {
970     GNUNET_SCHEDULER_cancel (post_test_task);
971     post_test_task = NULL;
972   }
973   if (NULL != churn_task)
974   {
975     GNUNET_SCHEDULER_cancel (churn_task);
976     churn_task = NULL;
977   }
978   entry = oplist_head;
979   while (NULL != (entry = oplist_head))
980   {
981     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
982                 "Operation still pending on shutdown (%u)\n",
983                 entry->index);
984     GNUNET_TESTBED_operation_done (entry->op);
985     GNUNET_CONTAINER_DLL_remove (oplist_head, oplist_tail, entry);
986     GNUNET_free (entry);
987   }
988   for (i = 0; i < num_peers; i++)
989   {
990     clean_peer (i);
991   }
992 }
993
994 static void
995 trigger_shutdown (void *cls)
996 {
997   (void) cls;
998
999   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1000               "Shutdown was triggerd by timeout, going down.\n");
1001   shutdown_task = NULL;
1002   GNUNET_SCHEDULER_shutdown ();
1003 }
1004
1005
1006 /**
1007  * Task run after #duration to collect statistics and potentially shut down.
1008  */
1009 static void
1010 post_test_op (void *cls)
1011 {
1012   unsigned int i;
1013   (void) cls;
1014
1015   post_test_task = NULL;
1016   post_test = GNUNET_YES;
1017   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1018               "Post test task scheduled.\n");
1019   if (NULL != churn_task)
1020   {
1021     GNUNET_SCHEDULER_cancel (churn_task);
1022     churn_task = NULL;
1023   }
1024   for (i = 0; i < num_peers; i++)
1025   {
1026     if (NULL != rps_peers[i].op)
1027     {
1028       GNUNET_TESTBED_operation_done (rps_peers[i].op);
1029       rps_peers[i].op = NULL;
1030     }
1031     if (NULL != cur_test_run.post_test)
1032     {
1033       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Executing post_test for peer %u\n", i);
1034       cur_test_run.post_test (&rps_peers[i]);
1035     }
1036   }
1037   /* If we do not collect statistics, shut down directly */
1038   if (NO_COLLECT_STATISTICS == cur_test_run.have_collect_statistics ||
1039       GNUNET_YES == check_statistics_collect_completed())
1040   {
1041     GNUNET_SCHEDULER_cancel (shutdown_task);
1042     shutdown_task = NULL;
1043     GNUNET_SCHEDULER_shutdown ();
1044   }
1045 }
1046
1047
1048 /**
1049  * Seed peers.
1050  */
1051 static void
1052 seed_peers (void *cls)
1053 {
1054   struct RPSPeer *peer = cls;
1055   unsigned int amount;
1056   unsigned int i;
1057
1058   // TODO if malicious don't seed mal peers
1059   amount = round (.5 * num_peers);
1060
1061   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Seeding peers:\n");
1062   for (i = 0 ; i < amount ; i++)
1063     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Seeding %u. peer: %s\n",
1064                 i,
1065                 GNUNET_i2s (&rps_peer_ids[i]));
1066
1067   GNUNET_RPS_seed_ids (peer->rps_handle, amount, rps_peer_ids);
1068 }
1069
1070
1071 /**
1072  * Get the id of peer i.
1073  */
1074   void
1075 info_cb (void *cb_cls,
1076          struct GNUNET_TESTBED_Operation *op,
1077          const struct GNUNET_TESTBED_PeerInformation *pinfo,
1078          const char *emsg)
1079 {
1080   struct OpListEntry *entry = (struct OpListEntry *) cb_cls;
1081   (void) op;
1082
1083   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1084   {
1085     return;
1086   }
1087
1088   if (NULL == pinfo || NULL != emsg)
1089   {
1090     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Got Error: %s\n", emsg);
1091     GNUNET_TESTBED_operation_done (entry->op);
1092     return;
1093   }
1094
1095   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1096               "Peer %u is %s\n",
1097               entry->index,
1098               GNUNET_i2s (pinfo->result.id));
1099
1100   rps_peer_ids[entry->index] = *(pinfo->result.id);
1101   rps_peers[entry->index].peer_id = &rps_peer_ids[entry->index];
1102
1103   GNUNET_assert (GNUNET_OK ==
1104       GNUNET_CONTAINER_multipeermap_put (peer_map,
1105         &rps_peer_ids[entry->index],
1106         &rps_peers[entry->index],
1107         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1108   tofile ("/tmp/rps/peer_ids",
1109            "%u\t%s\n",
1110            entry->index,
1111            GNUNET_i2s_full (&rps_peer_ids[entry->index]));
1112
1113   GNUNET_CONTAINER_DLL_remove (oplist_head, oplist_tail, entry);
1114   GNUNET_TESTBED_operation_done (entry->op);
1115   GNUNET_free (entry);
1116 }
1117
1118
1119 /**
1120  * Callback to be called when RPS service connect operation is completed
1121  *
1122  * @param cls the callback closure from functions generating an operation
1123  * @param op the operation that has been finished
1124  * @param ca_result the RPS service handle returned from rps_connect_adapter
1125  * @param emsg error message in case the operation has failed; will be NULL if
1126  *          operation has executed successfully.
1127  */
1128 static void
1129 rps_connect_complete_cb (void *cls,
1130                          struct GNUNET_TESTBED_Operation *op,
1131                          void *ca_result,
1132                          const char *emsg)
1133 {
1134   struct RPSPeer *rps_peer = cls;
1135   struct GNUNET_RPS_Handle *rps = ca_result;
1136
1137   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1138   {
1139     return;
1140   }
1141
1142   rps_peer->rps_handle = rps;
1143   rps_peer->online = GNUNET_YES;
1144   num_peers_online++;
1145
1146   GNUNET_assert (op == rps_peer->op);
1147   if (NULL != emsg)
1148   {
1149     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1150                 "Failed to connect to RPS service: %s\n",
1151                 emsg);
1152     ok = 1;
1153     GNUNET_SCHEDULER_shutdown ();
1154     return;
1155   }
1156
1157   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1158               "Started client successfully (%u)\n",
1159               rps_peer->index);
1160
1161   cur_test_run.main_test (rps_peer);
1162 }
1163
1164
1165 /**
1166  * Adapter function called to establish a connection to
1167  * the RPS service.
1168  *
1169  * @param cls closure
1170  * @param cfg configuration of the peer to connect to; will be available until
1171  *          GNUNET_TESTBED_operation_done() is called on the operation returned
1172  *          from GNUNET_TESTBED_service_connect()
1173  * @return service handle to return in 'op_result', NULL on error
1174  */
1175 static void *
1176 rps_connect_adapter (void *cls,
1177                      const struct GNUNET_CONFIGURATION_Handle *cfg)
1178 {
1179   struct GNUNET_RPS_Handle *h;
1180
1181   h = GNUNET_RPS_connect (cfg);
1182
1183   if (NULL != cur_test_run.pre_test)
1184     cur_test_run.pre_test (cls, h);
1185
1186   return h;
1187 }
1188
1189 /**
1190  * Called to open a connection to the peer's statistics
1191  *
1192  * @param cls peer context
1193  * @param cfg configuration of the peer to connect to; will be available until
1194  *          GNUNET_TESTBED_operation_done() is called on the operation returned
1195  *          from GNUNET_TESTBED_service_connect()
1196  * @return service handle to return in 'op_result', NULL on error
1197  */
1198 static void *
1199 stat_connect_adapter (void *cls,
1200                       const struct GNUNET_CONFIGURATION_Handle *cfg)
1201 {
1202   struct RPSPeer *peer = cls;
1203
1204   peer->stats_h = GNUNET_STATISTICS_create ("rps-profiler", cfg);
1205   return peer->stats_h;
1206 }
1207
1208 /**
1209  * Called to disconnect from peer's statistics service
1210  *
1211  * @param cls peer context
1212  * @param op_result service handle returned from the connect adapter
1213  */
1214 static void
1215 stat_disconnect_adapter (void *cls, void *op_result)
1216 {
1217   struct RPSPeer *peer = cls;
1218
1219   //GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch_cancel
1220   //              (peer->stats_h, "core", "# peers connected",
1221   //               stat_iterator, peer));
1222   //GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch_cancel
1223   //              (peer->stats_h, "nse", "# peers connected",
1224   //               stat_iterator, peer));
1225   GNUNET_STATISTICS_destroy (op_result, GNUNET_NO);
1226   peer->stats_h = NULL;
1227 }
1228
1229 /**
1230  * Called after successfully opening a connection to a peer's statistics
1231  * service; we register statistics monitoring for CORE and NSE here.
1232  *
1233  * @param cls the callback closure from functions generating an operation
1234  * @param op the operation that has been finished
1235  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
1236  * @param emsg error message in case the operation has failed; will be NULL if
1237  *          operation has executed successfully.
1238  */
1239 static void
1240 stat_complete_cb (void *cls,
1241                   struct GNUNET_TESTBED_Operation *op,
1242                   void *ca_result,
1243                   const char *emsg )
1244 {
1245   //struct GNUNET_STATISTICS_Handle *sh = ca_result;
1246   //struct RPSPeer *peer = (struct RPSPeer *) cls;
1247   (void) cls;
1248   (void) op;
1249   (void) ca_result;
1250
1251   if (NULL != emsg)
1252   {
1253     GNUNET_break (0);
1254     return;
1255   }
1256   //GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch
1257   //              (sh, "core", "# peers connected",
1258   //               stat_iterator, peer));
1259   //GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch
1260   //              (sh, "nse", "# peers connected",
1261   //               stat_iterator, peer));
1262 }
1263
1264
1265 /**
1266  * Adapter function called to destroy connection to
1267  * RPS service.
1268  *
1269  * @param cls closure
1270  * @param op_result service handle returned from the connect adapter
1271  */
1272 static void
1273 rps_disconnect_adapter (void *cls,
1274                         void *op_result)
1275 {
1276   struct RPSPeer *peer = cls;
1277   struct GNUNET_RPS_Handle *h = op_result;
1278   struct PendingReply *pending_rep;
1279
1280   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1281               "disconnect_adapter (%u)\n",
1282               peer->index);
1283   GNUNET_assert (NULL != peer);
1284   if (NULL != peer->rps_handle)
1285   {
1286     while (NULL != (pending_rep = peer->pending_rep_head))
1287     {
1288       cancel_request (pending_rep);
1289     }
1290     GNUNET_assert (h == peer->rps_handle);
1291     GNUNET_RPS_disconnect (h);
1292     peer->rps_handle = NULL;
1293   }
1294 }
1295
1296
1297 /***********************************************************************
1298  * Definition of tests
1299 ***********************************************************************/
1300
1301 /**
1302  * Callback to call on receipt of a reply
1303  *
1304  * @param cls closure
1305  * @param n number of peers
1306  * @param recv_peers the received peers
1307  */
1308 static void
1309 default_reply_handle (void *cls,
1310                       uint64_t n,
1311                       const struct GNUNET_PeerIdentity *recv_peers)
1312 {
1313   struct RPSPeer *rps_peer;
1314   struct PendingReply *pending_rep = (struct PendingReply *) cls;
1315   unsigned int i;
1316
1317   rps_peer = pending_rep->rps_peer;
1318   GNUNET_CONTAINER_DLL_remove (rps_peer->pending_rep_head,
1319                                rps_peer->pending_rep_tail,
1320                                pending_rep);
1321   rps_peer->num_pending_reps--;
1322   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1323               "[%s] got %" PRIu64 " peers:\n",
1324               GNUNET_i2s (rps_peer->peer_id),
1325               n);
1326
1327   for (i = 0; i < n; i++)
1328   {
1329     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1330                 "%u: %s\n",
1331                 i,
1332                 GNUNET_i2s (&recv_peers[i]));
1333
1334     rps_peer->num_recv_ids++;
1335   }
1336
1337   if (GNUNET_YES != post_test) return;
1338   if (HAVE_QUICK_QUIT != cur_test_run.have_quick_quit) return;
1339   if (0 == evaluate())
1340   {
1341     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1342                 "Test succeeded before end of duration\n");
1343     if (NULL != post_test_task) GNUNET_SCHEDULER_cancel (post_test_task);
1344     post_test_task = GNUNET_SCHEDULER_add_now (&post_test_op, NULL);
1345     GNUNET_assert (NULL != post_test_task);
1346   }
1347 }
1348
1349 /**
1350  * Request random peers.
1351  */
1352 static void
1353 request_peers (void *cls)
1354 {
1355   struct PendingRequest *pending_req = cls;
1356   struct RPSPeer *rps_peer;
1357   struct PendingReply *pending_rep;
1358
1359   rps_peer = pending_req->rps_peer;
1360   GNUNET_assert (1 <= rps_peer->num_pending_reqs);
1361   GNUNET_CONTAINER_DLL_remove (rps_peer->pending_req_head,
1362                                rps_peer->pending_req_tail,
1363                                pending_req);
1364   rps_peer->num_pending_reqs--;
1365   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test) return;
1366   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1367               "Requesting one peer\n");
1368   pending_rep = GNUNET_new (struct PendingReply);
1369   pending_rep->rps_peer = rps_peer;
1370   pending_rep->req_handle = GNUNET_RPS_request_peers (rps_peer->rps_handle,
1371       1,
1372       cur_test_run.reply_handle,
1373       pending_rep);
1374   GNUNET_CONTAINER_DLL_insert_tail (rps_peer->pending_rep_head,
1375                                     rps_peer->pending_rep_tail,
1376                                     pending_rep);
1377   rps_peer->num_pending_reps++;
1378 }
1379
1380
1381 /**
1382  * Schedule requests for peer @a rps_peer that have neither been scheduled, nor
1383  * issued, nor replied
1384  */
1385 void
1386 schedule_missing_requests (struct RPSPeer *rps_peer)
1387 {
1388   unsigned int i;
1389   struct PendingRequest *pending_req;
1390
1391   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1392       "Scheduling %u - %u missing requests\n",
1393       rps_peer->num_ids_to_request,
1394       rps_peer->num_pending_reqs + rps_peer->num_pending_reps);
1395   GNUNET_assert (rps_peer->num_pending_reqs + rps_peer->num_pending_reps <=
1396       rps_peer->num_ids_to_request);
1397   for (i = rps_peer->num_pending_reqs + rps_peer->num_pending_reps;
1398        i < rps_peer->num_ids_to_request; i++)
1399   {
1400     pending_req = GNUNET_new (struct PendingRequest);
1401     pending_req->rps_peer = rps_peer;
1402     pending_req->request_task = GNUNET_SCHEDULER_add_delayed (
1403         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
1404           cur_test_run.request_interval * i),
1405         request_peers,
1406         pending_req);
1407     GNUNET_CONTAINER_DLL_insert_tail (rps_peer->pending_req_head,
1408                                       rps_peer->pending_req_tail,
1409                                       pending_req);
1410     rps_peer->num_pending_reqs++;
1411   }
1412 }
1413
1414 void
1415 cancel_pending_req_rep (struct RPSPeer *rps_peer)
1416 {
1417   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1418       "Cancelling all (pending) requests.\n");
1419   while (NULL != rps_peer->pending_req_head)
1420     cancel_pending_req (rps_peer->pending_req_head);
1421   GNUNET_assert (0 == rps_peer->num_pending_reqs);
1422   while (NULL != rps_peer->pending_rep_head)
1423     cancel_request (rps_peer->pending_rep_head);
1424   GNUNET_assert (0 == rps_peer->num_pending_reps);
1425 }
1426
1427 /***********************************
1428  * MALICIOUS
1429 ***********************************/
1430
1431 /**
1432  * Initialise only non-mal RPSPeers
1433  */
1434 static void mal_init_peer (struct RPSPeer *rps_peer)
1435 {
1436   if (rps_peer->index >= round (portion * num_peers))
1437     rps_peer->num_ids_to_request = 1;
1438 }
1439
1440
1441 /**
1442  * @brief Set peers to (non-)malicious before execution
1443  *
1444  * Of signature #PreTest
1445  *
1446  * @param rps_peer the peer to set (non-) malicious
1447  * @param h the handle to the service
1448  */
1449 static void
1450 mal_pre (struct RPSPeer *rps_peer, struct GNUNET_RPS_Handle *h)
1451 {
1452   #ifdef ENABLE_MALICIOUS
1453   uint32_t num_mal_peers;
1454
1455   GNUNET_assert ( (1 >= portion) &&
1456                   (0 <  portion) );
1457   num_mal_peers = round (portion * num_peers);
1458
1459   if (rps_peer->index < num_mal_peers)
1460   {
1461     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1462                 "%u. peer [%s] of %" PRIu32 " malicious peers turning malicious\n",
1463                 rps_peer->index,
1464                 GNUNET_i2s (rps_peer->peer_id),
1465                 num_mal_peers);
1466
1467     GNUNET_RPS_act_malicious (h, mal_type, num_mal_peers,
1468                               rps_peer_ids, target_peer);
1469   }
1470   #endif /* ENABLE_MALICIOUS */
1471 }
1472
1473 static void
1474 mal_cb (struct RPSPeer *rps_peer)
1475 {
1476   uint32_t num_mal_peers;
1477
1478   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1479   {
1480     return;
1481   }
1482
1483   #ifdef ENABLE_MALICIOUS
1484   GNUNET_assert ( (1 >= portion) &&
1485                   (0 <  portion) );
1486   num_mal_peers = round (portion * num_peers);
1487
1488   if (rps_peer->index >= num_mal_peers)
1489   { /* It's useless to ask a malicious peer about a random sample -
1490        it's not sampling */
1491     GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2),
1492                                   seed_peers, rps_peer);
1493     schedule_missing_requests (rps_peer);
1494   }
1495   #endif /* ENABLE_MALICIOUS */
1496 }
1497
1498 /***********************************
1499  * CHURN
1500 ***********************************/
1501
1502 static void
1503 churn (void *cls);
1504
1505 /**
1506  * @brief Starts churn
1507  *
1508  * Has signature of #MainTest
1509  *
1510  * This is not implemented too nicely as this is called for each peer, but we
1511  * only need to call it once. (Yes we check that we only schedule the task
1512  * once.)
1513  *
1514  * @param rps_peer The peer it's called for
1515  */
1516 static void
1517 churn_test_cb (struct RPSPeer *rps_peer)
1518 {
1519   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1520   {
1521     return;
1522   }
1523
1524   /* Start churn */
1525   if (HAVE_CHURN == cur_test_run.have_churn && NULL == churn_task)
1526   {
1527     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1528                 "Starting churn task\n");
1529     churn_task = GNUNET_SCHEDULER_add_delayed (
1530           GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5),
1531           churn,
1532           NULL);
1533   } else {
1534     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1535                 "Not starting churn task\n");
1536   }
1537
1538   schedule_missing_requests (rps_peer);
1539 }
1540
1541 /***********************************
1542  * PROFILER
1543 ***********************************/
1544
1545 /**
1546  * Callback to be called when RPS service is started or stopped at peers
1547  *
1548  * @param cls NULL
1549  * @param op the operation handle
1550  * @param emsg NULL on success; otherwise an error description
1551  */
1552 static void
1553 churn_cb (void *cls,
1554           struct GNUNET_TESTBED_Operation *op,
1555           const char *emsg)
1556 {
1557   // FIXME
1558   struct OpListEntry *entry = cls;
1559   (void) op;
1560
1561   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1562   {
1563     return;
1564   }
1565
1566   GNUNET_TESTBED_operation_done (entry->op);
1567   if (NULL != emsg)
1568   {
1569     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Failed to start/stop RPS at a peer\n");
1570     GNUNET_SCHEDULER_shutdown ();
1571     return;
1572   }
1573   GNUNET_assert (0 != entry->delta);
1574
1575   num_peers_online += entry->delta;
1576
1577   if (PEER_GO_OFFLINE == entry->delta)
1578   { /* Peer hopefully just went offline */
1579     if (GNUNET_YES != rps_peers[entry->index].online)
1580     {
1581       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1582                   "peer %s was expected to go offline but is still marked as online\n",
1583                   GNUNET_i2s (rps_peers[entry->index].peer_id));
1584       GNUNET_break (0);
1585     }
1586     else
1587     {
1588       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1589                   "peer %s probably went offline as expected\n",
1590                   GNUNET_i2s (rps_peers[entry->index].peer_id));
1591     }
1592     rps_peers[entry->index].online = GNUNET_NO;
1593   }
1594
1595   else if (PEER_GO_ONLINE < entry->delta)
1596   { /* Peer hopefully just went online */
1597     if (GNUNET_NO != rps_peers[entry->index].online)
1598     {
1599       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1600                   "peer %s was expected to go online but is still marked as offline\n",
1601                   GNUNET_i2s (rps_peers[entry->index].peer_id));
1602       GNUNET_break (0);
1603     }
1604     else
1605     {
1606       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1607                   "peer %s probably went online as expected\n",
1608                   GNUNET_i2s (rps_peers[entry->index].peer_id));
1609       if (NULL != cur_test_run.pre_test)
1610       {
1611         cur_test_run.pre_test (&rps_peers[entry->index],
1612             rps_peers[entry->index].rps_handle);
1613         schedule_missing_requests (&rps_peers[entry->index]);
1614       }
1615     }
1616     rps_peers[entry->index].online = GNUNET_YES;
1617   }
1618   else
1619   {
1620     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1621         "Invalid value for delta: %i\n", entry->delta);
1622     GNUNET_break (0);
1623   }
1624
1625   GNUNET_CONTAINER_DLL_remove (oplist_head, oplist_tail, entry);
1626   rps_peers[entry->index].entry_op_manage = NULL;
1627   GNUNET_free (entry);
1628   //if (num_peers_in_round[current_round] == peers_running)
1629   //  run_round ();
1630 }
1631
1632 /**
1633  * @brief Set the rps-service up or down for a specific peer
1634  *
1635  * @param i index of action
1636  * @param j index of peer
1637  * @param delta (#PEER_ONLINE_DELTA) down (-1) or up (1)
1638  * @param prob_go_on_off the probability of the action
1639  */
1640 static void
1641 manage_service_wrapper (unsigned int i, unsigned int j,
1642                         enum PEER_ONLINE_DELTA delta,
1643                         double prob_go_on_off)
1644 {
1645   struct OpListEntry *entry = NULL;
1646   uint32_t prob;
1647
1648   /* make sure that management operation is not already scheduled */
1649   if (NULL != rps_peers[j].entry_op_manage)
1650   {
1651     return;
1652   }
1653
1654   prob = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1655                                    UINT32_MAX);
1656   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1657               "%u. selected peer (%u: %s) is %s.\n",
1658               i,
1659               j,
1660               GNUNET_i2s (rps_peers[j].peer_id),
1661               (PEER_GO_ONLINE == delta) ? "online" : "offline");
1662   if (prob < prob_go_on_off * UINT32_MAX)
1663   {
1664     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1665                 "%s goes %s\n",
1666                 GNUNET_i2s (rps_peers[j].peer_id),
1667                 (PEER_GO_OFFLINE == delta) ? "offline" : "online");
1668
1669     if (PEER_GO_OFFLINE == delta)
1670       cancel_pending_req_rep (&rps_peers[j]);
1671     entry = make_oplist_entry ();
1672     entry->delta = delta;
1673     entry->index = j;
1674     entry->op = GNUNET_TESTBED_peer_manage_service (NULL,
1675                                                     testbed_peers[j],
1676                                                     "rps",
1677                                                     &churn_cb,
1678                                                     entry,
1679                                                     (PEER_GO_OFFLINE == delta) ? 0 : 1);
1680     rps_peers[j].entry_op_manage = entry;
1681   }
1682 }
1683
1684
1685 static void
1686 churn (void *cls)
1687 {
1688   unsigned int i;
1689   unsigned int j;
1690   double portion_online;
1691   unsigned int *permut;
1692   double prob_go_offline;
1693   double portion_go_online;
1694   double portion_go_offline;
1695   (void) cls;
1696
1697   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1698   {
1699     return;
1700   }
1701   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1702               "Churn function executing\n");
1703
1704   churn_task = NULL; /* Should be invalid by now */
1705
1706   /* Compute the probability for an online peer to go offline
1707    * this round */
1708   portion_online = num_peers_online * 1.0 / num_peers;
1709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1710               "Portion online: %f\n",
1711               portion_online);
1712   portion_go_online = ((1 - portion_online) * .5 * .66);
1713   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1714               "Portion that should go online: %f\n",
1715               portion_go_online);
1716   portion_go_offline = (portion_online + portion_go_online) - .75;
1717   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1718               "Portion that probably goes offline: %f\n",
1719               portion_go_offline);
1720   prob_go_offline = portion_go_offline / (portion_online * .5);
1721   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1722               "Probability of a selected online peer to go offline: %f\n",
1723               prob_go_offline);
1724
1725   permut = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
1726                                          (unsigned int) num_peers);
1727
1728   /* Go over 50% randomly chosen peers */
1729   for (i = 0; i < .5 * num_peers; i++)
1730   {
1731     j = permut[i];
1732
1733     /* If online, shut down with certain probability */
1734     if (GNUNET_YES == rps_peers[j].online)
1735     {
1736       manage_service_wrapper (i, j, -1, prob_go_offline);
1737     }
1738
1739     /* If offline, restart with certain probability */
1740     else if (GNUNET_NO == rps_peers[j].online)
1741     {
1742       manage_service_wrapper (i, j, 1, 0.66);
1743     }
1744   }
1745
1746   GNUNET_free (permut);
1747
1748   churn_task = GNUNET_SCHEDULER_add_delayed (
1749         GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 2),
1750         churn,
1751         NULL);
1752 }
1753
1754
1755 /**
1756  * Initialise given RPSPeer
1757  */
1758 static void profiler_init_peer (struct RPSPeer *rps_peer)
1759 {
1760   rps_peer->num_ids_to_request = cur_test_run.num_requests;
1761   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer shall request %i peers\n",
1762               rps_peer->num_ids_to_request);
1763 }
1764
1765
1766 /**
1767  * Callback to call on receipt of a reply
1768  *
1769  * @param cls closure
1770  * @param n number of peers
1771  * @param recv_peers the received peers
1772  */
1773 static void
1774 profiler_reply_handle (void *cls,
1775                       uint64_t n,
1776                       const struct GNUNET_PeerIdentity *recv_peers)
1777 {
1778   struct RPSPeer *rps_peer;
1779   struct RPSPeer *rcv_rps_peer;
1780   char file_name_buf[128];
1781   char file_name_dh_buf[128];
1782   char file_name_dhr_buf[128];
1783   char file_name_dhru_buf[128];
1784   char *file_name = file_name_buf;
1785   char *file_name_dh = file_name_dh_buf;
1786   char *file_name_dhr = file_name_dhr_buf;
1787   char *file_name_dhru = file_name_dhru_buf;
1788   unsigned int i;
1789   struct PendingReply *pending_rep = (struct PendingReply *) cls;
1790
1791   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "profiler_reply_handle()\n");
1792   rps_peer = pending_rep->rps_peer;
1793   (void) GNUNET_asprintf (&file_name,
1794                                        "/tmp/rps/received_ids-%u",
1795                                        rps_peer->index);
1796
1797   (void) GNUNET_asprintf (&file_name_dh,
1798                                        "/tmp/rps/diehard_input-%u",
1799                                        rps_peer->index);
1800   (void) GNUNET_asprintf (&file_name_dhr,
1801                                        "/tmp/rps/diehard_input_raw-%u",
1802                                        rps_peer->index);
1803   (void) GNUNET_asprintf (&file_name_dhru,
1804                                        "/tmp/rps/diehard_input_raw_aligned-%u",
1805                                        rps_peer->index);
1806   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1807               "[%s] got %" PRIu64 " peers:\n",
1808               GNUNET_i2s (rps_peer->peer_id),
1809               n);
1810   for (i = 0; i < n; i++)
1811   {
1812     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1813                 "%u: %s\n",
1814                 i,
1815                 GNUNET_i2s (&recv_peers[i]));
1816     tofile (file_name,
1817              "%s\n",
1818              GNUNET_i2s_full (&recv_peers[i]));
1819     rcv_rps_peer = GNUNET_CONTAINER_multipeermap_get (peer_map, &recv_peers[i]);
1820     GNUNET_assert (NULL != rcv_rps_peer);
1821     tofile (file_name_dh,
1822              "%" PRIu32 "\n",
1823              (uint32_t) rcv_rps_peer->index);
1824 #ifdef TO_FILE
1825     to_file_raw (file_name_dhr,
1826                 (char *) &rcv_rps_peer->index,
1827                  sizeof (uint32_t));
1828     to_file_raw_unaligned (file_name_dhru,
1829                           (char *) &rcv_rps_peer->index,
1830                            sizeof (uint32_t),
1831                            bits_needed);
1832 #endif /* TO_FILE */
1833   }
1834   default_reply_handle (cls, n, recv_peers);
1835 }
1836
1837
1838 static void
1839 profiler_cb (struct RPSPeer *rps_peer)
1840 {
1841   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1842   {
1843     return;
1844   }
1845
1846   /* Start churn */
1847   if (HAVE_CHURN == cur_test_run.have_churn && NULL == churn_task)
1848   {
1849     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1850                 "Starting churn task\n");
1851     churn_task = GNUNET_SCHEDULER_add_delayed (
1852           GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5),
1853           churn,
1854           NULL);
1855   } else {
1856     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1857                 "Not starting churn task\n");
1858   }
1859
1860   /* Only request peer ids at one peer.
1861    * (It's the before-last because last one is target of the focussed attack.)
1862    */
1863   if (0 < rps_peer->num_ids_to_request)
1864     schedule_missing_requests (rps_peer);
1865 }
1866
1867 /**
1868  * Function called from #profiler_eval with a filename.
1869  *
1870  * @param cls closure
1871  * @param filename complete filename (absolute path)
1872  * @return #GNUNET_OK to continue to iterate,
1873  *  #GNUNET_NO to stop iteration with no error,
1874  *  #GNUNET_SYSERR to abort iteration with error!
1875  */
1876 static int
1877 file_name_cb (void *cls, const char *filename)
1878 {
1879   if (NULL != strstr (filename, "sampler_el"))
1880   {
1881     struct RPS_SamplerElement *s_elem;
1882     struct GNUNET_CRYPTO_AuthKey auth_key;
1883     const char *key_char;
1884     uint32_t i;
1885     (void) cls;
1886
1887     key_char = filename + 20; /* Length of "/tmp/rps/sampler_el-" */
1888     tofile (filename, "--------------------------\n");
1889
1890     auth_key = string_to_auth_key (key_char);
1891     s_elem = RPS_sampler_elem_create ();
1892     RPS_sampler_elem_set (s_elem, auth_key);
1893
1894     for (i = 0; i < num_peers; i++)
1895     {
1896       RPS_sampler_elem_next (s_elem, &rps_peer_ids[i]);
1897     }
1898     RPS_sampler_elem_destroy (s_elem);
1899   }
1900   return GNUNET_OK;
1901 }
1902
1903 /**
1904  * This is run after the test finished.
1905  *
1906  * Compute all perfect samples.
1907  */
1908 static int
1909 profiler_eval (void)
1910 {
1911 #ifdef TO_FILE
1912   /* Compute perfect sample for each sampler element */
1913   if (-1 == GNUNET_DISK_directory_scan ("/tmp/rps/", file_name_cb, NULL))
1914   {
1915     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Scan of directory failed\n");
1916   }
1917 #endif /* TO_FILE */
1918
1919   return evaluate ();
1920 }
1921
1922 static uint32_t fac (uint32_t x)
1923 {
1924   if (1 >= x)
1925   {
1926     return x;
1927   }
1928   return x * fac (x - 1);
1929 }
1930
1931 static uint32_t binom (uint32_t n, uint32_t k)
1932 {
1933   //GNUNET_assert (n >= k);
1934   if (k > n) return 0;
1935   /* if (0 > n) return 0;  - always false */
1936   /* if (0 > k) return 0;  - always false */
1937   if (0 == k) return 1;
1938   return fac (n)
1939     /
1940     fac(k) * fac(n - k);
1941 }
1942
1943 /**
1944  * @brief is b in view of a?
1945  *
1946  * @param a
1947  * @param b
1948  *
1949  * @return
1950  */
1951 static int is_in_view (uint32_t a, uint32_t b)
1952 {
1953   uint32_t i;
1954   for (i = 0; i < rps_peers[a].cur_view_count; i++)
1955   {
1956     if (0 == memcmp (rps_peers[b].peer_id,
1957           &rps_peers[a].cur_view[i],
1958           sizeof (struct GNUNET_PeerIdentity)))
1959     {
1960       return GNUNET_YES;
1961     }
1962   }
1963   return GNUNET_NO;
1964 }
1965
1966 static uint32_t get_idx_of_pid (const struct GNUNET_PeerIdentity *pid)
1967 {
1968   uint32_t i;
1969
1970   for (i = 0; i < num_peers; i++)
1971   {
1972     if (0 == memcmp (pid,
1973           rps_peers[i].peer_id,
1974           sizeof (struct GNUNET_PeerIdentity)))
1975     {
1976       return i;
1977     }
1978   }
1979   //return 0; /* Should not happen - make compiler happy */
1980   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1981              "No known _PeerIdentity %s!\n",
1982              GNUNET_i2s_full (pid));
1983   GNUNET_assert (0);
1984 }
1985
1986 /**
1987  * @brief Counts number of peers in view of a that have b in their view
1988  *
1989  * @param a
1990  * @param uint32_tb
1991  *
1992  * @return
1993  */
1994 static uint32_t count_containing_views (uint32_t a, uint32_t b)
1995 {
1996   uint32_t i;
1997   uint32_t peer_idx;
1998   uint32_t count = 0;
1999
2000   for (i = 0; i < rps_peers[a].cur_view_count; i++)
2001   {
2002     peer_idx = get_idx_of_pid (&rps_peers[a].cur_view[i]);
2003     if (GNUNET_YES == is_in_view (peer_idx, b))
2004     {
2005       count++;
2006     }
2007   }
2008   return count;
2009 }
2010
2011 /**
2012  * @brief Computes the probability for each other peer to be selected by the
2013  * sampling process based on the views of all peers
2014  *
2015  * @param peer_idx index of the peer that is about to sample
2016  */
2017 static void compute_probabilities (uint32_t peer_idx)
2018 {
2019   //double probs[num_peers] = { 0 };
2020   double probs[num_peers];
2021   size_t probs_as_str_size = (num_peers * 10 + 1) * sizeof (char);
2022   char *probs_as_str = GNUNET_malloc (probs_as_str_size);
2023   char *probs_as_str_cpy;
2024   uint32_t i;
2025   double prob_push;
2026   double prob_pull;
2027   uint32_t view_size;
2028   uint32_t cont_views;
2029   uint32_t number_of_being_in_pull_events;
2030   int tmp;
2031   uint32_t count_non_zero_prob = 0;
2032
2033   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2034       "Computing probabilities for peer %" PRIu32 "\n", peer_idx);
2035   /* Firstly without knowledge of old views */
2036   for (i = 0; i < num_peers; i++)
2037   {
2038     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2039         "\tfor peer %" PRIu32 ":\n", i);
2040     view_size = rps_peers[i].cur_view_count;
2041     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2042         "\t\tview_size: %" PRIu32 "\n", view_size);
2043     /* For peer i the probability of being sampled is
2044      * evenly distributed among all possibly observed peers. */
2045     /* We could have observed a peer in three cases:
2046      *   1. peer sent a push
2047      *   2. peer was contained in a pull reply
2048      *   3. peer was in history (sampler) - ignored for now */
2049     /* 1. Probability of having received a push from peer i */
2050     if ((GNUNET_YES == is_in_view (i, peer_idx)) &&
2051         (1 <= (0.45 * view_size)))
2052     {
2053       if (0 == binom (view_size, 0.45 * view_size)) prob_push = 0;
2054       else
2055       {
2056         prob_push = 1.0 * binom (0.45 * view_size, 1)
2057           /
2058           binom (view_size, 0.45 * view_size);
2059       }
2060       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2061                  "\t\t%" PRIu32 " is in %" PRIu32 "'s view, prob: %f\n",
2062                  peer_idx,
2063                  i,
2064                  prob_push);
2065       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2066                  "\t\tposs choices from view: %" PRIu32 ", containing i: %" PRIu32 "\n",
2067                  binom (view_size, 0.45 * view_size),
2068                  binom (0.45 * view_size, 1));
2069     } else {
2070       prob_push = 0;
2071       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2072                  "\t\t%" PRIu32 " is not in %" PRIu32 "'s view, prob: 0\n",
2073                  peer_idx,
2074                  i);
2075     }
2076     /* 2. Probability of peer i being contained in pulls */
2077     view_size = rps_peers[peer_idx].cur_view_count;
2078     cont_views = count_containing_views (peer_idx, i);
2079     number_of_being_in_pull_events =
2080       (binom (view_size, 0.45 * view_size) -
2081        binom (view_size - cont_views, 0.45 * view_size));
2082     if (0 != number_of_being_in_pull_events)
2083     {
2084       prob_pull = number_of_being_in_pull_events
2085         /
2086         (1.0 * binom (view_size, 0.45 * view_size));
2087     } else
2088     {
2089       prob_pull = 0;
2090     }
2091     probs[i] = prob_push + prob_pull - (prob_push * prob_pull);
2092     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2093                "\t\t%" PRIu32 " has %" PRIu32 " of %" PRIu32
2094                " peers in its view who know %" PRIu32 " prob: %f\n",
2095                peer_idx,
2096                cont_views,
2097                view_size,
2098                i,
2099                prob_pull);
2100     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2101                "\t\tnumber of possible pull combinations: %" PRIu32 "\n",
2102                binom (view_size, 0.45 * view_size));
2103     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2104                "\t\tnumber of possible pull combinations without %" PRIu32
2105                ": %" PRIu32 "\n",
2106                i,
2107                binom (view_size - cont_views, 0.45 * view_size));
2108     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2109                "\t\tnumber of possible pull combinations with %" PRIu32
2110                ": %" PRIu32 "\n",
2111                i,
2112                number_of_being_in_pull_events);
2113
2114     if (0 != probs[i]) count_non_zero_prob++;
2115   }
2116   /* normalize */
2117   if (0 != count_non_zero_prob)
2118   {
2119     for (i = 0; i < num_peers; i++)
2120     {
2121       probs[i] = probs[i] * (1.0 / count_non_zero_prob);
2122     }
2123   } else {
2124     for (i = 0; i < num_peers; i++)
2125     {
2126       probs[i] = 0;
2127     }
2128   }
2129   /* str repr */
2130   for (i = 0; i < num_peers; i++)
2131   {
2132     probs_as_str_cpy = GNUNET_strndup (probs_as_str, probs_as_str_size);
2133     tmp = GNUNET_snprintf (probs_as_str,
2134                            probs_as_str_size,
2135                            "%s %7.6f", probs_as_str_cpy, probs[i]);
2136     GNUNET_free (probs_as_str_cpy);
2137     GNUNET_assert (0 <= tmp);
2138   }
2139
2140   to_file_w_len (rps_peers[peer_idx].file_name_probs,
2141                  probs_as_str_size,
2142                  probs_as_str);
2143   GNUNET_free (probs_as_str);
2144 }
2145
2146 /**
2147  * @brief This counts the number of peers in which views a given peer occurs.
2148  *
2149  * It also stores this value in the rps peer.
2150  *
2151  * @param peer_idx the index of the peer to count the representation
2152  *
2153  * @return the number of occurrences
2154  */
2155 static uint32_t count_peer_in_views_2 (uint32_t peer_idx)
2156 {
2157   uint32_t i, j;
2158   uint32_t count = 0;
2159
2160   for (i = 0; i < num_peers; i++) /* Peer in which view is counted */
2161   {
2162     for (j = 0; j < rps_peers[i].cur_view_count; j++) /* entry in view */
2163     {
2164       if (0 == memcmp (rps_peers[peer_idx].peer_id,
2165             &rps_peers[i].cur_view[j],
2166             sizeof (struct GNUNET_PeerIdentity)))
2167       {
2168         count++;
2169         break;
2170       }
2171     }
2172   }
2173   rps_peers[peer_idx].count_in_views = count;
2174   return count;
2175 }
2176
2177 static uint32_t cumulated_view_sizes ()
2178 {
2179   uint32_t i;
2180
2181   view_sizes = 0;
2182   for (i = 0; i < num_peers; i++) /* Peer in which view is counted */
2183   {
2184     view_sizes += rps_peers[i].cur_view_count;
2185   }
2186   return view_sizes;
2187 }
2188
2189 static void count_peer_in_views (uint32_t *count_peers)
2190 {
2191   uint32_t i, j;
2192
2193   for (i = 0; i < num_peers; i++) /* Peer in which view is counted */
2194   {
2195     for (j = 0; j < rps_peers[i].cur_view_count; j++) /* entry in view */
2196     {
2197       if (0 == memcmp (rps_peers[i].peer_id,
2198             &rps_peers[i].cur_view[j],
2199             sizeof (struct GNUNET_PeerIdentity)))
2200       {
2201         count_peers[i]++;
2202       }
2203     }
2204   }
2205 }
2206
2207 void compute_diversity ()
2208 {
2209   uint32_t i;
2210   /* ith entry represents the numer of occurrences in other peer's views */
2211   uint32_t *count_peers = GNUNET_new_array (num_peers, uint32_t);
2212   uint32_t views_total_size;
2213   double expected;
2214   /* deviation from expected number of peers */
2215   double *deviation = GNUNET_new_array (num_peers, double);
2216
2217   views_total_size = 0;
2218   expected = 0;
2219
2220   /* For each peer count its representation in other peer's views*/
2221   for (i = 0; i < num_peers; i++) /* Peer to count */
2222   {
2223     views_total_size += rps_peers[i].cur_view_count;
2224     count_peer_in_views (count_peers);
2225     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2226                "Counted representation of %" PRIu32 "th peer [%s]: %" PRIu32"\n",
2227                i,
2228                GNUNET_i2s (rps_peers[i].peer_id),
2229                count_peers[i]);
2230   }
2231
2232   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2233              "size of all views combined: %" PRIu32 "\n",
2234              views_total_size);
2235   expected = ((double) 1/num_peers) * views_total_size;
2236   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2237              "Expected number of occurrences of each peer in all views: %f\n",
2238              expected);
2239   for (i = 0; i < num_peers; i++) /* Peer to count */
2240   {
2241     deviation[i] = expected - count_peers[i];
2242     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2243                "Deviation from expectation: %f\n", deviation[i]);
2244   }
2245   GNUNET_free (count_peers);
2246   GNUNET_free (deviation);
2247 }
2248
2249 void print_view_sizes()
2250 {
2251   uint32_t i;
2252
2253   for (i = 0; i < num_peers; i++) /* Peer to count */
2254   {
2255     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2256                "View size of %" PRIu32 ". [%s] is %" PRIu32 "\n",
2257                i,
2258                GNUNET_i2s (rps_peers[i].peer_id),
2259                rps_peers[i].cur_view_count);
2260   }
2261 }
2262
2263 void all_views_updated_cb()
2264 {
2265   compute_diversity();
2266   print_view_sizes();
2267 }
2268
2269 void view_update_cb (void *cls,
2270                      uint64_t view_size,
2271                      const struct GNUNET_PeerIdentity *peers)
2272 {
2273   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2274               "View was updated (%" PRIu64 ")\n", view_size);
2275   struct RPSPeer *rps_peer = (struct RPSPeer *) cls;
2276   to_file ("/tmp/rps/view_sizes.txt",
2277          "%" PRIu64 " %" PRIu32 "",
2278          rps_peer->index,
2279          view_size);
2280   for (uint64_t i = 0; i < view_size; i++)
2281   {
2282     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2283                "\t%s\n", GNUNET_i2s (&peers[i]));
2284   }
2285   GNUNET_array_grow (rps_peer->cur_view,
2286                      rps_peer->cur_view_count,
2287                      view_size);
2288   //*rps_peer->cur_view = *peers;
2289   GNUNET_memcpy (rps_peer->cur_view,
2290                  peers,
2291                  view_size * sizeof (struct GNUNET_PeerIdentity));
2292   to_file ("/tmp/rps/count_in_views.txt",
2293          "%" PRIu64 " %" PRIu32 "",
2294          rps_peer->index,
2295          count_peer_in_views_2 (rps_peer->index));
2296   cumulated_view_sizes();
2297   if (0 != view_size)
2298   {
2299     to_file ("/tmp/rps/repr.txt",
2300            "%" PRIu64 /* index */
2301            " %" PRIu32 /* occurrence in views */
2302            " %" PRIu32 /* view sizes */
2303            " %f" /* fraction of repr in views */
2304            " %f" /* average view size */
2305            " %f" /* prob of occurrence in view slot */
2306            " %f" "", /* exp frac of repr in views */
2307            rps_peer->index,
2308            count_peer_in_views_2 (rps_peer->index),
2309            view_sizes,
2310            count_peer_in_views_2 (rps_peer->index) / (view_size * 1.0), /* fraction of representation in views */
2311            view_sizes / (view_size * 1.0), /* average view size */
2312            1.0 /view_size, /* prob of occurrence in view slot */
2313            (1.0/view_size) * (view_sizes/view_size) /* expected fraction of repr in views */
2314            );
2315   }
2316   compute_probabilities (rps_peer->index);
2317   all_views_updated_cb();
2318 }
2319
2320 static void
2321 pre_profiler (struct RPSPeer *rps_peer, struct GNUNET_RPS_Handle *h)
2322 {
2323   rps_peer->file_name_probs =
2324     store_prefix_file_name (rps_peer->peer_id, "probs");
2325   GNUNET_RPS_view_request (h, 0, view_update_cb, rps_peer);
2326 }
2327
2328 void write_final_stats (void){
2329   uint64_t sums[STAT_TYPE_MAX] = { 0 };
2330
2331   for (uint32_t i = 0; i < num_peers; i++)
2332   {
2333     to_file ("/tmp/rps/final_stats.csv",
2334              ", %" PRIu32 ", " /* index */
2335              "%s, %" /* id */
2336              PRIu64 ", %" /* rounds */
2337              PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" /* blocking */
2338              PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" /* issued */
2339              PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" /* sent */
2340              PRIu64 ", %" PRIu64 ", %" PRIu64 /* recv */,
2341              i,
2342              GNUNET_i2s (rps_peers[i].peer_id),
2343              rps_peers[i].stats[STAT_TYPE_ROUNDS],
2344              rps_peers[i].stats[STAT_TYPE_BLOCKS],
2345              rps_peers[i].stats[STAT_TYPE_BLOCKS_MANY_PUSH],
2346              rps_peers[i].stats[STAT_TYPE_BLOCKS_NO_PUSH],
2347              rps_peers[i].stats[STAT_TYPE_BLOCKS_NO_PULL],
2348              rps_peers[i].stats[STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL],
2349              rps_peers[i].stats[STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL],
2350              rps_peers[i].stats[STAT_TYPE_ISSUED_PUSH_SEND],
2351              rps_peers[i].stats[STAT_TYPE_ISSUED_PULL_REQ],
2352              rps_peers[i].stats[STAT_TYPE_ISSUED_PULL_REP],
2353              rps_peers[i].stats[STAT_TYPE_SENT_PUSH_SEND],
2354              rps_peers[i].stats[STAT_TYPE_SENT_PULL_REQ],
2355              rps_peers[i].stats[STAT_TYPE_SENT_PULL_REP],
2356              rps_peers[i].stats[STAT_TYPE_RECV_PUSH_SEND],
2357              rps_peers[i].stats[STAT_TYPE_RECV_PULL_REQ],
2358              rps_peers[i].stats[STAT_TYPE_RECV_PULL_REP]);
2359     for (enum STAT_TYPE stat_type = STAT_TYPE_ROUNDS;
2360          stat_type < STAT_TYPE_MAX;
2361          stat_type++)
2362     {
2363       sums[stat_type] += rps_peers[i].stats[stat_type];
2364     }
2365   }
2366   to_file ("/tmp/rps/final_stats.dat",
2367            "SUM %"
2368            PRIu64 " %" /* rounds */
2369            PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" /* blocking */
2370            PRIu64 " %" PRIu64 " %" PRIu64 " %" /* issued */
2371            PRIu64 " %" PRIu64 " %" PRIu64 " %" /* sent */
2372            PRIu64 " %" PRIu64 " %" PRIu64 /* recv */,
2373            sums[STAT_TYPE_ROUNDS],
2374            sums[STAT_TYPE_BLOCKS],
2375            sums[STAT_TYPE_BLOCKS_MANY_PUSH],
2376            sums[STAT_TYPE_BLOCKS_NO_PUSH],
2377            sums[STAT_TYPE_BLOCKS_NO_PULL],
2378            sums[STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL],
2379            sums[STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL],
2380            sums[STAT_TYPE_ISSUED_PUSH_SEND],
2381            sums[STAT_TYPE_ISSUED_PULL_REQ],
2382            sums[STAT_TYPE_ISSUED_PULL_REP],
2383            sums[STAT_TYPE_SENT_PUSH_SEND],
2384            sums[STAT_TYPE_SENT_PULL_REQ],
2385            sums[STAT_TYPE_SENT_PULL_REP],
2386            sums[STAT_TYPE_RECV_PUSH_SEND],
2387            sums[STAT_TYPE_RECV_PULL_REQ],
2388            sums[STAT_TYPE_RECV_PULL_REP]);
2389 }
2390
2391 /**
2392  * Continuation called by #GNUNET_STATISTICS_get() functions.
2393  *
2394  * Remembers that this specific statistics value was received for this peer.
2395  * Checks whether all peers received their statistics yet.
2396  * Issues the shutdown.
2397  *
2398  * @param cls closure
2399  * @param success #GNUNET_OK if statistics were
2400  *        successfully obtained, #GNUNET_SYSERR if not.
2401  */
2402 void
2403 post_test_shutdown_ready_cb (void *cls,
2404                              int success)
2405 {
2406   struct STATcls *stat_cls = (struct STATcls *) cls;
2407   struct RPSPeer *rps_peer = stat_cls->rps_peer;
2408
2409   rps_peer->h_stat_get[stat_cls->stat_type] = NULL;
2410   if (GNUNET_OK == success)
2411   {
2412     /* set flag that we we got the value */
2413     rps_peer->stat_collected_flags |= BIT(stat_cls->stat_type);
2414   } else {
2415     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2416         "Peer %u did not receive statistics value\n",
2417         rps_peer->index);
2418     GNUNET_free (stat_cls);
2419     GNUNET_break (0);
2420     return;
2421   }
2422
2423   if (NULL != rps_peer->stat_op &&
2424       GNUNET_YES == check_statistics_collect_completed_single_peer (rps_peer))
2425   {
2426     GNUNET_TESTBED_operation_done (rps_peer->stat_op);
2427   }
2428
2429   //write_final_stats ();
2430   if (GNUNET_YES == check_statistics_collect_completed())
2431   {
2432     write_final_stats ();
2433     GNUNET_free (stat_cls);
2434     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2435         "Shutting down\n");
2436     GNUNET_SCHEDULER_shutdown ();
2437   } else {
2438     GNUNET_free (stat_cls);
2439   }
2440 }
2441
2442 /**
2443  * Callback function to process statistic values.
2444  *
2445  * @param cls closure
2446  * @param subsystem name of subsystem that created the statistic
2447  * @param name the name of the datum
2448  * @param value the current value
2449  * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
2450  * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
2451  */
2452 int
2453 stat_iterator (void *cls,
2454                const char *subsystem,
2455                const char *name,
2456                uint64_t value,
2457                int is_persistent)
2458 {
2459   const struct STATcls *stat_cls = (const struct STATcls *) cls;
2460   struct RPSPeer *rps_peer = (struct RPSPeer *) stat_cls->rps_peer;
2461   enum STAT_TYPE stat_type;
2462   (void) subsystem;
2463   (void) is_persistent;
2464
2465   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got stat value: %s - %" PRIu64 "\n",
2466       name,
2467       value);
2468   to_file (rps_peer->file_name_stats,
2469           "%s: %" PRIu64 "\n",
2470           name,
2471           value);
2472   stat_type = stat_str_2_type (name);
2473   GNUNET_assert (STAT_TYPE_ROUNDS <= stat_type &&
2474                  STAT_TYPE_MAX > stat_type);
2475   rps_peer->stats[stat_type] = value;
2476   return GNUNET_OK;
2477 }
2478
2479 void post_profiler (struct RPSPeer *rps_peer)
2480 {
2481   if (COLLECT_STATISTICS != cur_test_run.have_collect_statistics)
2482   {
2483     return;
2484   }
2485
2486   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2487       "Going to request statistic values with mask 0x%" PRIx32 "\n",
2488       cur_test_run.stat_collect_flags);
2489
2490   struct STATcls *stat_cls;
2491   uint32_t stat_type;
2492   for (stat_type = STAT_TYPE_ROUNDS;
2493       stat_type < STAT_TYPE_MAX;
2494       stat_type++)
2495   {
2496     if (BIT(stat_type) & cur_test_run.stat_collect_flags)
2497     {
2498       stat_cls = GNUNET_malloc (sizeof (struct STATcls));
2499       stat_cls->rps_peer = rps_peer;
2500       stat_cls->stat_type = stat_type;
2501       rps_peer->file_name_stats =
2502         store_prefix_file_name (rps_peer->peer_id, "stats");
2503       rps_peer->h_stat_get[stat_type] =
2504         GNUNET_STATISTICS_get (rps_peer->stats_h,
2505                                "rps",
2506                                stat_type_strings [stat_type],
2507                                post_test_shutdown_ready_cb,
2508                                stat_iterator,
2509                                (struct STATcls *) stat_cls);
2510       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2511                   "Requested statistics for %s (peer %" PRIu32 ")\n",
2512                   stat_type_strings [stat_type],
2513                   rps_peer->index);
2514     }
2515   }
2516 }
2517
2518
2519 /***********************************************************************
2520  * /Definition of tests
2521 ***********************************************************************/
2522
2523
2524 /**
2525  * Actual "main" function for the testcase.
2526  *
2527  * @param cls closure
2528  * @param h the run handle
2529  * @param n_peers number of peers in 'peers'
2530  * @param peers handle to peers run in the testbed
2531  * @param links_succeeded the number of overlay link connection attempts that
2532  *          succeeded
2533  * @param links_failed the number of overlay link connection attempts that
2534  *          failed
2535  */
2536 static void
2537 test_run (void *cls,
2538      struct GNUNET_TESTBED_RunHandle *h,
2539      unsigned int n_peers,
2540      struct GNUNET_TESTBED_Peer **peers,
2541      unsigned int links_succeeded,
2542      unsigned int links_failed)
2543 {
2544   unsigned int i;
2545   struct OpListEntry *entry;
2546   (void) cls;
2547   (void) h;
2548   (void) links_failed;
2549
2550   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "RUN was called\n");
2551
2552   /* Check whether we timed out */
2553   if (n_peers != num_peers ||
2554       NULL == peers ||
2555       0 == links_succeeded)
2556   {
2557     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Going down due to args (eg. timeout)\n");
2558     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tn_peers: %u\n", n_peers);
2559     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tnum_peers: %" PRIu32 "\n", num_peers);
2560     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tpeers: %p\n", peers);
2561     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tlinks_succeeded: %u\n", links_succeeded);
2562     GNUNET_SCHEDULER_shutdown ();
2563     return;
2564   }
2565
2566
2567   /* Initialize peers */
2568   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "going to initialise peers\n");
2569   testbed_peers = peers;
2570   num_peers_online = 0;
2571   for (i = 0; i < num_peers; i++)
2572   {
2573     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "initialising %u\n", i);
2574     entry = make_oplist_entry ();
2575     entry->index = i;
2576     rps_peers[i].index = i;
2577     if (NULL != cur_test_run.init_peer)
2578       cur_test_run.init_peer (&rps_peers[i]);
2579     if (NO_COLLECT_VIEW == cur_test_run.have_collect_view)
2580     {
2581       rps_peers->cur_view_count = 0;
2582       rps_peers->cur_view = NULL;
2583     }
2584     entry->op = GNUNET_TESTBED_peer_get_information (peers[i],
2585                                                      GNUNET_TESTBED_PIT_IDENTITY,
2586                                                      &info_cb,
2587                                                      entry);
2588   }
2589
2590   /* Bring peers up */
2591   GNUNET_assert (num_peers == n_peers);
2592   for (i = 0; i < n_peers; i++)
2593   {
2594     rps_peers[i].index = i;
2595     rps_peers[i].op =
2596       GNUNET_TESTBED_service_connect (&rps_peers[i],
2597                                       peers[i],
2598                                       "rps",
2599                                       &rps_connect_complete_cb,
2600                                       &rps_peers[i],
2601                                       &rps_connect_adapter,
2602                                       &rps_disconnect_adapter,
2603                                       &rps_peers[i]);
2604     /* Connect all peers to statistics service */
2605     if (COLLECT_STATISTICS == cur_test_run.have_collect_statistics)
2606     {
2607       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2608                  "Connecting to statistics service\n");
2609       rps_peers[i].stat_op =
2610         GNUNET_TESTBED_service_connect (NULL,
2611                                         peers[i],
2612                                         "statistics",
2613                                         stat_complete_cb,
2614                                         &rps_peers[i],
2615                                         &stat_connect_adapter,
2616                                         &stat_disconnect_adapter,
2617                                         &rps_peers[i]);
2618     }
2619   }
2620
2621   if (NULL != churn_task)
2622     GNUNET_SCHEDULER_cancel (churn_task);
2623   post_test_task = GNUNET_SCHEDULER_add_delayed (duration, &post_test_op, NULL);
2624   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "timeout for shutdown is %lu\n", timeout.rel_value_us/1000000);
2625   shutdown_task = GNUNET_SCHEDULER_add_delayed (timeout,
2626                                                 &trigger_shutdown,
2627                                                 NULL);
2628   GNUNET_SCHEDULER_add_shutdown (shutdown_op, NULL);
2629 }
2630
2631
2632 /**
2633  * Entry point for the testcase, sets up the testbed.
2634  *
2635  * @param argc unused
2636  * @param argv unused
2637  */
2638 static void
2639 run (void *cls,
2640      char *const *args,
2641      const char *cfgfile,
2642      const struct GNUNET_CONFIGURATION_Handle *cfg)
2643 {
2644   //int ret_value;
2645   (void) cls;
2646   (void) args;
2647   (void) cfgfile;
2648
2649   /* Defaults for tests */
2650   churn_task = NULL;
2651
2652   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "This is the profiler\n");
2653   cur_test_run.name = "test-rps-profiler";
2654   if (0 == num_peers) num_peers = 10;
2655   mal_type = 3;
2656   cur_test_run.init_peer = profiler_init_peer;
2657   //cur_test_run.pre_test = mal_pre;
2658   cur_test_run.pre_test = pre_profiler;
2659   cur_test_run.main_test = profiler_cb;
2660   cur_test_run.reply_handle = profiler_reply_handle;
2661   cur_test_run.eval_cb = profiler_eval;
2662   cur_test_run.post_test = post_profiler;
2663   cur_test_run.request_interval = 2;
2664   if (0 == cur_test_run.num_requests) cur_test_run.num_requests = 5;
2665   //cur_test_run.have_churn = HAVE_CHURN;
2666   cur_test_run.have_churn = HAVE_NO_CHURN;
2667   cur_test_run.have_quick_quit = HAVE_QUICK_QUIT;
2668   cur_test_run.have_collect_statistics = COLLECT_STATISTICS;
2669   cur_test_run.stat_collect_flags = BIT(STAT_TYPE_ROUNDS) |
2670                                     BIT(STAT_TYPE_BLOCKS) |
2671                                     BIT(STAT_TYPE_BLOCKS_MANY_PUSH) |
2672                                     BIT(STAT_TYPE_BLOCKS_NO_PUSH) |
2673                                     BIT(STAT_TYPE_BLOCKS_NO_PULL) |
2674                                     BIT(STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL) |
2675                                     BIT(STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL) |
2676                                     BIT(STAT_TYPE_ISSUED_PUSH_SEND) |
2677                                     BIT(STAT_TYPE_ISSUED_PULL_REQ) |
2678                                     BIT(STAT_TYPE_ISSUED_PULL_REP) |
2679                                     BIT(STAT_TYPE_SENT_PUSH_SEND) |
2680                                     BIT(STAT_TYPE_SENT_PULL_REQ) |
2681                                     BIT(STAT_TYPE_SENT_PULL_REP) |
2682                                     BIT(STAT_TYPE_RECV_PUSH_SEND) |
2683                                     BIT(STAT_TYPE_RECV_PULL_REQ) |
2684                                     BIT(STAT_TYPE_RECV_PULL_REP);
2685   cur_test_run.have_collect_view = COLLECT_VIEW;
2686
2687   /* 'Clean' directory */
2688   (void) GNUNET_DISK_directory_remove ("/tmp/rps/");
2689   GNUNET_DISK_directory_create ("/tmp/rps/");
2690   if (0 == duration.rel_value_us)
2691   {
2692     if (0 == timeout.rel_value_us)
2693     {
2694       duration = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 90);
2695       timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
2696                                                (90 * 1.2) +
2697                                                  (0.01 * num_peers));
2698     }
2699     else
2700     {
2701       duration = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
2702                                                 (timeout.rel_value_us/1000000)
2703                                                   * 0.75);
2704     }
2705   }
2706   else
2707   {
2708     if (0 == timeout.rel_value_us)
2709     {
2710       timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
2711                                                ((duration.rel_value_us/1000000)
2712                                                   * 1.2) + (0.01 * num_peers));
2713     }
2714   }
2715   GNUNET_assert (duration.rel_value_us < timeout.rel_value_us);
2716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2717               "duration is %lus\n",
2718               duration.rel_value_us/1000000);
2719   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2720               "timeout is %lus\n",
2721               timeout.rel_value_us/1000000);
2722
2723   /* Compute number of bits for representing largest peer id */
2724   for (bits_needed = 1; (1 << bits_needed) < num_peers; bits_needed++)
2725     ;
2726   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2727             "Need %u bits to represent %" PRIu32 " peers\n",
2728              bits_needed,
2729              num_peers);
2730
2731   rps_peers = GNUNET_new_array (num_peers, struct RPSPeer);
2732   peer_map = GNUNET_CONTAINER_multipeermap_create (num_peers, GNUNET_NO);
2733   rps_peer_ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
2734   if ( (2 == mal_type) ||
2735        (3 == mal_type))
2736     target_peer = &rps_peer_ids[num_peers - 2];
2737
2738   ok = 1;
2739   GNUNET_TESTBED_run (NULL,
2740                       cfg,
2741                       num_peers,
2742                       0, /* event mask */
2743                       NULL,
2744                       NULL,
2745                       &test_run,
2746                       NULL);
2747 }
2748
2749 /**
2750  * Entry point for the testcase, sets up the testbed.
2751  *
2752  * @param argc unused
2753  * @param argv unused
2754  * @return 0 on success
2755  */
2756 int
2757 main (int argc, char *argv[])
2758 {
2759   int ret_value;
2760   struct GNUNET_GETOPT_CommandLineOption options[] = {
2761     GNUNET_GETOPT_option_uint ('n',
2762                                "num-peers",
2763                                "COUNT",
2764                                gettext_noop ("number of peers to start"),
2765                                &num_peers),
2766
2767     GNUNET_GETOPT_option_relative_time ('d',
2768                                         "duration",
2769                                         "DURATION",
2770                                         gettext_noop ("duration of the profiling"),
2771                                         &duration),
2772
2773     GNUNET_GETOPT_option_relative_time ('t',
2774                                         "timeout",
2775                                         "TIMEOUT",
2776                                         gettext_noop ("timeout for the profiling"),
2777                                         &timeout),
2778
2779     GNUNET_GETOPT_option_uint ('r',
2780                                "num-requests",
2781                                "COUNT",
2782                                gettext_noop ("number of PeerIDs to request"),
2783                                &cur_test_run.num_requests),
2784
2785     GNUNET_GETOPT_OPTION_END
2786   };
2787
2788   //if (GNUNET_OK !=
2789   //    GNUNET_STRINGS_get_utf8_args (argc, argv,
2790   //                                  &argc, &argv))
2791   //  return 2;
2792   ret_value = 0;
2793   if (GNUNET_OK !=
2794       GNUNET_PROGRAM_run (argc,
2795                           argv,
2796                           "gnunet-rps-profiler",
2797                           gettext_noop ("Measure quality and performance of the RPS service."),
2798                           options,
2799                           &run,
2800                           NULL))
2801   {
2802     ret_value = 1;
2803   }
2804   if (GNUNET_OK != ret_value)
2805   {
2806     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2807                 "Test did not run successfully!\n");
2808   }
2809
2810   ret_value = cur_test_run.eval_cb();
2811   if (NO_COLLECT_VIEW == cur_test_run.have_collect_view)
2812   {
2813     GNUNET_array_grow (rps_peers->cur_view,
2814                        rps_peers->cur_view_count,
2815                        0);
2816   }
2817   GNUNET_free (rps_peers);
2818   GNUNET_free (rps_peer_ids);
2819   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2820   return ret_value;
2821 }
2822
2823 /* end of test_rps.c */