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