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