79f0fbe2f4e7605d354caa6d9f78a90a39971736
[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  * ID of the peer that requests for the evaluation.
480  */
481 static struct RPSPeer *eval_peer;
482
483 /**
484  * Number of online peers.
485  */
486 static unsigned int num_peers_online;
487
488 /**
489  * @brief The added sizes of the peer's views
490  */
491 static unsigned int view_sizes;
492
493 /**
494  * Return value from 'main'.
495  */
496 static int ok;
497
498 /**
499  * Identifier for the task that runs after the test to collect results
500  */
501 static struct GNUNET_SCHEDULER_Task *post_test_task;
502
503 /**
504  * Identifier for the shutdown task
505  */
506 static struct GNUNET_SCHEDULER_Task *shutdown_task;
507
508
509 /**
510  * Identifier for the churn task that runs periodically
511  */
512 static struct GNUNET_SCHEDULER_Task *churn_task;
513
514 /**
515  * Called to initialise the given RPSPeer
516  */
517 typedef void (*InitPeer) (struct RPSPeer *rps_peer);
518
519 /**
520  * @brief Called directly after connecting to the service
521  *
522  * @param rps_peer Specific peer the function is called on
523  * @param h the handle to the rps service
524  */
525 typedef void (*PreTest) (struct RPSPeer *rps_peer, struct GNUNET_RPS_Handle *h);
526
527 /**
528  * @brief Executes functions to test the api/service for a given peer
529  *
530  * Called from within #rps_connect_complete_cb ()
531  * Implemented by #churn_test_cb, #profiler_cb, #mal_cb, #single_req_cb,
532  * #delay_req_cb, #seed_big_cb, #single_peer_seed_cb, #seed_cb, #req_cancel_cb
533  *
534  * @param rps_peer the peer the task runs on
535  */
536 typedef void (*MainTest) (struct RPSPeer *rps_peer);
537
538 /**
539  * Callback called once the requested random peers are available
540  */
541 typedef void (*ReplyHandle) (void *cls,
542                              uint64_t n,
543                              const struct GNUNET_PeerIdentity *recv_peers);
544
545 /**
546  * Called directly before disconnecting from the service
547  */
548 typedef void (*PostTest) (struct RPSPeer *peer);
549
550 /**
551  * Function called after disconnect to evaluate test success
552  */
553 typedef int (*EvaluationCallback) (void);
554
555 /**
556  * @brief Do we have Churn?
557  */
558 enum OPTION_CHURN {
559   /**
560    * @brief If we have churn this is set
561    */
562   HAVE_CHURN,
563   /**
564    * @brief If we have no churn this is set
565    */
566   HAVE_NO_CHURN,
567 };
568
569 /**
570  * @brief Is it ok to quit the test before the timeout?
571  */
572 enum OPTION_QUICK_QUIT {
573   /**
574    * @brief It is ok for the test to quit before the timeout triggers
575    */
576   HAVE_QUICK_QUIT,
577
578   /**
579    * @brief It is NOT ok for the test to quit before the timeout triggers
580    */
581   HAVE_NO_QUICK_QUIT,
582 };
583
584 /**
585  * @brief Do we collect statistics at the end?
586  */
587 enum OPTION_COLLECT_STATISTICS {
588   /**
589    * @brief We collect statistics at the end
590    */
591   COLLECT_STATISTICS,
592
593   /**
594    * @brief We do not collect statistics at the end
595    */
596   NO_COLLECT_STATISTICS,
597 };
598
599 /**
600  * @brief Do we collect views during run?
601  */
602 enum OPTION_COLLECT_VIEW {
603   /**
604    * @brief We collect view during run
605    */
606   COLLECT_VIEW,
607
608   /**
609    * @brief We do not collect the view during run
610    */
611   NO_COLLECT_VIEW,
612 };
613
614 /**
615  * Structure to define a single test
616  */
617 struct SingleTestRun
618 {
619   /**
620    * Name of the test
621    */
622   char *name;
623
624   /**
625    * Called with a single peer in order to initialise that peer
626    */
627   InitPeer init_peer;
628
629   /**
630    * Called directly after connecting to the service
631    */
632   PreTest pre_test;
633
634   /**
635    * Main function for each peer
636    */
637   MainTest main_test;
638
639   /**
640    * Callback called once the requested peers are available
641    */
642   ReplyHandle reply_handle;
643
644   /**
645    * Called directly before disconnecting from the service
646    */
647   PostTest post_test;
648
649   /**
650    * Function to evaluate the test results
651    */
652   EvaluationCallback eval_cb;
653
654   /**
655    * Request interval
656    */
657   uint32_t request_interval;
658
659   /**
660    * Number of Requests to make.
661    */
662   uint32_t num_requests;
663
664   /**
665    * Run with (-out) churn
666    */
667   enum OPTION_CHURN have_churn;
668
669   /**
670    * Quit test before timeout?
671    */
672   enum OPTION_QUICK_QUIT have_quick_quit;
673
674   /**
675    * Collect statistics at the end?
676    */
677   enum OPTION_COLLECT_STATISTICS have_collect_statistics;
678
679   /**
680    * Collect view during run?
681    */
682   enum OPTION_COLLECT_VIEW have_collect_view;
683
684   /**
685    * @brief Mark which values from the statistics service to collect at the end
686    * of the run
687    */
688   uint32_t stat_collect_flags;
689 } cur_test_run;
690
691 /**
692  * Did we finish the test?
693  */
694 static int post_test;
695
696 /**
697  * Are we shutting down?
698  */
699 static int in_shutdown;
700
701 /**
702  * Append arguments to file
703  */
704 static void
705 tofile_ (const char *file_name, const char *line)
706 {
707   struct GNUNET_DISK_FileHandle *f;
708   /* char output_buffer[512]; */
709   size_t size;
710   /* int size; */
711   size_t size2;
712
713   if (NULL == (f = GNUNET_DISK_file_open (file_name,
714                                           GNUNET_DISK_OPEN_APPEND |
715                                           GNUNET_DISK_OPEN_WRITE |
716                                           GNUNET_DISK_OPEN_CREATE,
717                                           GNUNET_DISK_PERM_USER_READ |
718                                           GNUNET_DISK_PERM_USER_WRITE |
719                                           GNUNET_DISK_PERM_GROUP_READ |
720                                           GNUNET_DISK_PERM_OTHER_READ)))
721   {
722     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
723                 "Not able to open file %s\n",
724                 file_name);
725     return;
726   }
727   /* size = GNUNET_snprintf (output_buffer,
728                           sizeof (output_buffer),
729                           "%llu %s\n",
730                           GNUNET_TIME_absolute_get ().abs_value_us,
731                           line);
732   if (0 > size)
733   {
734     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
735                 "Failed to write string to buffer (size: %i)\n",
736                 size);
737     return;
738   } */
739
740   size = strlen (line) * sizeof (char);
741
742   size2 = GNUNET_DISK_file_write (f, line, size);
743   if (size != size2)
744   {
745     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
746                 "Unable to write to file! (Size: %lu, size2: %lu)\n",
747                 size,
748                 size2);
749     if (GNUNET_YES != GNUNET_DISK_file_close (f))
750     {
751       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
752                   "Unable to close file\n");
753     }
754     return;
755   }
756
757   if (GNUNET_YES != GNUNET_DISK_file_close (f))
758   {
759     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
760                 "Unable to close file\n");
761   }
762 }
763
764 /**
765  * This function is used to facilitate writing important information to disk
766  */
767 #define tofile(file_name, ...) do {\
768   char tmp_buf[512];\
769     int size;\
770     size = GNUNET_snprintf(tmp_buf,sizeof(tmp_buf),__VA_ARGS__);\
771     if (0 > size)\
772       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,\
773                      "Failed to create tmp_buf\n");\
774     else\
775       tofile_(file_name,tmp_buf);\
776   } while (0);
777
778
779 /**
780  * Write the ids and their according index in the given array to a file
781  * Unused
782  */
783 /* static void
784 ids_to_file (char *file_name,
785              struct GNUNET_PeerIdentity *peer_ids,
786              unsigned int num_peer_ids)
787 {
788   unsigned int i;
789
790   for (i=0 ; i < num_peer_ids ; i++)
791   {
792     to_file (file_name,
793              "%u\t%s",
794              i,
795              GNUNET_i2s_full (&peer_ids[i]));
796   }
797 } */
798
799 /**
800  * Test the success of a single test
801  */
802 static int
803 evaluate (void)
804 {
805   unsigned int i;
806   int tmp_ok;
807
808   tmp_ok = 1;
809
810   for (i = 0; i < num_peers; i++)
811   {
812     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
813         "%u. peer [%s] received %u of %u expected peer_ids: %i\n",
814         i,
815         GNUNET_i2s (rps_peers[i].peer_id),
816         rps_peers[i].num_recv_ids,
817         rps_peers[i].num_ids_to_request,
818         (rps_peers[i].num_ids_to_request == rps_peers[i].num_recv_ids));
819     tmp_ok &= (rps_peers[i].num_ids_to_request == rps_peers[i].num_recv_ids);
820   }
821   return tmp_ok? 0 : 1;
822 }
823
824
825 /**
826  * Creates an oplist entry and adds it to the oplist DLL
827  */
828 static struct OpListEntry *
829 make_oplist_entry ()
830 {
831   struct OpListEntry *entry;
832
833   entry = GNUNET_new (struct OpListEntry);
834   GNUNET_CONTAINER_DLL_insert_tail (oplist_head, oplist_tail, entry);
835   return entry;
836 }
837
838
839 /**
840  * @brief Checks if given peer already received its statistics value from the
841  * statistics service.
842  *
843  * @param rps_peer the peer to check for
844  *
845  * @return #GNUNET_YES if so
846  *         #GNUNET_NO otherwise
847  */
848 static int check_statistics_collect_completed_single_peer (
849     const struct RPSPeer *rps_peer)
850 {
851   if (cur_test_run.stat_collect_flags !=
852         (cur_test_run.stat_collect_flags &
853           rps_peer->stat_collected_flags))
854   {
855     return GNUNET_NO;
856   }
857   return GNUNET_YES;
858 }
859 /**
860  * @brief Checks if all peers already received their statistics value from the
861  * statistics service.
862  *
863  * @return #GNUNET_YES if so
864  *         #GNUNET_NO otherwise
865  */
866 static int check_statistics_collect_completed ()
867 {
868   uint32_t i;
869
870   for (i = 0; i < num_peers; i++)
871   {
872     if (GNUNET_NO == check_statistics_collect_completed_single_peer (&rps_peers[i]))
873     {
874       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
875           "At least Peer %" PRIu32 " did not yet receive all statistics values\n",
876           i);
877       return GNUNET_NO;
878     }
879   }
880   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
881       "All peers received their statistics values\n");
882   return GNUNET_YES;
883 }
884
885 static void
886 rps_disconnect_adapter (void *cls,
887                         void *op_result);
888
889 static void
890 cancel_pending_req (struct PendingRequest *pending_req)
891 {
892   struct RPSPeer *rps_peer;
893
894   rps_peer = pending_req->rps_peer;
895   GNUNET_CONTAINER_DLL_remove (rps_peer->pending_req_head,
896                                rps_peer->pending_req_tail,
897                                pending_req);
898   rps_peer->num_pending_reqs--;
899   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
900               "Cancelling pending rps get request\n");
901   GNUNET_SCHEDULER_cancel (pending_req->request_task);
902   GNUNET_free (pending_req);
903 }
904
905 static void
906 cancel_request (struct PendingReply *pending_rep)
907 {
908   struct RPSPeer *rps_peer;
909
910   rps_peer = pending_rep->rps_peer;
911   GNUNET_CONTAINER_DLL_remove (rps_peer->pending_rep_head,
912                                rps_peer->pending_rep_tail,
913                                pending_rep);
914   rps_peer->num_pending_reps--;
915   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
916               "Cancelling rps get reply\n");
917   GNUNET_RPS_request_cancel (pending_rep->req_handle);
918   GNUNET_free (pending_rep);
919 }
920
921 void
922 clean_peer (unsigned peer_index)
923 {
924   struct PendingRequest *pending_req;
925
926   while (NULL != (pending_req = rps_peers[peer_index].pending_req_head))
927   {
928     cancel_pending_req (pending_req);
929   }
930   pending_req = rps_peers[peer_index].pending_req_head;
931   rps_disconnect_adapter (&rps_peers[peer_index],
932                           &rps_peers[peer_index].rps_handle);
933   for (unsigned stat_type = STAT_TYPE_ROUNDS;
934        stat_type < STAT_TYPE_MAX;
935        stat_type++)
936   {
937     if (NULL != rps_peers[peer_index].h_stat_get[stat_type])
938     {
939       GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
940                   "(%u) did not yet receive stat value for `%s'\n",
941                   rps_peers[peer_index].index,
942                   stat_type_strings[stat_type]);
943       GNUNET_STATISTICS_get_cancel (
944           rps_peers[peer_index].h_stat_get[stat_type]);
945     }
946   }
947   if (NULL != rps_peers[peer_index].op)
948   {
949     GNUNET_TESTBED_operation_done (rps_peers[peer_index].op);
950     rps_peers[peer_index].op = NULL;
951   }
952 }
953
954 /**
955  * Task run on timeout to shut everything down.
956  */
957 static void
958 shutdown_op (void *cls)
959 {
960   unsigned int i;
961   struct OpListEntry *entry;
962   (void) cls;
963
964   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
965               "Shutdown task scheduled, going down.\n");
966   in_shutdown = GNUNET_YES;
967
968   if (NULL != shutdown_task)
969   {
970     GNUNET_SCHEDULER_cancel (shutdown_task);
971     shutdown_task = NULL;
972   }
973   if (NULL != post_test_task)
974   {
975     GNUNET_SCHEDULER_cancel (post_test_task);
976     post_test_task = NULL;
977   }
978   if (NULL != churn_task)
979   {
980     GNUNET_SCHEDULER_cancel (churn_task);
981     churn_task = NULL;
982   }
983   entry = oplist_head;
984   while (NULL != (entry = oplist_head))
985   {
986     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
987                 "Operation still pending on shutdown (%u)\n",
988                 entry->index);
989     GNUNET_TESTBED_operation_done (entry->op);
990     GNUNET_CONTAINER_DLL_remove (oplist_head, oplist_tail, entry);
991     GNUNET_free (entry);
992   }
993   for (i = 0; i < num_peers; i++)
994   {
995     clean_peer (i);
996   }
997 }
998
999 static void
1000 trigger_shutdown (void *cls)
1001 {
1002   (void) cls;
1003
1004   GNUNET_log (GNUNET_ERROR_TYPE_INFO,
1005               "Shutdown was triggerd by timeout, going down.\n");
1006   shutdown_task = NULL;
1007   GNUNET_SCHEDULER_shutdown ();
1008 }
1009
1010
1011 /**
1012  * Task run after #duration to collect statistics and potentially shut down.
1013  */
1014 static void
1015 post_test_op (void *cls)
1016 {
1017   unsigned int i;
1018   (void) cls;
1019
1020   post_test_task = NULL;
1021   post_test = GNUNET_YES;
1022   GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1023               "Post test task scheduled.\n");
1024   if (NULL != churn_task)
1025   {
1026     GNUNET_SCHEDULER_cancel (churn_task);
1027     churn_task = NULL;
1028   }
1029   for (i = 0; i < num_peers; i++)
1030   {
1031     if (NULL != rps_peers[i].op)
1032     {
1033       GNUNET_TESTBED_operation_done (rps_peers[i].op);
1034       rps_peers[i].op = NULL;
1035     }
1036     if (NULL != cur_test_run.post_test)
1037     {
1038       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Executing post_test for peer %u\n", i);
1039       cur_test_run.post_test (&rps_peers[i]);
1040     }
1041   }
1042   /* If we do not collect statistics, shut down directly */
1043   if (NO_COLLECT_STATISTICS == cur_test_run.have_collect_statistics ||
1044       GNUNET_YES == check_statistics_collect_completed())
1045   {
1046     GNUNET_SCHEDULER_cancel (shutdown_task);
1047     shutdown_task = NULL;
1048     GNUNET_SCHEDULER_shutdown ();
1049   }
1050 }
1051
1052
1053 /**
1054  * Seed peers.
1055  */
1056 static void
1057 seed_peers (void *cls)
1058 {
1059   struct RPSPeer *peer = cls;
1060   unsigned int amount;
1061   unsigned int i;
1062
1063   // TODO if malicious don't seed mal peers
1064   amount = round (.5 * num_peers);
1065
1066   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Seeding peers:\n");
1067   for (i = 0 ; i < amount ; i++)
1068     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Seeding %u. peer: %s\n",
1069                 i,
1070                 GNUNET_i2s (&rps_peer_ids[i]));
1071
1072   GNUNET_RPS_seed_ids (peer->rps_handle, amount, rps_peer_ids);
1073 }
1074
1075
1076 /**
1077  * Get the id of peer i.
1078  */
1079   void
1080 info_cb (void *cb_cls,
1081          struct GNUNET_TESTBED_Operation *op,
1082          const struct GNUNET_TESTBED_PeerInformation *pinfo,
1083          const char *emsg)
1084 {
1085   struct OpListEntry *entry = (struct OpListEntry *) cb_cls;
1086   (void) op;
1087
1088   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1089   {
1090     return;
1091   }
1092
1093   if (NULL == pinfo || NULL != emsg)
1094   {
1095     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Got Error: %s\n", emsg);
1096     GNUNET_TESTBED_operation_done (entry->op);
1097     return;
1098   }
1099
1100   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1101               "Peer %u is %s\n",
1102               entry->index,
1103               GNUNET_i2s (pinfo->result.id));
1104
1105   rps_peer_ids[entry->index] = *(pinfo->result.id);
1106   rps_peers[entry->index].peer_id = &rps_peer_ids[entry->index];
1107
1108   GNUNET_assert (GNUNET_OK ==
1109       GNUNET_CONTAINER_multipeermap_put (peer_map,
1110         &rps_peer_ids[entry->index],
1111         &rps_peers[entry->index],
1112         GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1113   tofile ("/tmp/rps/peer_ids",
1114            "%u\t%s\n",
1115            entry->index,
1116            GNUNET_i2s_full (&rps_peer_ids[entry->index]));
1117
1118   GNUNET_CONTAINER_DLL_remove (oplist_head, oplist_tail, entry);
1119   GNUNET_TESTBED_operation_done (entry->op);
1120   GNUNET_free (entry);
1121 }
1122
1123
1124 /**
1125  * Callback to be called when RPS service connect operation is completed
1126  *
1127  * @param cls the callback closure from functions generating an operation
1128  * @param op the operation that has been finished
1129  * @param ca_result the RPS service handle returned from rps_connect_adapter
1130  * @param emsg error message in case the operation has failed; will be NULL if
1131  *          operation has executed successfully.
1132  */
1133 static void
1134 rps_connect_complete_cb (void *cls,
1135                          struct GNUNET_TESTBED_Operation *op,
1136                          void *ca_result,
1137                          const char *emsg)
1138 {
1139   struct RPSPeer *rps_peer = cls;
1140   struct GNUNET_RPS_Handle *rps = ca_result;
1141
1142   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1143   {
1144     return;
1145   }
1146
1147   rps_peer->rps_handle = rps;
1148   rps_peer->online = GNUNET_YES;
1149   num_peers_online++;
1150
1151   GNUNET_assert (op == rps_peer->op);
1152   if (NULL != emsg)
1153   {
1154     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1155                 "Failed to connect to RPS service: %s\n",
1156                 emsg);
1157     ok = 1;
1158     GNUNET_SCHEDULER_shutdown ();
1159     return;
1160   }
1161
1162   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1163               "Started client successfully (%u)\n",
1164               rps_peer->index);
1165
1166   cur_test_run.main_test (rps_peer);
1167 }
1168
1169
1170 /**
1171  * Adapter function called to establish a connection to
1172  * the RPS service.
1173  *
1174  * @param cls closure
1175  * @param cfg configuration of the peer to connect to; will be available until
1176  *          GNUNET_TESTBED_operation_done() is called on the operation returned
1177  *          from GNUNET_TESTBED_service_connect()
1178  * @return service handle to return in 'op_result', NULL on error
1179  */
1180 static void *
1181 rps_connect_adapter (void *cls,
1182                      const struct GNUNET_CONFIGURATION_Handle *cfg)
1183 {
1184   struct GNUNET_RPS_Handle *h;
1185
1186   h = GNUNET_RPS_connect (cfg);
1187
1188   if (NULL != cur_test_run.pre_test)
1189     cur_test_run.pre_test (cls, h);
1190
1191   return h;
1192 }
1193
1194 /**
1195  * Called to open a connection to the peer's statistics
1196  *
1197  * @param cls peer context
1198  * @param cfg configuration of the peer to connect to; will be available until
1199  *          GNUNET_TESTBED_operation_done() is called on the operation returned
1200  *          from GNUNET_TESTBED_service_connect()
1201  * @return service handle to return in 'op_result', NULL on error
1202  */
1203 static void *
1204 stat_connect_adapter (void *cls,
1205                       const struct GNUNET_CONFIGURATION_Handle *cfg)
1206 {
1207   struct RPSPeer *peer = cls;
1208
1209   peer->stats_h = GNUNET_STATISTICS_create ("rps-profiler", cfg);
1210   return peer->stats_h;
1211 }
1212
1213 /**
1214  * Called to disconnect from peer's statistics service
1215  *
1216  * @param cls peer context
1217  * @param op_result service handle returned from the connect adapter
1218  */
1219 static void
1220 stat_disconnect_adapter (void *cls, void *op_result)
1221 {
1222   struct RPSPeer *peer = cls;
1223
1224   //GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch_cancel
1225   //              (peer->stats_h, "core", "# peers connected",
1226   //               stat_iterator, peer));
1227   //GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch_cancel
1228   //              (peer->stats_h, "nse", "# peers connected",
1229   //               stat_iterator, peer));
1230   GNUNET_STATISTICS_destroy (op_result, GNUNET_NO);
1231   peer->stats_h = NULL;
1232 }
1233
1234 /**
1235  * Called after successfully opening a connection to a peer's statistics
1236  * service; we register statistics monitoring for CORE and NSE here.
1237  *
1238  * @param cls the callback closure from functions generating an operation
1239  * @param op the operation that has been finished
1240  * @param ca_result the service handle returned from GNUNET_TESTBED_ConnectAdapter()
1241  * @param emsg error message in case the operation has failed; will be NULL if
1242  *          operation has executed successfully.
1243  */
1244 static void
1245 stat_complete_cb (void *cls,
1246                   struct GNUNET_TESTBED_Operation *op,
1247                   void *ca_result,
1248                   const char *emsg )
1249 {
1250   //struct GNUNET_STATISTICS_Handle *sh = ca_result;
1251   //struct RPSPeer *peer = (struct RPSPeer *) cls;
1252   (void) cls;
1253   (void) op;
1254   (void) ca_result;
1255
1256   if (NULL != emsg)
1257   {
1258     GNUNET_break (0);
1259     return;
1260   }
1261   //GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch
1262   //              (sh, "core", "# peers connected",
1263   //               stat_iterator, peer));
1264   //GNUNET_break (GNUNET_OK == GNUNET_STATISTICS_watch
1265   //              (sh, "nse", "# peers connected",
1266   //               stat_iterator, peer));
1267 }
1268
1269
1270 /**
1271  * Adapter function called to destroy connection to
1272  * RPS service.
1273  *
1274  * @param cls closure
1275  * @param op_result service handle returned from the connect adapter
1276  */
1277 static void
1278 rps_disconnect_adapter (void *cls,
1279                         void *op_result)
1280 {
1281   struct RPSPeer *peer = cls;
1282   struct GNUNET_RPS_Handle *h = op_result;
1283   struct PendingReply *pending_rep;
1284
1285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1286               "disconnect_adapter (%u)\n",
1287               peer->index);
1288   GNUNET_assert (NULL != peer);
1289   if (NULL != peer->rps_handle)
1290   {
1291     while (NULL != (pending_rep = peer->pending_rep_head))
1292     {
1293       cancel_request (pending_rep);
1294     }
1295     GNUNET_assert (h == peer->rps_handle);
1296     GNUNET_RPS_disconnect (h);
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   if (num_peers - 1 == rps_peer->index)
1766   {
1767     rps_peer->num_ids_to_request = cur_test_run.num_requests;
1768   } else {
1769     rps_peer->num_ids_to_request = 0;
1770   }
1771   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "peer shall request %i peers\n",
1772               rps_peer->num_ids_to_request);
1773 }
1774
1775
1776 /**
1777  * Callback to call on receipt of a reply
1778  *
1779  * @param cls closure
1780  * @param n number of peers
1781  * @param recv_peers the received peers
1782  */
1783 static void
1784 profiler_reply_handle (void *cls,
1785                       uint64_t n,
1786                       const struct GNUNET_PeerIdentity *recv_peers)
1787 {
1788   struct RPSPeer *rps_peer;
1789   struct RPSPeer *rcv_rps_peer;
1790   char *file_name;
1791   char *file_name_dh;
1792   char *file_name_dhr;
1793   char *file_name_dhru;
1794   unsigned int i;
1795   struct PendingReply *pending_rep = (struct PendingReply *) cls;
1796
1797   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "profiler_reply_handle()\n");
1798   rps_peer = pending_rep->rps_peer;
1799   file_name = "/tmp/rps/received_ids";
1800   file_name_dh = "/tmp/rps/diehard_input";
1801   file_name_dhr = "/tmp/rps/diehard_input_raw";
1802   file_name_dhru = "/tmp/rps/diehard_input_raw_aligned";
1803   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1804               "[%s] got %" PRIu64 " peers:\n",
1805               GNUNET_i2s (rps_peer->peer_id),
1806               n);
1807   for (i = 0; i < n; i++)
1808   {
1809     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1810                 "%u: %s\n",
1811                 i,
1812                 GNUNET_i2s (&recv_peers[i]));
1813     tofile (file_name,
1814              "%s\n",
1815              GNUNET_i2s_full (&recv_peers[i]));
1816     rcv_rps_peer = GNUNET_CONTAINER_multipeermap_get (peer_map, &recv_peers[i]);
1817     GNUNET_assert (NULL != rcv_rps_peer);
1818     tofile (file_name_dh,
1819              "%" PRIu32 "\n",
1820              (uint32_t) rcv_rps_peer->index);
1821     to_file_raw (file_name_dhr,
1822                 (char *) &rcv_rps_peer->index,
1823                  sizeof (uint32_t));
1824     to_file_raw_unaligned (file_name_dhru,
1825                           (char *) &rcv_rps_peer->index,
1826                            sizeof (uint32_t),
1827                            bits_needed);
1828   }
1829   default_reply_handle (cls, n, recv_peers);
1830 }
1831
1832
1833 static void
1834 profiler_cb (struct RPSPeer *rps_peer)
1835 {
1836   if (GNUNET_YES == in_shutdown || GNUNET_YES == post_test)
1837   {
1838     return;
1839   }
1840
1841   /* Start churn */
1842   if (HAVE_CHURN == cur_test_run.have_churn && NULL == churn_task)
1843   {
1844     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1845                 "Starting churn task\n");
1846     churn_task = GNUNET_SCHEDULER_add_delayed (
1847           GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5),
1848           churn,
1849           NULL);
1850   } else {
1851     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1852                 "Not starting churn task\n");
1853   }
1854
1855   /* Only request peer ids at one peer.
1856    * (It's the before-last because last one is target of the focussed attack.)
1857    */
1858   if (eval_peer == rps_peer)
1859     schedule_missing_requests (rps_peer);
1860 }
1861
1862 /**
1863  * Function called from #profiler_eval with a filename.
1864  *
1865  * @param cls closure
1866  * @param filename complete filename (absolute path)
1867  * @return #GNUNET_OK to continue to iterate,
1868  *  #GNUNET_NO to stop iteration with no error,
1869  *  #GNUNET_SYSERR to abort iteration with error!
1870  */
1871 int
1872 file_name_cb (void *cls, const char *filename)
1873 {
1874   if (NULL != strstr (filename, "sampler_el"))
1875   {
1876     struct RPS_SamplerElement *s_elem;
1877     struct GNUNET_CRYPTO_AuthKey auth_key;
1878     const char *key_char;
1879     uint32_t i;
1880     (void) cls;
1881
1882     key_char = filename + 20; /* Length of "/tmp/rps/sampler_el-" */
1883     tofile (filename, "--------------------------\n");
1884
1885     auth_key = string_to_auth_key (key_char);
1886     s_elem = RPS_sampler_elem_create ();
1887     RPS_sampler_elem_set (s_elem, auth_key);
1888
1889     for (i = 0; i < num_peers; i++)
1890     {
1891       RPS_sampler_elem_next (s_elem, &rps_peer_ids[i]);
1892     }
1893     RPS_sampler_elem_destroy (s_elem);
1894   }
1895   return GNUNET_OK;
1896 }
1897
1898 /**
1899  * This is run after the test finished.
1900  *
1901  * Compute all perfect samples.
1902  */
1903 int
1904 profiler_eval (void)
1905 {
1906   /* Compute perfect sample for each sampler element */
1907   if (-1 == GNUNET_DISK_directory_scan ("/tmp/rps/", file_name_cb, NULL))
1908   {
1909     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Scan of directory failed\n");
1910   }
1911
1912   return evaluate ();
1913 }
1914
1915 static uint32_t fac (uint32_t x)
1916 {
1917   if (1 >= x)
1918   {
1919     return x;
1920   }
1921   return x * fac (x - 1);
1922 }
1923
1924 static uint32_t binom (uint32_t n, uint32_t k)
1925 {
1926   //GNUNET_assert (n >= k);
1927   if (k > n) return 0;
1928   if (0 > n) return 0; /* just for clarity - always false */
1929   if (0 > k) return 0; /* just for clarity - always false */
1930   if (0 == k) return 1;
1931   return fac (n)
1932     /
1933     fac(k) * fac(n - k);
1934 }
1935
1936 /**
1937  * @brief is b in view of a?
1938  *
1939  * @param a
1940  * @param b
1941  *
1942  * @return
1943  */
1944 static int is_in_view (uint32_t a, uint32_t b)
1945 {
1946   uint32_t i;
1947   for (i = 0; i < rps_peers[a].cur_view_count; i++)
1948   {
1949     if (0 == memcmp (rps_peers[b].peer_id,
1950           &rps_peers[a].cur_view[i],
1951           sizeof (struct GNUNET_PeerIdentity)))
1952     {
1953       return GNUNET_YES;
1954     }
1955   }
1956   return GNUNET_NO;
1957 }
1958
1959 static uint32_t get_idx_of_pid (const struct GNUNET_PeerIdentity *pid)
1960 {
1961   uint32_t i;
1962
1963   for (i = 0; i < num_peers; i++)
1964   {
1965     if (0 == memcmp (pid,
1966           rps_peers[i].peer_id,
1967           sizeof (struct GNUNET_PeerIdentity)))
1968     {
1969       return i;
1970     }
1971   }
1972   //return 0; /* Should not happen - make compiler happy */
1973   GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1974              "No known _PeerIdentity %s!\n",
1975              GNUNET_i2s_full (pid));
1976   GNUNET_assert (0);
1977 }
1978
1979 /**
1980  * @brief Counts number of peers in view of a that have b in their view
1981  *
1982  * @param a
1983  * @param uint32_tb
1984  *
1985  * @return
1986  */
1987 static uint32_t count_containing_views (uint32_t a, uint32_t b)
1988 {
1989   uint32_t i;
1990   uint32_t peer_idx;
1991   uint32_t count = 0;
1992
1993   for (i = 0; i < rps_peers[a].cur_view_count; i++)
1994   {
1995     peer_idx = get_idx_of_pid (&rps_peers[a].cur_view[i]);
1996     if (GNUNET_YES == is_in_view (peer_idx, b))
1997     {
1998       count++;
1999     }
2000   }
2001   return count;
2002 }
2003
2004 /**
2005  * @brief Computes the probability for each other peer to be selected by the
2006  * sampling process based on the views of all peers
2007  *
2008  * @param peer_idx index of the peer that is about to sample
2009  */
2010 static void compute_probabilities (uint32_t peer_idx)
2011 {
2012   //double probs[num_peers] = { 0 };
2013   double probs[num_peers];
2014   size_t probs_as_str_size = (num_peers * 10 + 1) * sizeof (char);
2015   char *probs_as_str = GNUNET_malloc (probs_as_str_size);
2016   char *probs_as_str_cpy;
2017   uint32_t i;
2018   double prob_push;
2019   double prob_pull;
2020   uint32_t view_size;
2021   uint32_t cont_views;
2022   uint32_t number_of_being_in_pull_events;
2023   int tmp;
2024   uint32_t count_non_zero_prob = 0;
2025
2026   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2027       "Computing probabilities for peer %" PRIu32 "\n", peer_idx);
2028   /* Firstly without knowledge of old views */
2029   for (i = 0; i < num_peers; i++)
2030   {
2031     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2032         "\tfor peer %" PRIu32 ":\n", i);
2033     view_size = rps_peers[i].cur_view_count;
2034     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2035         "\t\tview_size: %" PRIu32 "\n", view_size);
2036     /* For peer i the probability of being sampled is
2037      * evenly distributed among all possibly observed peers. */
2038     /* We could have observed a peer in three cases:
2039      *   1. peer sent a push
2040      *   2. peer was contained in a pull reply
2041      *   3. peer was in history (sampler) - ignored for now */
2042     /* 1. Probability of having received a push from peer i */
2043     if ((GNUNET_YES == is_in_view (i, peer_idx)) &&
2044         (1 <= (0.45 * view_size)))
2045     {
2046       if (0 == binom (view_size, 0.45 * view_size)) prob_push = 0;
2047       else
2048       {
2049         prob_push = 1.0 * binom (0.45 * view_size, 1)
2050           /
2051           binom (view_size, 0.45 * view_size);
2052       }
2053       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2054                  "\t\t%" PRIu32 " is in %" PRIu32 "'s view, prob: %f\n",
2055                  peer_idx,
2056                  i,
2057                  prob_push);
2058       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2059                  "\t\tposs choices from view: %" PRIu32 ", containing i: %" PRIu32 "\n",
2060                  binom (view_size, 0.45 * view_size),
2061                  binom (0.45 * view_size, 1));
2062     } else {
2063       prob_push = 0;
2064       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2065                  "\t\t%" PRIu32 " is not in %" PRIu32 "'s view, prob: 0\n",
2066                  peer_idx,
2067                  i);
2068     }
2069     /* 2. Probability of peer i being contained in pulls */
2070     view_size = rps_peers[peer_idx].cur_view_count;
2071     cont_views = count_containing_views (peer_idx, i);
2072     number_of_being_in_pull_events =
2073       (binom (view_size, 0.45 * view_size) -
2074        binom (view_size - cont_views, 0.45 * view_size));
2075     if (0 != number_of_being_in_pull_events)
2076     {
2077       prob_pull = number_of_being_in_pull_events
2078         /
2079         (1.0 * binom (view_size, 0.45 * view_size));
2080     } else
2081     {
2082       prob_pull = 0;
2083     }
2084     probs[i] = prob_push + prob_pull - (prob_push * prob_pull);
2085     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2086                "\t\t%" PRIu32 " has %" PRIu32 " of %" PRIu32
2087                " peers in its view who know %" PRIu32 " prob: %f\n",
2088                peer_idx,
2089                cont_views,
2090                view_size,
2091                i,
2092                prob_pull);
2093     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2094                "\t\tnumber of possible pull combinations: %" PRIu32 "\n",
2095                binom (view_size, 0.45 * view_size));
2096     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2097                "\t\tnumber of possible pull combinations without %" PRIu32
2098                ": %" PRIu32 "\n",
2099                i,
2100                binom (view_size - cont_views, 0.45 * view_size));
2101     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2102                "\t\tnumber of possible pull combinations with %" PRIu32
2103                ": %" PRIu32 "\n",
2104                i,
2105                number_of_being_in_pull_events);
2106
2107     if (0 != probs[i]) count_non_zero_prob++;
2108   }
2109   /* normalize */
2110   if (0 != count_non_zero_prob)
2111   {
2112     for (i = 0; i < num_peers; i++)
2113     {
2114       probs[i] = probs[i] * (1.0 / count_non_zero_prob);
2115     }
2116   } else {
2117     for (i = 0; i < num_peers; i++)
2118     {
2119       probs[i] = 0;
2120     }
2121   }
2122   /* str repr */
2123   for (i = 0; i < num_peers; i++)
2124   {
2125     probs_as_str_cpy = GNUNET_strndup (probs_as_str, probs_as_str_size);
2126     tmp = GNUNET_snprintf (probs_as_str,
2127                            probs_as_str_size,
2128                            "%s %7.6f", probs_as_str_cpy, probs[i]);
2129     GNUNET_free (probs_as_str_cpy);
2130     GNUNET_assert (0 <= tmp);
2131   }
2132
2133   to_file_w_len (rps_peers[peer_idx].file_name_probs,
2134                  probs_as_str_size,
2135                  probs_as_str);
2136   GNUNET_free (probs_as_str);
2137 }
2138
2139 /**
2140  * @brief This counts the number of peers in which views a given peer occurs.
2141  *
2142  * It also stores this value in the rps peer.
2143  *
2144  * @param peer_idx the index of the peer to count the representation
2145  *
2146  * @return the number of occurrences
2147  */
2148 static uint32_t count_peer_in_views_2 (uint32_t peer_idx)
2149 {
2150   uint32_t i, j;
2151   uint32_t count = 0;
2152
2153   for (i = 0; i < num_peers; i++) /* Peer in which view is counted */
2154   {
2155     for (j = 0; j < rps_peers[i].cur_view_count; j++) /* entry in view */
2156     {
2157       if (0 == memcmp (rps_peers[peer_idx].peer_id,
2158             &rps_peers[i].cur_view[j],
2159             sizeof (struct GNUNET_PeerIdentity)))
2160       {
2161         count++;
2162         break;
2163       }
2164     }
2165   }
2166   rps_peers[peer_idx].count_in_views = count;
2167   return count;
2168 }
2169
2170 static uint32_t cumulated_view_sizes ()
2171 {
2172   uint32_t i;
2173
2174   view_sizes = 0;
2175   for (i = 0; i < num_peers; i++) /* Peer in which view is counted */
2176   {
2177     view_sizes += rps_peers[i].cur_view_count;
2178   }
2179   return view_sizes;
2180 }
2181
2182 static void count_peer_in_views (uint32_t *count_peers)
2183 {
2184   uint32_t i, j;
2185
2186   for (i = 0; i < num_peers; i++) /* Peer in which view is counted */
2187   {
2188     for (j = 0; j < rps_peers[i].cur_view_count; j++) /* entry in view */
2189     {
2190       if (0 == memcmp (rps_peers[i].peer_id,
2191             &rps_peers[i].cur_view[j],
2192             sizeof (struct GNUNET_PeerIdentity)))
2193       {
2194         count_peers[i]++;
2195       }
2196     }
2197   }
2198 }
2199
2200 void compute_diversity ()
2201 {
2202   uint32_t i;
2203   /* ith entry represents the numer of occurrences in other peer's views */
2204   uint32_t *count_peers = GNUNET_new_array (num_peers, uint32_t);
2205   uint32_t views_total_size;
2206   double expected;
2207   /* deviation from expected number of peers */
2208   double *deviation = GNUNET_new_array (num_peers, double);
2209
2210   views_total_size = 0;
2211   expected = 0;
2212
2213   /* For each peer count its representation in other peer's views*/
2214   for (i = 0; i < num_peers; i++) /* Peer to count */
2215   {
2216     views_total_size += rps_peers[i].cur_view_count;
2217     count_peer_in_views (count_peers);
2218     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2219                "Counted representation of %" PRIu32 "th peer [%s]: %" PRIu32"\n",
2220                i,
2221                GNUNET_i2s (rps_peers[i].peer_id),
2222                count_peers[i]);
2223   }
2224
2225   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2226              "size of all views combined: %" PRIu32 "\n",
2227              views_total_size);
2228   expected = ((double) 1/num_peers) * views_total_size;
2229   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2230              "Expected number of occurrences of each peer in all views: %f\n",
2231              expected);
2232   for (i = 0; i < num_peers; i++) /* Peer to count */
2233   {
2234     deviation[i] = expected - count_peers[i];
2235     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2236                "Deviation from expectation: %f\n", deviation[i]);
2237   }
2238   GNUNET_free (count_peers);
2239   GNUNET_free (deviation);
2240 }
2241
2242 void print_view_sizes()
2243 {
2244   uint32_t i;
2245
2246   for (i = 0; i < num_peers; i++) /* Peer to count */
2247   {
2248     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2249                "View size of %" PRIu32 ". [%s] is %" PRIu32 "\n",
2250                i,
2251                GNUNET_i2s (rps_peers[i].peer_id),
2252                rps_peers[i].cur_view_count);
2253   }
2254 }
2255
2256 void all_views_updated_cb()
2257 {
2258   compute_diversity();
2259   print_view_sizes();
2260 }
2261
2262 void view_update_cb (void *cls,
2263                      uint64_t view_size,
2264                      const struct GNUNET_PeerIdentity *peers)
2265 {
2266   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2267               "View was updated (%" PRIu64 ")\n", view_size);
2268   struct RPSPeer *rps_peer = (struct RPSPeer *) cls;
2269   to_file ("/tmp/rps/view_sizes.txt",
2270          "%" PRIu64 " %" PRIu32 "",
2271          rps_peer->index,
2272          view_size);
2273   for (uint64_t i = 0; i < view_size; i++)
2274   {
2275     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2276                "\t%s\n", GNUNET_i2s (&peers[i]));
2277   }
2278   GNUNET_array_grow (rps_peer->cur_view,
2279                      rps_peer->cur_view_count,
2280                      view_size);
2281   //*rps_peer->cur_view = *peers;
2282   GNUNET_memcpy (rps_peer->cur_view,
2283                  peers,
2284                  view_size * sizeof (struct GNUNET_PeerIdentity));
2285   to_file ("/tmp/rps/count_in_views.txt",
2286          "%" PRIu64 " %" PRIu32 "",
2287          rps_peer->index,
2288          count_peer_in_views_2 (rps_peer->index));
2289   cumulated_view_sizes();
2290   if (0 != view_size)
2291   {
2292     to_file ("/tmp/rps/repr.txt",
2293            "%" PRIu64 /* index */
2294            " %" PRIu32 /* occurrence in views */
2295            " %" PRIu32 /* view sizes */
2296            " %f" /* fraction of repr in views */
2297            " %f" /* average view size */
2298            " %f" /* prob of occurrence in view slot */
2299            " %f" "", /* exp frac of repr in views */
2300            rps_peer->index,
2301            count_peer_in_views_2 (rps_peer->index),
2302            view_sizes,
2303            count_peer_in_views_2 (rps_peer->index) / (view_size * 1.0), /* fraction of representation in views */
2304            view_sizes / (view_size * 1.0), /* average view size */
2305            1.0 /view_size, /* prob of occurrence in view slot */
2306            (1.0/view_size) * (view_sizes/view_size) /* expected fraction of repr in views */
2307            );
2308   }
2309   compute_probabilities (rps_peer->index);
2310   all_views_updated_cb();
2311 }
2312
2313 static void
2314 pre_profiler (struct RPSPeer *rps_peer, struct GNUNET_RPS_Handle *h)
2315 {
2316   rps_peer->file_name_probs =
2317     store_prefix_file_name (rps_peer->peer_id, "probs");
2318   GNUNET_RPS_view_request (h, 0, view_update_cb, rps_peer);
2319 }
2320
2321 void write_final_stats (void){
2322   uint64_t sums[STAT_TYPE_MAX] = { 0 };
2323
2324   for (uint32_t i = 0; i < num_peers; i++)
2325   {
2326     to_file ("/tmp/rps/final_stats.csv",
2327              ", %" PRIu32 ", " /* index */
2328              "%s, %" /* id */
2329              PRIu64 ", %" /* rounds */
2330              PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" /* blocking */
2331              PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" /* issued */
2332              PRIu64 ", %" PRIu64 ", %" PRIu64 ", %" /* sent */
2333              PRIu64 ", %" PRIu64 ", %" PRIu64 /* recv */,
2334              i,
2335              GNUNET_i2s (rps_peers[i].peer_id),
2336              rps_peers[i].stats[STAT_TYPE_ROUNDS],
2337              rps_peers[i].stats[STAT_TYPE_BLOCKS],
2338              rps_peers[i].stats[STAT_TYPE_BLOCKS_MANY_PUSH],
2339              rps_peers[i].stats[STAT_TYPE_BLOCKS_NO_PUSH],
2340              rps_peers[i].stats[STAT_TYPE_BLOCKS_NO_PULL],
2341              rps_peers[i].stats[STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL],
2342              rps_peers[i].stats[STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL],
2343              rps_peers[i].stats[STAT_TYPE_ISSUED_PUSH_SEND],
2344              rps_peers[i].stats[STAT_TYPE_ISSUED_PULL_REQ],
2345              rps_peers[i].stats[STAT_TYPE_ISSUED_PULL_REP],
2346              rps_peers[i].stats[STAT_TYPE_SENT_PUSH_SEND],
2347              rps_peers[i].stats[STAT_TYPE_SENT_PULL_REQ],
2348              rps_peers[i].stats[STAT_TYPE_SENT_PULL_REP],
2349              rps_peers[i].stats[STAT_TYPE_RECV_PUSH_SEND],
2350              rps_peers[i].stats[STAT_TYPE_RECV_PULL_REQ],
2351              rps_peers[i].stats[STAT_TYPE_RECV_PULL_REP]);
2352     for (enum STAT_TYPE stat_type = STAT_TYPE_ROUNDS;
2353          stat_type < STAT_TYPE_MAX;
2354          stat_type++)
2355     {
2356       sums[stat_type] += rps_peers[i].stats[stat_type];
2357     }
2358   }
2359   to_file ("/tmp/rps/final_stats.dat",
2360            "SUM %"
2361            PRIu64 " %" /* rounds */
2362            PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %" /* blocking */
2363            PRIu64 " %" PRIu64 " %" PRIu64 " %" /* issued */
2364            PRIu64 " %" PRIu64 " %" PRIu64 " %" /* sent */
2365            PRIu64 " %" PRIu64 " %" PRIu64 /* recv */,
2366            sums[STAT_TYPE_ROUNDS],
2367            sums[STAT_TYPE_BLOCKS],
2368            sums[STAT_TYPE_BLOCKS_MANY_PUSH],
2369            sums[STAT_TYPE_BLOCKS_NO_PUSH],
2370            sums[STAT_TYPE_BLOCKS_NO_PULL],
2371            sums[STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL],
2372            sums[STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL],
2373            sums[STAT_TYPE_ISSUED_PUSH_SEND],
2374            sums[STAT_TYPE_ISSUED_PULL_REQ],
2375            sums[STAT_TYPE_ISSUED_PULL_REP],
2376            sums[STAT_TYPE_SENT_PUSH_SEND],
2377            sums[STAT_TYPE_SENT_PULL_REQ],
2378            sums[STAT_TYPE_SENT_PULL_REP],
2379            sums[STAT_TYPE_RECV_PUSH_SEND],
2380            sums[STAT_TYPE_RECV_PULL_REQ],
2381            sums[STAT_TYPE_RECV_PULL_REP]);
2382 }
2383
2384 /**
2385  * Continuation called by #GNUNET_STATISTICS_get() functions.
2386  *
2387  * Remembers that this specific statistics value was received for this peer.
2388  * Checks whether all peers received their statistics yet.
2389  * Issues the shutdown.
2390  *
2391  * @param cls closure
2392  * @param success #GNUNET_OK if statistics were
2393  *        successfully obtained, #GNUNET_SYSERR if not.
2394  */
2395 void
2396 post_test_shutdown_ready_cb (void *cls,
2397                              int success)
2398 {
2399   struct STATcls *stat_cls = (struct STATcls *) cls;
2400   struct RPSPeer *rps_peer = stat_cls->rps_peer;
2401
2402   rps_peer->h_stat_get[stat_cls->stat_type] = NULL;
2403   if (GNUNET_OK == success)
2404   {
2405     /* set flag that we we got the value */
2406     rps_peer->stat_collected_flags |= BIT(stat_cls->stat_type);
2407   } else {
2408     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2409         "Peer %u did not receive statistics value\n",
2410         rps_peer->index);
2411     GNUNET_free (stat_cls);
2412     GNUNET_break (0);
2413     return;
2414   }
2415
2416   if (NULL != rps_peer->stat_op &&
2417       GNUNET_YES == check_statistics_collect_completed_single_peer (rps_peer))
2418   {
2419     GNUNET_TESTBED_operation_done (rps_peer->stat_op);
2420   }
2421
2422   //write_final_stats ();
2423   if (GNUNET_YES == check_statistics_collect_completed())
2424   {
2425     write_final_stats ();
2426     GNUNET_free (stat_cls);
2427     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2428         "Shutting down\n");
2429     GNUNET_SCHEDULER_shutdown ();
2430   } else {
2431     GNUNET_free (stat_cls);
2432   }
2433 }
2434
2435 /**
2436  * Callback function to process statistic values.
2437  *
2438  * @param cls closure
2439  * @param subsystem name of subsystem that created the statistic
2440  * @param name the name of the datum
2441  * @param value the current value
2442  * @param is_persistent #GNUNET_YES if the value is persistent, #GNUNET_NO if not
2443  * @return #GNUNET_OK to continue, #GNUNET_SYSERR to abort iteration
2444  */
2445 int
2446 stat_iterator (void *cls,
2447                const char *subsystem,
2448                const char *name,
2449                uint64_t value,
2450                int is_persistent)
2451 {
2452   const struct STATcls *stat_cls = (const struct STATcls *) cls;
2453   struct RPSPeer *rps_peer = (struct RPSPeer *) stat_cls->rps_peer;
2454   enum STAT_TYPE stat_type;
2455   (void) subsystem;
2456   (void) is_persistent;
2457
2458   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got stat value: %s - %" PRIu64 "\n",
2459       name,
2460       value);
2461   to_file (rps_peer->file_name_stats,
2462           "%s: %" PRIu64 "\n",
2463           name,
2464           value);
2465   stat_type = stat_str_2_type (name);
2466   GNUNET_assert (STAT_TYPE_ROUNDS <= stat_type &&
2467                  STAT_TYPE_MAX > stat_type);
2468   rps_peer->stats[stat_type] = value;
2469   return GNUNET_OK;
2470 }
2471
2472 void post_profiler (struct RPSPeer *rps_peer)
2473 {
2474   if (COLLECT_STATISTICS != cur_test_run.have_collect_statistics)
2475   {
2476     return;
2477   }
2478
2479   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2480       "Going to request statistic values with mask 0x%" PRIx32 "\n",
2481       cur_test_run.stat_collect_flags);
2482
2483   struct STATcls *stat_cls;
2484   uint32_t stat_type;
2485   for (stat_type = STAT_TYPE_ROUNDS;
2486       stat_type < STAT_TYPE_MAX;
2487       stat_type++)
2488   {
2489     if (BIT(stat_type) & cur_test_run.stat_collect_flags)
2490     {
2491       stat_cls = GNUNET_malloc (sizeof (struct STATcls));
2492       stat_cls->rps_peer = rps_peer;
2493       stat_cls->stat_type = stat_type;
2494       rps_peer->file_name_stats =
2495         store_prefix_file_name (rps_peer->peer_id, "stats");
2496       rps_peer->h_stat_get[stat_type] =
2497         GNUNET_STATISTICS_get (rps_peer->stats_h,
2498                                "rps",
2499                                stat_type_strings [stat_type],
2500                                post_test_shutdown_ready_cb,
2501                                stat_iterator,
2502                                (struct STATcls *) stat_cls);
2503       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2504                   "Requested statistics for %s (peer %" PRIu32 ")\n",
2505                   stat_type_strings [stat_type],
2506                   rps_peer->index);
2507     }
2508   }
2509 }
2510
2511
2512 /***********************************************************************
2513  * /Definition of tests
2514 ***********************************************************************/
2515
2516
2517 /**
2518  * Actual "main" function for the testcase.
2519  *
2520  * @param cls closure
2521  * @param h the run handle
2522  * @param n_peers number of peers in 'peers'
2523  * @param peers handle to peers run in the testbed
2524  * @param links_succeeded the number of overlay link connection attempts that
2525  *          succeeded
2526  * @param links_failed the number of overlay link connection attempts that
2527  *          failed
2528  */
2529 static void
2530 test_run (void *cls,
2531      struct GNUNET_TESTBED_RunHandle *h,
2532      unsigned int n_peers,
2533      struct GNUNET_TESTBED_Peer **peers,
2534      unsigned int links_succeeded,
2535      unsigned int links_failed)
2536 {
2537   unsigned int i;
2538   struct OpListEntry *entry;
2539   (void) cls;
2540   (void) h;
2541   (void) links_failed;
2542
2543   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "RUN was called\n");
2544
2545   /* Check whether we timed out */
2546   if (n_peers != num_peers ||
2547       NULL == peers ||
2548       0 == links_succeeded)
2549   {
2550     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Going down due to args (eg. timeout)\n");
2551     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tn_peers: %u\n", n_peers);
2552     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tnum_peers: %" PRIu32 "\n", num_peers);
2553     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tpeers: %p\n", peers);
2554     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "\tlinks_succeeded: %u\n", links_succeeded);
2555     GNUNET_SCHEDULER_shutdown ();
2556     return;
2557   }
2558
2559
2560   /* Initialize peers */
2561   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "going to initialise peers\n");
2562   testbed_peers = peers;
2563   num_peers_online = 0;
2564   for (i = 0; i < num_peers; i++)
2565   {
2566     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "initialising %u\n", i);
2567     entry = make_oplist_entry ();
2568     entry->index = i;
2569     rps_peers[i].index = i;
2570     if (NULL != cur_test_run.init_peer)
2571       cur_test_run.init_peer (&rps_peers[i]);
2572     if (NO_COLLECT_VIEW == cur_test_run.have_collect_view)
2573     {
2574       rps_peers->cur_view_count = 0;
2575       rps_peers->cur_view = NULL;
2576     }
2577     entry->op = GNUNET_TESTBED_peer_get_information (peers[i],
2578                                                      GNUNET_TESTBED_PIT_IDENTITY,
2579                                                      &info_cb,
2580                                                      entry);
2581   }
2582
2583   /* Bring peers up */
2584   GNUNET_assert (num_peers == n_peers);
2585   for (i = 0; i < n_peers; i++)
2586   {
2587     rps_peers[i].index = i;
2588     rps_peers[i].op =
2589       GNUNET_TESTBED_service_connect (&rps_peers[i],
2590                                       peers[i],
2591                                       "rps",
2592                                       &rps_connect_complete_cb,
2593                                       &rps_peers[i],
2594                                       &rps_connect_adapter,
2595                                       &rps_disconnect_adapter,
2596                                       &rps_peers[i]);
2597     /* Connect all peers to statistics service */
2598     if (COLLECT_STATISTICS == cur_test_run.have_collect_statistics)
2599     {
2600       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2601                  "Connecting to statistics service\n");
2602       rps_peers[i].stat_op =
2603         GNUNET_TESTBED_service_connect (NULL,
2604                                         peers[i],
2605                                         "statistics",
2606                                         stat_complete_cb,
2607                                         &rps_peers[i],
2608                                         &stat_connect_adapter,
2609                                         &stat_disconnect_adapter,
2610                                         &rps_peers[i]);
2611     }
2612   }
2613
2614   if (NULL != churn_task)
2615     GNUNET_SCHEDULER_cancel (churn_task);
2616   post_test_task = GNUNET_SCHEDULER_add_delayed (duration, &post_test_op, NULL);
2617   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "timeout for shutdown is %lu\n", timeout.rel_value_us/1000000);
2618   shutdown_task = GNUNET_SCHEDULER_add_delayed (timeout,
2619                                                 &trigger_shutdown,
2620                                                 NULL);
2621   GNUNET_SCHEDULER_add_shutdown (shutdown_op, NULL);
2622 }
2623
2624
2625 /**
2626  * Entry point for the testcase, sets up the testbed.
2627  *
2628  * @param argc unused
2629  * @param argv unused
2630  */
2631 static void
2632 run (void *cls,
2633      char *const *args,
2634      const char *cfgfile,
2635      const struct GNUNET_CONFIGURATION_Handle *cfg)
2636 {
2637   //int ret_value;
2638   (void) cls;
2639   (void) args;
2640   (void) cfgfile;
2641
2642   /* Defaults for tests */
2643   churn_task = NULL;
2644
2645   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "This is the profiler\n");
2646   cur_test_run.name = "test-rps-profiler";
2647   if (0 == num_peers) num_peers = 10;
2648   mal_type = 3;
2649   cur_test_run.init_peer = profiler_init_peer;
2650   //cur_test_run.pre_test = mal_pre;
2651   cur_test_run.pre_test = pre_profiler;
2652   cur_test_run.main_test = profiler_cb;
2653   cur_test_run.reply_handle = profiler_reply_handle;
2654   cur_test_run.eval_cb = profiler_eval;
2655   cur_test_run.post_test = post_profiler;
2656   cur_test_run.request_interval = 2;
2657   if (0 == cur_test_run.num_requests) cur_test_run.num_requests = 5;
2658   //cur_test_run.have_churn = HAVE_CHURN;
2659   cur_test_run.have_churn = HAVE_NO_CHURN;
2660   cur_test_run.have_quick_quit = HAVE_QUICK_QUIT;
2661   cur_test_run.have_collect_statistics = COLLECT_STATISTICS;
2662   cur_test_run.stat_collect_flags = BIT(STAT_TYPE_ROUNDS) |
2663                                     BIT(STAT_TYPE_BLOCKS) |
2664                                     BIT(STAT_TYPE_BLOCKS_MANY_PUSH) |
2665                                     BIT(STAT_TYPE_BLOCKS_NO_PUSH) |
2666                                     BIT(STAT_TYPE_BLOCKS_NO_PULL) |
2667                                     BIT(STAT_TYPE_BLOCKS_MANY_PUSH_NO_PULL) |
2668                                     BIT(STAT_TYPE_BLOCKS_NO_PUSH_NO_PULL) |
2669                                     BIT(STAT_TYPE_ISSUED_PUSH_SEND) |
2670                                     BIT(STAT_TYPE_ISSUED_PULL_REQ) |
2671                                     BIT(STAT_TYPE_ISSUED_PULL_REP) |
2672                                     BIT(STAT_TYPE_SENT_PUSH_SEND) |
2673                                     BIT(STAT_TYPE_SENT_PULL_REQ) |
2674                                     BIT(STAT_TYPE_SENT_PULL_REP) |
2675                                     BIT(STAT_TYPE_RECV_PUSH_SEND) |
2676                                     BIT(STAT_TYPE_RECV_PULL_REQ) |
2677                                     BIT(STAT_TYPE_RECV_PULL_REP);
2678   cur_test_run.have_collect_view = COLLECT_VIEW;
2679
2680   /* 'Clean' directory */
2681   (void) GNUNET_DISK_directory_remove ("/tmp/rps/");
2682   GNUNET_DISK_directory_create ("/tmp/rps/");
2683   if (0 == duration.rel_value_us)
2684   {
2685     if (0 == timeout.rel_value_us)
2686     {
2687       duration = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 90);
2688       timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
2689                                                (90 * 1.2) +
2690                                                  (0.01 * num_peers));
2691     }
2692     else
2693     {
2694       duration = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
2695                                                 (timeout.rel_value_us/1000000)
2696                                                   * 0.75);
2697     }
2698   }
2699   else
2700   {
2701     if (0 == timeout.rel_value_us)
2702     {
2703       timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
2704                                                ((duration.rel_value_us/1000000)
2705                                                   * 1.2) + (0.01 * num_peers));
2706     }
2707   }
2708   GNUNET_assert (duration.rel_value_us < timeout.rel_value_us);
2709   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2710               "duration is %lus\n",
2711               duration.rel_value_us/1000000);
2712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2713               "timeout is %lus\n",
2714               timeout.rel_value_us/1000000);
2715
2716   /* Compute number of bits for representing largest peer id */
2717   for (bits_needed = 1; (1 << bits_needed) < num_peers; bits_needed++)
2718     ;
2719   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
2720             "Need %u bits to represent %" PRIu32 " peers\n",
2721              bits_needed,
2722              num_peers);
2723
2724   rps_peers = GNUNET_new_array (num_peers, struct RPSPeer);
2725   peer_map = GNUNET_CONTAINER_multipeermap_create (num_peers, GNUNET_NO);
2726   rps_peer_ids = GNUNET_new_array (num_peers, struct GNUNET_PeerIdentity);
2727   if ( (2 == mal_type) ||
2728        (3 == mal_type))
2729     target_peer = &rps_peer_ids[num_peers - 2];
2730   if (profiler_eval == cur_test_run.eval_cb)
2731     eval_peer = &rps_peers[num_peers - 1];    /* FIXME: eval_peer could be a
2732                                                  malicious peer if not careful
2733                                                  with the malicious portion */
2734
2735   ok = 1;
2736   GNUNET_TESTBED_run (NULL,
2737                       cfg,
2738                       num_peers,
2739                       0, /* event mask */
2740                       NULL,
2741                       NULL,
2742                       &test_run,
2743                       NULL);
2744 }
2745
2746 /**
2747  * Entry point for the testcase, sets up the testbed.
2748  *
2749  * @param argc unused
2750  * @param argv unused
2751  * @return 0 on success
2752  */
2753 int
2754 main (int argc, char *argv[])
2755 {
2756   int ret_value;
2757   struct GNUNET_GETOPT_CommandLineOption options[] = {
2758     GNUNET_GETOPT_option_uint ('n',
2759                                "num-peers",
2760                                "COUNT",
2761                                gettext_noop ("number of peers to start"),
2762                                &num_peers),
2763
2764     GNUNET_GETOPT_option_relative_time ('d',
2765                                         "duration",
2766                                         "DURATION",
2767                                         gettext_noop ("duration of the profiling"),
2768                                         &duration),
2769
2770     GNUNET_GETOPT_option_relative_time ('t',
2771                                         "timeout",
2772                                         "TIMEOUT",
2773                                         gettext_noop ("timeout for the profiling"),
2774                                         &timeout),
2775
2776     GNUNET_GETOPT_option_uint ('r',
2777                                "num-requests",
2778                                "COUNT",
2779                                gettext_noop ("number of PeerIDs to request"),
2780                                &cur_test_run.num_requests),
2781
2782     GNUNET_GETOPT_OPTION_END
2783   };
2784
2785   //if (GNUNET_OK !=
2786   //    GNUNET_STRINGS_get_utf8_args (argc, argv,
2787   //                                  &argc, &argv))
2788   //  return 2;
2789   ret_value = 0;
2790   if (GNUNET_OK !=
2791       GNUNET_PROGRAM_run (argc,
2792                           argv,
2793                           "gnunet-rps-profiler",
2794                           gettext_noop ("Measure quality and performance of the RPS service."),
2795                           options,
2796                           &run,
2797                           NULL))
2798   {
2799     ret_value = 1;
2800   }
2801   if (GNUNET_OK != ret_value)
2802   {
2803     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
2804                 "Test did not run successfully!\n");
2805   }
2806
2807   ret_value = cur_test_run.eval_cb();
2808   if (NO_COLLECT_VIEW == cur_test_run.have_collect_view)
2809   {
2810     GNUNET_array_grow (rps_peers->cur_view,
2811                        rps_peers->cur_view_count,
2812                        0);
2813   }
2814   GNUNET_free (rps_peers);
2815   GNUNET_free (rps_peer_ids);
2816   GNUNET_CONTAINER_multipeermap_destroy (peer_map);
2817   return ret_value;
2818 }
2819
2820 /* end of test_rps.c */