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