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