386e97190d9010b088cd9f43a0e9836726aa8a7f
[oweals/gnunet.git] / src / rps / gnunet-service-rps.c
1 /*
2      This file is part of GNUnet.
3      (C)
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., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file rps/gnunet-service-rps.c
23  * @brief rps service implementation
24  * @author Julius Bünger
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_cadet_service.h"
29 #include "gnunet_nse_service.h"
30 #include "rps.h"
31
32 #include <math.h>
33 #include <inttypes.h>
34
35 #define LOG(kind, ...) GNUNET_log(kind, __VA_ARGS__)
36
37 // TODO modify @brief in every file
38
39 // TODO take care that messages are not longer than 64k
40
41 // TODO check for overflows
42
43 // TODO align message structs
44
45 // TODO multipeerlist indep of gossiped list
46
47 // (TODO api -- possibility of getting weak random peer immideately)
48
49 // TODO malicious peer
50
51 // TODO switch Slist -> DLL
52
53 /**
54  * Our configuration.
55  */
56 static const struct GNUNET_CONFIGURATION_Handle *cfg;
57
58 /**
59  * Our own identity.
60  */
61 struct GNUNET_PeerIdentity *own_identity;
62
63 /**
64  * Compare two peer identities. Taken from secretsharing.
65  *
66  * @param p1 Some peer identity.
67  * @param p2 Some peer identity.
68  * @return 1 if p1 > p2, -1 if p1 < p2 and 0 if p1 == p2.
69  */
70 static int
71 peer_id_cmp (const void *p1, const void *p2)
72 {
73   return memcmp (p1, p2, sizeof (struct GNUNET_PeerIdentity));
74 }
75
76 /***********************************************************************
77  * Sampler
78  *
79  * WARNING: This section needs to be reviewed regarding the use of
80  * functions providing (pseudo)randomness!
81 ***********************************************************************/
82
83 // TODO care about invalid input of the caller (size 0 or less...)
84
85 /**
86  * A sampler sampling PeerIDs.
87  */
88 struct Sampler
89 {
90   /**
91    * Min-wise linear permutation used by this sampler.
92    *
93    * This is an key later used by a hmac.
94    */
95   struct GNUNET_CRYPTO_AuthKey auth_key;
96
97   /**
98    * The PeerID this sampler currently samples.
99    */
100   struct GNUNET_PeerIdentity *peer_id;
101
102   /**
103    * The according hash value of this PeerID.
104    */
105   struct GNUNET_HashCode peer_id_hash;
106
107   /**
108    * Samplers are kept in a linked list.
109    */
110   struct Sampler *next;
111
112   /**
113    * Samplers are kept in a linked list.
114    */
115   struct Sampler *prev;
116
117 };
118
119 /**
120  * A n-tuple of samplers.
121  */
122 struct Samplers
123 {
124   /**
125    * Number of samplers we hold.
126    */
127   size_t size;
128   
129   /**
130    * All PeerIDs in one array.
131    */
132   struct GNUNET_PeerIdentity peer_ids[];
133
134   /**
135    * The head of the DLL.
136    */
137   struct Sampler *head;
138
139   /**
140    * The tail of the DLL.
141    */
142   struct Sampler *tail;
143
144 };
145
146
147 typedef void (* SAMPLER_deleteCB) (void *cls, const struct GNUNET_PeerIdentity *id, struct GNUNET_HashCode hash);
148
149 /**
150  * (Re)Initialise given Sampler with random min-wise independent function.
151  *
152  * In this implementation this means choosing an auth_key for later use in
153  * a hmac at random.
154  *
155  * @param id pointer to the place where this sampler will store the PeerID.
156  *           This will be overwritten.
157  */
158   struct Sampler *
159 SAMPLER_init(struct GNUNET_PeerIdentity *id)
160 {
161   struct Sampler *s;
162   
163   s = GNUNET_new(struct Sampler);
164
165   // I guess I don't need to call GNUNET_CRYPTO_hmac_derive_key()...
166   GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_STRONG,
167                              &(s->auth_key.key),
168                              GNUNET_CRYPTO_HASH_LENGTH);
169
170   //s->peer_id = GNUNET_new( struct GNUNET_PeerIdentity );
171   GNUENT_assert(NULL != id);
172   s->peer_id = id;
173   memcpy(s->peer_id, own_identity, sizeof(struct GNUNET_PeerIdentity));
174   //s->peer_id = own_identity; // Maybe set to own PeerID. So we always have
175                      // a valid PeerID in the sampler.
176                      // Maybe take a PeerID as second argument.
177   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: initialised with PeerID %s (at %p) \n", GNUNET_i2s(s->peer_id), s->peer_id);
178
179   GNUNET_CRYPTO_hmac(&s->auth_key, s->peer_id,
180                      sizeof(struct GNUNET_PeerIdentity),
181                      &s->peer_id_hash);
182
183   s->prev = NULL;
184   s->next = NULL;
185
186   return s;
187 }
188
189 /**
190  * Compare two hashes.
191  *
192  * Returns if the first one is smaller then the second.
193  * Used by SAMPLER_next() to compare hashes.
194  */
195   int
196 hash_cmp(struct GNUNET_HashCode hash1, struct GNUNET_HashCode hash2)
197 {
198   return memcmp( (const void *) &hash1, (const void *) & hash2, sizeof(struct GNUNET_HashCode));
199 }
200
201 /**
202  * Input an PeerID into the given sampler.
203  */
204   static void
205 SAMPLER_next(struct Sampler *s, const struct GNUNET_PeerIdentity *id, SAMPLER_deleteCB del_cb, void *cb_cls)
206   // TODO set id in peer_ids
207 {
208   struct GNUNET_HashCode other_hash;
209
210   if ( id == s->peer_id )
211   {
212     LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:          Got PeerID %s\n",
213         GNUNET_i2s(id));
214     LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Have already PeerID %s\n",
215         GNUNET_i2s(s->peer_id));
216   }
217   else
218   {
219     GNUNET_CRYPTO_hmac(&s->auth_key,
220         id,
221         sizeof(struct GNUNET_PeerIdentity),
222         &other_hash);
223
224     if ( NULL == s->peer_id )
225     { // Or whatever is a valid way to say
226       // "we have no PeerID at the moment"
227       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Got PeerID %s; Simply accepting (got NULL previously).\n",
228           GNUNET_i2s(id));
229       memcpy(s->peer_id, id, sizeof(struct GNUNET_PeerIdentity));
230       //s->peer_id = id;
231       s->peer_id_hash = other_hash;
232     }
233     else if ( 0 > hash_cmp(other_hash, s->peer_id_hash) )
234     {
235       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:            Got PeerID %s\n",
236           GNUNET_i2s(id));
237       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Discarding old PeerID %s\n",
238           GNUNET_i2s(s->peer_id));
239
240       if ( NULL != del_cb )
241       {
242         LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Removing old PeerID %s with the delete callback.\n",
243             GNUNET_i2s(s->peer_id));
244         del_cb(cb_cls, s->peer_id, s->peer_id_hash);
245       }
246
247       memcpy(s->peer_id, id, sizeof(struct GNUNET_PeerIdentity));
248       //s->peer_id = id;
249       s->peer_id_hash = other_hash;
250     }
251     else
252     {
253       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER:         Got PeerID %s\n",
254           GNUNET_i2s(id), id);
255       LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER: Keeping old PeerID %s\n",
256           GNUNET_i2s(s->peer_id), s->peer_id);
257     }
258   }
259 }
260
261
262 /**
263  * Initialise a tuple of samplers.
264  */
265 struct Samplers *
266 SAMPLER_samplers_init(size_t init_size)
267 {
268   struct Samplers *samplers;
269   struct Sampler *s;
270   uint64_t i;
271
272   samplers = GNUNET_new(struct Samplers);
273   samplers->size = init_size;
274   samplers->head = samplers->tail = NULL;
275   samplers->peer_ids = GNUNET_new_array(init_size, struct GNUNET_PeerIdentity);
276
277   for ( i = 0 ; i < init_size ; i++ )
278   {
279     GNUNET_array_append(samplers->peer_ids,
280         sizeof(struct GNUNET_PeerIdentity),
281         own_identity);
282     s = SAMPLER_init(&samplers->peer_ids[i]);
283     GNUNET_CONTAINER_DLL_insert_tail(samplers->head,
284         samplers->tail,
285         );
286   }
287   return sammplers;
288 }
289
290
291 /**
292  * A fuction to update every sampler in the given list
293  */
294   static void
295 SAMPLER_update_list(struct Samplers *samplers, const struct GNUNET_PeerIdentity *id,
296                     SAMPLER_deleteCB del_cb, void *cb_cls)
297 {
298   struct Sampler *sampler;
299
300   sampler = samplers->head;
301   while ( NULL != sampler->next )
302   {
303     SAMPLER_next(sampler, id, del_cb, cb_cls);
304   }
305   
306 }
307
308 /**
309  * Get one random peer out of the sampled peers.
310  *
311  * We might want to reinitialise this sampler after giving the
312  * corrsponding peer to the client.
313  */
314   const struct GNUNET_PeerIdentity* 
315 SAMPLER_get_rand_peer (struct Samplers *samplers)
316 {
317   LOG(GNUNET_ERROR_TYPE_DEBUG, "SAMPLER_get_rand_peer:\n");
318
319   if ( 0 == samplers->size )
320   {
321     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sgrp: List empty - Returning own PeerID %s\n", GNUNET_i2s(own_identity));
322     return own_identity;
323   }
324   else
325   {
326     uint64_t index;
327     struct Sampler *iter;
328     uint64_t i;
329     size_t s;
330     const struct GNUNET_PeerIdentity *peer;
331
332     /**
333      * Choose the index of the peer we want to give back
334      * at random from the interval of the sampler list
335      */
336     index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
337                                      list_size);
338                                      // TODO check that it does not overflow
339     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sgrp: Length of Slist: %" PRIu64 ", index: %" PRIu64 "\n", list_size, index);
340
341     s = sizeof( struct Sampler );
342     iter = samplers->head;
343     for ( i = 0 ; i < index ; i++ )
344     {
345       if ( NULL == iter->next )
346       { // Maybe unneeded
347         iter = samplers->head;
348       }
349     }
350     
351     // TODO something missing?
352
353     peer = iter->peer_id;
354     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sgrp: Returning PeerID %s\n", GNUNET_i2s(peer));
355     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sgrp: (own ID: %s)\n", GNUNET_i2s(own_identity));
356
357     return peer;
358   }
359 }
360
361 /**
362  * Get n random peers out of the sampled peers.
363  *
364  * We might want to reinitialise this sampler after giving the
365  * corrsponding peer to the client.
366  * Random with or without consumption?
367  */
368   const struct GNUNET_PeerIdentity*  // TODO give back simple array
369 SAMPLER_get_n_rand_peers (struct Samplers *samplers, uint64_t n)
370 {
371   // TODO check if we have too much (distinct) sampled peers
372   // If we are not ready yet maybe schedule for later
373   const struct GNUNET_PeerIdentity *peers;
374   uint64_t i;
375   
376   peers = GNUNET_malloc(n * sizeof(struct GNUNET_PeerIdentity));
377
378   for ( i = 0 ; i < n ; i++ ) {
379     peers[i] = SAMPLER_get_rand_peer(samplers);
380   }
381
382   // TODO something else missing?
383   return peers;
384 }
385
386 /**
387  * Counts how many Samplers currently hold a given PeerID.
388  */
389   uint64_t
390 SAMPLER_count_id ( struct Samplers *samplers, struct GNUNET_PeerIdentity *id )
391 {
392   struct Sampler *iter;
393   uint64_t count;
394
395   iter = samplers->head;
396   count = 0;
397   while ( NULL != iter )
398   {
399     if ( peer_id_cmp( iter->peer_id, id) )
400       count++;
401     iter = iter->next;
402   }
403   return count;
404 }
405
406 /**
407  * Gow the size of the tuple of samplers.
408  */
409   void
410 SAMPLER_samplers_grow (struct Samplers * samplers, size_t new_size)
411 {
412   uint64_t i;
413   struct Sampler;
414
415   if ( new_size > samplers->size )
416   {
417     GNUNET_array_grow(samplers->peer_ids, samplers->size, new_size);
418     for ( i = 0 ; i < new_size - samplers-size ; i++ )
419     {
420       sampler = SAMPLER_init(&samplers->peer_ids[samplers->size + i]);
421       GNUNET_CONTAINER_DLL_insert_tail(samplers->head, samplers->tail, sampler);
422     }
423   }
424   else if ( new_size < samplers->size )
425   {
426     for ( i = 0 ; i < samplers->size - new_size ; i++)
427     {
428       // TODO call delCB on elem?
429       GNUNET_CONTAINER_DLL_remove(samplers->head, samplers->tail, samplers->tail);
430     }
431     GNUNET_array_grow(samplers->peer_ids, samplers->size, new_size);
432   }
433
434   samplers->size = new_size;
435 }
436
437 /***********************************************************************
438  * /Sampler
439 ***********************************************************************/
440
441
442
443 /***********************************************************************
444  * Peer list
445 ***********************************************************************/
446
447 /**
448  * A struct that just holds the PeerID.
449  */
450 struct PeerEntry
451 {
452   /**
453    * The PeerID.
454    */
455   struct GNUNET_PeerIdentity *id;
456 };
457
458 /**
459  * A DLL holding PeerIDs.
460  */
461 struct PeerList
462 {
463   /**
464    * The size of the list.
465    */
466   size_t size;
467
468   /**
469    * Array of PeerIDs.
470    */
471   struct GNUNET_PeerIdentity *peer_ids;
472
473   /**
474    * Head of the DLL.
475    */
476   struct PeerEntry *head;
477
478   /**
479    * Tail of the DLL.
480    */
481   struct PeerEntry *tail;
482 };
483
484 /**
485  * Give back an empty PeerList.
486  */
487   struct PeerList*
488 PeerList_init()
489 {
490   struct PeerList *peer_list;
491
492   peer_list = GNUNET_new(struct PeerList);
493   peer_list->size = 0;
494   peer_list->peer_ids = NULL;
495   peer_list->head = peer_list->tail = NULL;
496
497   return peer_list;
498 }
499
500 /**
501  * Put one PeerID into the given PeerList.
502  */
503   void
504 PeerList_put(struct PeerList *peer_list, struct GNUNET_PeerIdentity *id)
505 {
506 }
507
508 ///**
509 // * Get one random peer out of the gossiped peer list.
510 // */
511 //  struct GNUNET_PeerIdentity *
512 //get_random_peer(struct GNUNET_CONTAINER_MultiPeerMap * lst)
513 //{
514 //  size_t n;
515 //  struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
516 //  uint64_t index;
517 //  uint64_t i;
518 //  struct GNUNET_PeerIdentity *peer;
519 //
520 //  n = (size_t) GNUNET_CONTAINER_multipeermap_size(lst);
521 //  index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
522 //                                   (uint64_t) n);
523 //  iter = GNUNET_CONTAINER_multipeermap_iterator_create(lst);
524 //
525 //  for ( i = 0 ; i < index ; i++ ) {
526 //    GNUNET_CONTAINER_multipeermap_iterator_next(iter, NULL, NULL);
527 //  }
528 //  
529 //  peer = GNUNET_malloc(sizeof(struct GNUNET_PeerIdentity));
530 //  GNUNET_CONTAINER_multipeermap_iterator_next(iter, peer, NULL);
531 //
532 //  return peer;
533 //}
534
535
536 /***********************************************************************
537  * /Peer list
538 ***********************************************************************/
539
540
541
542 /***********************************************************************
543  * Housekeeping with peers
544 ***********************************************************************/
545
546 /**
547  * Struct used to store the context of a connected client.
548  */
549 struct client_ctx
550 {
551   /**
552    * The message queue to communicate with the client.
553    */
554   struct GNUNET_MQ_Handle *mq;
555 };
556
557 /**
558  * Used to keep track in what lists single peerIDs are.
559  */
560 enum in_list_flag // probably unneeded
561 {
562   in_other_sampler_list = 0x1,
563   in_other_gossip_list  = 0x2, // unneeded?
564   in_own_sampler_list   = 0x4,
565   in_own_gossip_list    = 0x8 // unneeded?
566 };
567
568 /**
569  * Struct used to keep track of other peer's status
570  *
571  * This is stored in a multipeermap.
572  */
573 struct peer_context
574 {
575   /**
576    * In own gossip/sampler list, in other's gossip/sampler list
577    */
578   uint32_t in_flags; // unneeded?
579
580   /**
581    * Message queue open to client
582    */
583   struct GNUNET_MQ_Handle *mq;
584
585   /**
586    * Channel open to client.
587    */
588   struct GNUNET_CADET_Channel *to_channel;
589
590   /**
591    * Channel open from client.
592    */
593   struct GNUNET_CADET_Channel *from_channel; // unneeded
594
595   /**
596    * This is pobably followed by 'statistical' data (when we first saw
597    * him, how did we get his ID, how many pushes (in a timeinterval),
598    * ...)
599    */
600 };
601
602 /***********************************************************************
603  * /Housekeeping with peers
604 ***********************************************************************/
605
606 /**
607  * Set of all peers to keep track of them.
608  */
609 static struct GNUNET_CONTAINER_MultiPeerMap *peer_map;
610
611
612 // -- gossip list length --
613 // Depends on the (estimated) size of the
614 // network. - Initial size might be the
615 // number of peers cadet provides.
616 // TODO other events to grow/shrink size?
617
618 /**
619  * List of samplers // TODO get rid of that
620  */
621 struct GNUNET_CONTAINER_SList *sampler_list;
622
623 /**
624  * List of samplers.
625  */
626 struct Samplers *samplers; // TODO rename to sampler_list
627
628 /**
629  * Sampler list size // TODO get rid of that
630  *
631  * Adapts to the nse. Size should be in BigTheta(network_size)^(1/3).
632  */
633 size_t sampler_list_size;
634
635
636 /**
637  * The gossiped list of peers.
638  */
639 struct GNUNET_PeerIdentity *gossip_list;
640
641 /**
642  * Size of the gossiped list
643  */
644 unsigned int gossip_list_size;
645
646 /**
647  * Min size of the gossip list
648  */
649 uint64_t gossip_list_min_size;
650
651 ///**
652 // * Max size of the gossip list
653 // * 
654 // * This will probably be left to be set by the client.
655 // */
656 //uint64_t gossip_list_max_size;
657
658
659 /**
660  * The estimated size of the network.
661  *
662  * Influenced by the stdev.
663  */
664 size_t est_size;
665
666
667
668 /**
669  * Percentage of total peer number in the gossip list
670  * to send random PUSHes to
671  */
672 float alpha;
673
674 /**
675  * Percentage of total peer number in the gossip list
676  * to send random PULLs to
677  */
678 float beta;
679
680 /**
681  * The percentage gamma of history updates.
682  * Simply 1 - alpha - beta
683  */
684
685
686
687
688 /**
689  * Identifier for the main task that runs periodically.
690  */
691 GNUNET_SCHEDULER_TaskIdentifier do_round_task;
692
693 /**
694  * Time inverval the do_round task runs in.
695  */
696 struct GNUNET_TIME_Relative round_interval;
697
698
699
700 /**
701  * List to store peers received through pushes temporary.
702  */
703 struct GNUNET_CONTAINER_SList *push_list;
704
705 /**
706  * List to store peers received through pulls temporary.
707  */
708 struct GNUNET_CONTAINER_SList *pull_list;
709
710
711 /**
712  * Handler to NSE.
713  */
714 struct GNUNET_NSE_Handle *nse;
715
716 /**
717  * Handler to CADET.
718  */
719 struct GNUNET_CADET_Handle *cadet_handle;
720
721
722 /***********************************************************************
723  * Util functions
724 ***********************************************************************/
725
726 /**
727  * Get random peer from the gossip list.
728  */
729   struct GNUNET_PeerIdentity *
730 get_rand_gossip_peer()
731 {
732   uint64_t index;
733   struct GNUNET_PeerIdentity *peer;
734
735   // TODO find a better solution.
736   // FIXME if we have only own ID in gossip list this will block
737   // but then we might have a problem nevertheless ?
738
739   do {
740
741     /**;
742      * Choose the index of the peer we want to return
743      * at random from the interval of the gossip list
744      */
745     index = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG,
746                                      gossip_list_size);
747
748     peer = &(gossip_list[index]);
749   } while ( own_identity == peer || NULL == peer );
750
751   return peer;
752 }
753
754 /**
755  * Get the message queue of a specific peer.
756  *
757  * If we already have a message queue open to this client,
758  * simply return it, otherways create one.
759  */
760   struct GNUNET_MQ_Handle *
761 get_mq (struct GNUNET_CONTAINER_MultiPeerMap *peer_map, struct GNUNET_PeerIdentity *peer_id)
762 {
763   struct peer_context *ctx;
764   struct GNUNET_MQ_Handle * mq;
765   struct GNUNET_CADET_Channel *channel;
766
767   if ( GNUNET_OK != GNUNET_CONTAINER_multipeermap_contains( peer_map, peer_id ) ) {
768
769     channel = GNUNET_CADET_channel_create(cadet_handle, NULL, peer_id,
770                                   GNUNET_RPS_CADET_PORT,
771                                   GNUNET_CADET_OPTION_RELIABLE);
772     mq = GNUNET_CADET_mq_create(channel);
773
774     ctx = GNUNET_malloc(sizeof(struct peer_context));
775     ctx->in_flags = 0;
776     ctx->to_channel = channel;
777     ctx->mq = mq;
778
779     GNUNET_CONTAINER_multipeermap_put(peer_map, peer_id, ctx,
780                                       GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
781   } else {
782     ctx = GNUNET_CONTAINER_multipeermap_get(peer_map, peer_id);
783     if ( NULL == ctx->mq ) {
784       if ( NULL == ctx->to_channel ) {
785         channel = GNUNET_CADET_channel_create(cadet_handle, NULL, peer_id,
786                                       GNUNET_RPS_CADET_PORT,
787                                       GNUNET_CADET_OPTION_RELIABLE);
788         ctx->to_channel = channel;
789       }
790
791       mq = GNUNET_CADET_mq_create(ctx->to_channel);
792       ctx->mq = mq;
793     }
794   }
795
796   return ctx->mq;
797 }
798
799
800 /***********************************************************************
801  * /Util functions
802 ***********************************************************************/
803
804 /**
805  * Function called by NSE.
806  *
807  * Updates sizes of sampler list and gossip list and adapt those lists
808  * accordingly.
809  */
810   void
811 nse_callback(void *cls, struct GNUNET_TIME_Absolute timestamp, double logestimate, double std_dev)
812 {
813   double estimate;
814   //double scale; // TODO this might go gloabal/config
815
816   LOG(GNUNET_ERROR_TYPE_DEBUG, "Received a ns estimate - logest: %f, std_dev: %f\n", logestimate, std_dev);
817   //scale = .01;
818   estimate = 1 << (uint64_t) round(logestimate);
819   // GNUNET_NSE_log_estimate_to_n (logestimate);
820   estimate = pow(estimate, 1./3);// * (std_dev * scale); // TODO add
821   if ( 0 < estimate ) {
822     LOG(GNUNET_ERROR_TYPE_DEBUG, "Changing estimate to %f\n", estimate);
823     est_size = estimate;
824   } else {
825     LOG(GNUNET_ERROR_TYPE_DEBUG, "Not using estimate %f\n", estimate);
826   }
827 }
828
829 /**
830  * Handle RPS request from the client.
831  *
832  * @param cls closure
833  * @param client identification of the client
834  * @param message the actual message
835  */
836 static void
837 // TODO rename
838 handle_cs_request (void *cls,
839             struct GNUNET_SERVER_Client *client,
840             const struct GNUNET_MessageHeader *message)
841 {
842   LOG(GNUNET_ERROR_TYPE_DEBUG, "Client requested (a) random peer(s).\n");
843
844   struct GNUNET_RPS_CS_RequestMessage *msg;
845   //unsigned int n_arr[sampler_list_size];// =
846     //GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list_size);
847   //struct GNUNET_MQ_Handle *mq;
848   struct client_ctx *cli_ctx;
849   struct GNUNET_MQ_Envelope *ev;
850   struct GNUNET_RPS_CS_ReplyMessage *out_msg;
851   uint64_t num_peers;
852   uint64_t i;
853
854   // TODO
855   msg = (struct GNUNET_RPS_CS_RequestMessage *) message;
856   // Does not work because the compiler seems not to find it.
857   cli_ctx = GNUNET_SERVER_client_get_user_context(client, struct client_ctx);
858   if ( NULL == cli_ctx ) {
859     cli_ctx = GNUNET_new(struct client_ctx);
860     cli_ctx->mq = GNUNET_MQ_queue_for_server_client(client);
861     GNUNET_SERVER_client_set_user_context(client, cli_ctx);
862   }
863   
864   //mq = GNUNET_MQ_queue_for_server_client(client);
865     
866   // TODO How many peers do we give back?
867   // Wait until we have enough random peers?
868
869   ev = GNUNET_MQ_msg_extra(out_msg,
870                            GNUNET_ntohll(msg->num_peers) * sizeof(struct GNUNET_PeerIdentity),
871                            GNUNET_MESSAGE_TYPE_RPS_CS_REPLY);
872   out_msg->num_peers = GNUNET_ntohll(msg->num_peers);
873
874   num_peers = GNUNET_ntohll(msg->num_peers);
875   //&out_msg[1] = SAMPLER_get_n_rand_peers(sampler_list, num_peers);
876   for ( i = 0 ; i < num_peers ; i++ ) {
877     memcpy(&out_msg[1] + i * sizeof(struct GNUNET_PeerIdentity),
878            SAMPLER_get_rand_peer(sampler_list),
879            sizeof(struct GNUNET_PeerIdentity));
880   }
881   
882   GNUNET_MQ_send(cli_ctx->mq, ev);
883   //GNUNET_MQ_send(mq, ev);
884   //GNUNET_MQ_destroy(mq);
885
886   GNUNET_SERVER_receive_done (client,
887                               GNUNET_OK);
888 }
889
890 /**
891  * Handle a PUSH message from another peer.
892  *
893  * Check the proof of work and store the PeerID
894  * in the temporary list for pushed PeerIDs.
895  *
896  * @param cls Closure
897  * @param channel The channel the PUSH was received over
898  * @param channel_ctx The context associated with this channel
899  * @param msg The message header
900  */
901 static int
902 handle_peer_push (void *cls,
903     struct GNUNET_CADET_Channel *channel,
904     void **channel_ctx,
905     const struct GNUNET_MessageHeader *msg)
906 {
907   LOG(GNUNET_ERROR_TYPE_DEBUG, "PUSH received\n");
908
909   struct GNUNET_PeerIdentity *peer;
910
911   // TODO check the proof of work
912   // and check limit for PUSHes
913   // IF we count per peer PUSHes
914   // maybe remove from gossip/sampler list
915   
916   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info( channel, GNUNET_CADET_OPTION_PEER );
917   
918   /* Add the sending peer to the push_list */
919   GNUNET_CONTAINER_slist_add(push_list,
920                              GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
921                              peer, sizeof(struct GNUNET_PeerIdentity));
922
923   return GNUNET_OK;
924 }
925
926 /**
927  * Handle PULL REQUEST request message from another peer.
928  *
929  * Reply with the gossip list of PeerIDs.
930  *
931  * @param cls Closure
932  * @param channel The channel the PUSH was received over
933  * @param channel_ctx The context associated with this channel
934  * @param msg The message header
935  */
936 static int
937 handle_peer_pull_request (void *cls,
938     struct GNUNET_CADET_Channel *channel,
939     void **channel_ctx,
940     const struct GNUNET_MessageHeader *msg)
941 {
942
943   struct GNUNET_PeerIdentity *peer;
944   struct GNUNET_MQ_Handle *mq;
945   //struct GNUNET_RPS_P2P_PullRequestMessage *in_msg;
946   struct GNUNET_MQ_Envelope *ev;
947   struct GNUNET_RPS_P2P_PullReplyMessage *out_msg;
948
949   // TODO find some way to keep one peer from spamming with pull requests
950   // allow only one request per time interval ?
951   // otherwise remove from peerlist?
952
953   peer = (struct GNUNET_PeerIdentity *) GNUNET_CADET_channel_get_info(channel, GNUNET_CADET_OPTION_PEER);
954   LOG(GNUNET_ERROR_TYPE_DEBUG, "PULL REQUEST from peer %s received\n", GNUNET_i2s(peer));
955
956   mq = GNUNET_CADET_mq_create(channel); // TODO without mq?
957   //mq = get_mq(peer_map, peer);
958
959   //in_msg = (struct GNUNET_RPS_P2P_PullRequestMessage *) msg;
960   // TODO how many peers do we actually send?
961   // GNUNET_ntohll(in_msg->num_peers)
962   ev = GNUNET_MQ_msg_extra(out_msg,
963                            gossip_list_size * sizeof(struct GNUNET_PeerIdentity),
964                            GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY);
965   out_msg->num_peers = GNUNET_htonll(gossip_list_size);
966   memcpy(&out_msg[1], gossip_list,
967          gossip_list_size * sizeof(struct GNUNET_PeerIdentity));
968
969   GNUNET_MQ_send(mq, ev);
970
971   GNUNET_MQ_destroy(mq);
972
973
974   return GNUNET_OK;
975 }
976
977 /**
978  * Handle PULL REPLY message from another peer.
979  *
980  * Check whether we sent a corresponding request and
981  * whether this reply is the first one.
982  *
983  * @param cls Closure
984  * @param channel The channel the PUSH was received over
985  * @param channel_ctx The context associated with this channel
986  * @param msg The message header
987  */
988 static int
989 handle_peer_pull_reply (void *cls,
990     struct GNUNET_CADET_Channel *channel,
991     void **channel_ctx,
992     const struct GNUNET_MessageHeader *msg)
993 {
994   LOG(GNUNET_ERROR_TYPE_DEBUG, "PULL REPLY received\n");
995
996   struct GNUNET_RPS_P2P_PullReplyMessage *in_msg;
997   uint64_t i;
998
999   // TODO check that we sent a request and that it is the first reply
1000
1001   in_msg = (struct GNUNET_RPS_P2P_PullReplyMessage *) msg;
1002   for ( i = 0 ; i < in_msg->num_peers ; i++ ) {
1003     GNUNET_CONTAINER_slist_add(pull_list,
1004                                GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT,
1005                                &in_msg[1] + i * sizeof(struct GNUNET_PeerIdentity),
1006                                sizeof(struct GNUNET_PeerIdentity));
1007   }
1008
1009   // TODO maybe a disconnect happens here
1010   
1011   return GNUNET_OK;
1012 }
1013
1014
1015 /**
1016  * Callback called when a Sampler is updated.
1017  */
1018   void
1019 delete_cb (void *cls, struct GNUNET_PeerIdentity *id, struct GNUNET_HashCode hash)
1020 {
1021   size_t s;
1022
1023   //s = SAMPLER_count_id(samplers, id); // TODO
1024   s = SAMPLER_count_id(sampler_list, id);
1025   if ( 1 >= s ) {
1026     // TODO cleanup peer
1027     GNUNET_CONTAINER_multipeermap_remove_all( peer_map, id);
1028   }
1029 }
1030
1031
1032 /**
1033  * Send out PUSHes and PULLs.
1034  *
1035  * This is executed regylary.
1036  */
1037 static void
1038 do_round(void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1039 {
1040   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to execute next round\n");
1041
1042   uint64_t i;
1043   struct Sampler *s;
1044   struct GNUNET_CONTAINER_SList_Iterator *iter;
1045   //unsigned int *n_arr;
1046   struct GNUNET_RPS_P2P_PushMessage        *push_msg;
1047   struct GNUNET_RPS_P2P_PullRequestMessage *pull_msg; // FIXME Send empty message
1048   struct GNUNET_MQ_Envelope *ev;
1049   struct GNUNET_PeerIdentity *peer;
1050
1051   // TODO print lists, ...
1052   // TODO cleanup peer_map
1053
1054   iter = GNUNET_new(struct GNUNET_CONTAINER_SList_Iterator);
1055
1056
1057   /* If the NSE has changed adapt the lists accordingly */
1058   // TODO check nse == 0!
1059   LOG(GNUNET_ERROR_TYPE_DEBUG, "Checking size estimate.\n");
1060   SAMPLER_samplers_grow(samplers, est_size);
1061   //if ( sampler_list_size < est_size ) {
1062   //  LOG(GNUNET_ERROR_TYPE_DEBUG, "Growing size.\n");
1063   //  /* Grow the lists. */
1064   //  for ( i = 0 ; i < est_size - sampler_list_size ; i++ ) {
1065   //    s = SAMPLER_init();
1066   //    GNUNET_CONTAINER_slist_add_end(sampler_list,
1067   //                                   GNUNET_CONTAINER_SLIST_DISPOSITION_TRANSIENT, // DEPRECATED
1068   //                                   s,
1069   //                                   sizeof(struct Sampler));
1070
1071   //    // TODO add peers to gossiped ones?
1072   //  }
1073   //} else if ( sampler_list_size > est_size ) {
1074   //  LOG(GNUNET_ERROR_TYPE_DEBUG, "Shrinking size.\n");
1075   //  /* Shrink the lists. */
1076   //  for ( i = 0 ; i < sampler_list_size - est_size ; i++ ) {
1077   //    *iter = GNUNET_CONTAINER_slist_begin(sampler_list);
1078   //    GNUNET_CONTAINER_slist_erase(iter);
1079   //    GNUNET_CONTAINER_slist_iter_destroy(iter); // Maybe unneeded but I don't know whether _erase() also deletes the iter
1080   //  }
1081   //}
1082
1083   GNUNET_array_grow(gossip_list, gossip_list_size, est_size); // FIXME Do conversion correct or change type
1084
1085   gossip_list_size = sampler_list_size = est_size;
1086
1087  
1088
1089
1090   /* Would it make sense to have one shuffeled gossip list and then
1091    * to send PUSHes to first alpha peers, PULL requests to next beta peers and
1092    * use the rest to update sampler? */
1093
1094   /* Send PUSHes */
1095   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) gossip_list_size);
1096   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to send pushes to %f (%f * %" PRIu64 ") peers.\n",
1097       alpha * gossip_list_size, alpha, gossip_list_size);
1098   for ( i = 0 ; i < alpha * gossip_list_size ; i++ ) { // TODO compute length
1099     peer = get_rand_gossip_peer();
1100     // TODO check NULL == peer
1101     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sending PUSH to peer %s of gossiped list.\n", GNUNET_i2s(peer));
1102
1103     ev = GNUNET_MQ_msg(push_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PUSH);
1104     //ev = GNUNET_MQ_msg_extra();
1105     /* TODO Compute proof of work here
1106     push_msg; */
1107     push_msg->placeholder = 0;
1108     GNUNET_MQ_send( get_mq(peer_map, peer), ev );
1109
1110     // TODO modify in_flags of respective peer?
1111   }
1112
1113
1114   /* Send PULL requests */
1115   // TODO
1116   //n_arr = GNUNET_CRYPTO_random_permute(GNUNET_CRYPTO_QUALITY_STRONG, (unsigned int) sampler_list_size);
1117   LOG(GNUNET_ERROR_TYPE_DEBUG, "Going to send pulls to %f (%f * %" PRIu64 ") peers.\n",
1118       beta * gossip_list_size, beta, gossip_list_size);
1119   for ( i = 0 ; i < beta * gossip_list_size ; i++ ){ // TODO compute length
1120     peer = get_rand_gossip_peer();
1121     // TODO check NULL == peer
1122     LOG(GNUNET_ERROR_TYPE_DEBUG, "Sending PULL request to peer %s of gossiped list.\n", GNUNET_i2s(peer));
1123
1124     ev = GNUNET_MQ_msg(pull_msg, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST);
1125     //ev = GNUNET_MQ_msg_extra();
1126     pull_msg->placeholder = 0;
1127     GNUNET_MQ_send( get_mq(peer_map, peer), ev );
1128     // TODO modify in_flags of respective peer?
1129   }
1130
1131
1132
1133
1134   /* Update gossip list */
1135   uint64_t tmp_index;
1136
1137   if ( GNUNET_CONTAINER_slist_count(push_list) <= alpha * gossip_list_size &&
1138        GNUNET_CONTAINER_slist_count(push_list) != 0 &&
1139        GNUNET_CONTAINER_slist_count(pull_list) != 0 ) {
1140     LOG(GNUNET_ERROR_TYPE_DEBUG, "Update of the gossip list. ()\n");
1141
1142     for ( i = 0 ; i < alpha * gossip_list_size ; i++ ) { // TODO use SAMPLER_get_n_rand_peers
1143       /* Update gossip list with peers received through PUSHes */
1144       gossip_list[i] = *SAMPLER_get_rand_peer(push_list);
1145       // TODO change the in_flags accordingly
1146     }
1147
1148     for ( i = 0 ; i < beta * gossip_list_size ; i++ ) {
1149       /* Update gossip list with peers received through PULLs */
1150       tmp_index = i + round(alpha * gossip_list_size);
1151       gossip_list[tmp_index] = *SAMPLER_get_rand_peer(pull_list);
1152       // TODO change the in_flags accordingly
1153     }
1154
1155     for ( i = 0 ; i < (1 - (alpha + beta)) * gossip_list_size ; i++ ) {
1156       /* Update gossip list with peers from history */
1157       tmp_index = i + round((alpha + beta) * gossip_list_size);
1158       gossip_list[tmp_index] = *SAMPLER_get_rand_peer(sampler_list);
1159       // TODO change the in_flags accordingly
1160     }
1161
1162   } else {
1163     LOG(GNUNET_ERROR_TYPE_DEBUG, "No update of the gossip list. ()\n");
1164   }
1165   // TODO independent of that also get some peers from CADET_get_peers()?
1166
1167
1168
1169   /* Update samplers */
1170   size_t size;
1171
1172   if ( 0 < GNUNET_CONTAINER_slist_count(push_list) ) {
1173     LOG(GNUNET_ERROR_TYPE_DEBUG, "Update of the sampler list from pushes.\n");
1174
1175     *iter = GNUNET_CONTAINER_slist_begin(push_list);
1176     size = sizeof(struct GNUNET_PeerIdentity);
1177
1178     while ( GNUNET_NO != GNUNET_CONTAINER_slist_next(iter) ) {
1179       peer = (struct GNUNET_PeerIdentity *) GNUNET_CONTAINER_slist_get(iter, &size);
1180       SAMPLER_update_list(sampler_list, peer, NULL, NULL);
1181       // TODO set in_flag
1182     }
1183     GNUNET_CONTAINER_slist_iter_destroy(iter);
1184
1185   } else {
1186     LOG(GNUNET_ERROR_TYPE_DEBUG, "No update of the sampler list - received no pushes.\n");
1187   }
1188
1189   if ( 0 < GNUNET_CONTAINER_slist_count(pull_list) ) {
1190     LOG(GNUNET_ERROR_TYPE_DEBUG, "Update of the sampler list - received no pushes.\n");
1191
1192     *iter = GNUNET_CONTAINER_slist_begin(pull_list);
1193
1194     while ( GNUNET_NO != GNUNET_CONTAINER_slist_next(iter) ) {
1195       peer = (struct GNUNET_PeerIdentity *) GNUNET_CONTAINER_slist_get(iter, &size);
1196       SAMPLER_update_list(sampler_list, peer, NULL, NULL);
1197       // TODO set in_flag
1198     }
1199     GNUNET_CONTAINER_slist_iter_destroy(iter);
1200   } else {
1201     LOG(GNUNET_ERROR_TYPE_DEBUG, "No update of the sampler list - received no pulls.\n");
1202   }
1203
1204
1205   GNUNET_free(iter);
1206
1207
1208   // TODO go over whole peer_map and do cleanups
1209   // delete unneeded peers, set in_flags, check channel/mq
1210
1211
1212
1213   /* Empty push/pull lists */
1214   if ( 0 != GNUNET_CONTAINER_slist_count(push_list) ) {
1215       GNUNET_CONTAINER_slist_clear(push_list);
1216   }
1217
1218   if ( 0 != GNUNET_CONTAINER_slist_count(push_list) ) {
1219     GNUNET_CONTAINER_slist_clear(push_list);
1220   }
1221
1222
1223   /* Schedule next round */
1224   // TODO
1225   do_round_task = GNUNET_SCHEDULER_add_delayed( round_interval, &do_round, NULL );
1226   LOG(GNUNET_ERROR_TYPE_DEBUG, "Finished round\n");
1227 }
1228
1229 static void
1230 rps_start (struct GNUNET_SERVER_Handle *server);
1231
1232 /**
1233  * This is called from GNUNET_CADET_get_peers().
1234  *
1235  * It is called on every peer(ID) that cadet somehow has contact with.
1236  * We use those to initialise the sampler.
1237  */
1238 void
1239 init_peer_cb (void *cls,
1240               const struct GNUNET_PeerIdentity *peer,
1241               int tunnel, // "Do we have a tunnel towards this peer?"
1242               unsigned int n_paths, // "Number of known paths towards this peer"
1243               unsigned int best_path) // "How long is the best path?
1244                                       // (0 = unknown, 1 = ourselves, 2 = neighbor)"
1245 {
1246   // FIXME use the magic 0000 PeerID
1247   if ( NULL != peer ) {
1248     LOG(GNUNET_ERROR_TYPE_DEBUG, "Got peer %s (at %p) from CADET\n", GNUNET_i2s(peer), peer);
1249     SAMPLER_update_list(sampler_list, peer, NULL, NULL);
1250     if ( GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains( peer_map, peer ) ) {
1251     } else {
1252       struct peer_context *ctx;
1253
1254       ctx = GNUNET_malloc(sizeof(struct peer_context));
1255       ctx->in_flags = 0;
1256       ctx->mq = NULL;
1257       ctx->to_channel = NULL;
1258       ctx->from_channel = NULL;
1259       GNUNET_CONTAINER_multipeermap_put( peer_map, peer, ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1260     }
1261
1262     uint64_t i;
1263     i = GNUNET_CRYPTO_random_u64(GNUNET_CRYPTO_QUALITY_STRONG, gossip_list_size);
1264     gossip_list[i] = *peer;
1265     // TODO send push/pull to each of those peers?
1266   } else {
1267     rps_start( (struct GNUNET_SERVER_Handle *) cls);
1268   }
1269 }
1270
1271
1272
1273
1274 /**
1275  * Task run during shutdown.
1276  *
1277  * @param cls unused
1278  * @param tc unused
1279  */
1280 static void
1281 shutdown_task (void *cls,
1282                const struct GNUNET_SCHEDULER_TaskContext *tc)
1283 {
1284   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS is going down\n");
1285
1286   if ( GNUNET_SCHEDULER_NO_TASK != do_round_task )
1287   {
1288     GNUNET_SCHEDULER_cancel (do_round_task);
1289     do_round_task = GNUNET_SCHEDULER_NO_TASK;
1290   }
1291
1292   GNUNET_NSE_disconnect(nse);
1293   GNUNET_CADET_disconnect(cadet_handle);
1294   GNUNET_free(own_identity);
1295   //GNUNET_free(round_interval);
1296   //GNUNET_free(est_size);
1297   //GNUNET_free(gossip_list_size);
1298   //GNUNET_free(sampler_list_size);
1299   GNUNET_free(gossip_list);
1300   // TODO for i in sampler_list free sampler
1301   // TODO destroy sampler_list
1302   // TODO destroy push/pull_list
1303   // TODO delete global data
1304 }
1305
1306
1307 /**
1308  * A client disconnected.  Remove all of its data structure entries.
1309  *
1310  * @param cls closure, NULL
1311  * @param client identification of the client
1312  */
1313 static void
1314 handle_client_disconnect (void *cls,
1315                           struct GNUNET_SERVER_Client * client)
1316 {
1317   // TODO reinitialise that sampler
1318 }
1319
1320 /**
1321  * Handle the channel a peer opens to us.
1322  *
1323  * @param cls The closure
1324  * @param channel The channel the peer wants to establish
1325  * @param initiator The peer's peer ID
1326  * @param port The port the channel is being established over
1327  * @param options Further options
1328  */
1329   static void *
1330 handle_inbound_channel (void *cls,
1331                         struct GNUNET_CADET_Channel *channel,
1332                         const struct GNUNET_PeerIdentity *initiator,
1333                         uint32_t port,
1334                         enum GNUNET_CADET_ChannelOption options)
1335 {
1336   LOG(GNUNET_ERROR_TYPE_DEBUG, "New channel was established to us.\n");
1337
1338   GNUNET_assert( NULL != channel );
1339
1340   // TODO we might even not store the from_channel
1341
1342   if ( GNUNET_CONTAINER_multipeermap_contains( peer_map, initiator ) ) {
1343     ((struct peer_context *) GNUNET_CONTAINER_multipeermap_get( peer_map, initiator ))->from_channel = channel;
1344     // FIXME there might already be an established channel
1345   } else {
1346     struct peer_context *ctx;
1347
1348     ctx = GNUNET_malloc( sizeof(struct peer_context));
1349     ctx->in_flags = in_other_gossip_list;
1350     ctx->mq = NULL; // TODO create mq?
1351     ctx->from_channel = channel;
1352
1353     GNUNET_CONTAINER_multipeermap_put( peer_map, initiator, ctx, GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST);
1354   }
1355   return NULL; // TODO
1356 }
1357
1358 /**
1359  * This is called when a remote peer destroys a channel.
1360  *
1361  * @param cls The closure
1362  * @param channel The channel being closed
1363  * @param channel_ctx The context associated with this channel
1364  */
1365 static void
1366 cleanup_channel(void *cls,
1367                 const struct GNUNET_CADET_Channel *channel,
1368                 void *channel_ctx)
1369 {
1370   LOG(GNUNET_ERROR_TYPE_DEBUG, "Channel was destroyed by remote peer.\n");
1371 }
1372
1373 /**
1374  * Actually start the service.
1375  */
1376 static void
1377 rps_start (struct GNUNET_SERVER_Handle *server)
1378 {
1379   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1380     {&handle_cs_request, NULL, GNUNET_MESSAGE_TYPE_RPS_CS_REQUEST, 0},
1381     {NULL, NULL, 0, 0}
1382   };
1383
1384   GNUNET_SERVER_add_handlers (server, handlers);
1385   GNUNET_SERVER_disconnect_notify (server,
1386                                    &handle_client_disconnect,
1387                                    NULL);
1388   LOG(GNUNET_ERROR_TYPE_DEBUG, "Ready to receive requests from clients\n");
1389
1390
1391
1392   do_round_task = GNUNET_SCHEDULER_add_delayed( round_interval, &do_round, NULL);
1393   LOG(GNUNET_ERROR_TYPE_DEBUG, "Scheduled first round\n");
1394
1395   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1396                                 &shutdown_task,
1397                                 NULL);
1398 }
1399
1400
1401
1402 /**
1403  * Process statistics requests.
1404  *
1405  * @param cls closure
1406  * @param server the initialized server
1407  * @param c configuration to use
1408  */
1409 static void
1410 run (void *cls,
1411      struct GNUNET_SERVER_Handle *server,
1412      const struct GNUNET_CONFIGURATION_Handle *c)
1413 {
1414   // TODO check what this does -- copied from gnunet-boss
1415   // - seems to work as expected
1416   GNUNET_log_setup("rps", GNUNET_error_type_to_string(GNUNET_ERROR_TYPE_DEBUG), NULL);
1417
1418   LOG(GNUNET_ERROR_TYPE_DEBUG, "RPS started\n");
1419
1420   uint32_t i;
1421
1422   cfg = c;
1423
1424
1425   own_identity = GNUNET_new(struct GNUNET_PeerIdentity);
1426
1427   GNUNET_CRYPTO_get_peer_identity(cfg, own_identity); // TODO check return value
1428
1429   LOG(GNUNET_ERROR_TYPE_DEBUG, "Own identity is %s (at %p).\n", GNUNET_i2s(own_identity), own_identity);
1430
1431
1432
1433   /* Get time interval from the configuration */
1434   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_time (cfg, "RPS",
1435                                                         "ROUNDINTERVAL",
1436                                                         &round_interval))
1437   {
1438     LOG(GNUNET_ERROR_TYPE_DEBUG, "Failed to read ROUNDINTERVAL from config\n");
1439     GNUNET_SCHEDULER_shutdown();
1440     return;
1441   }
1442
1443   /* Get initial size of sampler/gossip list from the configuration */
1444   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, "RPS",
1445                                                          "INITSIZE",
1446                                                          (long long unsigned int *) &est_size))
1447   {
1448     LOG(GNUNET_ERROR_TYPE_DEBUG, "Failed to read INITSIZE from config\n");
1449     GNUNET_SCHEDULER_shutdown();
1450     return;
1451   }
1452   LOG(GNUNET_ERROR_TYPE_DEBUG, "INITSIZE is %" PRIu64 "\n", est_size);
1453
1454   gossip_list_size = sampler_list_size = est_size; // TODO rename est_size
1455
1456
1457   gossip_list = NULL;
1458
1459   static unsigned int tmp = 0;
1460
1461   GNUNET_array_grow(gossip_list, tmp, gossip_list_size);
1462
1463
1464
1465   /* connect to NSE */
1466   nse = GNUNET_NSE_connect(cfg, nse_callback, NULL);
1467   // TODO check whether that was successful
1468   // TODO disconnect on shutdown
1469   LOG(GNUNET_ERROR_TYPE_DEBUG, "Connected to NSE\n");
1470
1471
1472   alpha = 0.45;
1473   beta  = 0.45;
1474   // TODO initialise thresholds - ?
1475
1476   ///* Get alpha from the configuration */
1477   //if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1478   //                                                       "ALPHA",
1479   //                                                       &alpha))
1480   //{
1481   //  LOG(GNUNET_ERROR_TYPE_DEBUG, "No ALPHA specified in the config\n");
1482   //}
1483   //LOG(GNUNET_ERROR_TYPE_DEBUG, "ALPHA is %f\n", alpha);
1484  
1485   ///* Get beta from the configuration */
1486   //if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_float (cfg, "RPS",
1487   //                                                       "BETA",
1488   //                                                       &beta))
1489   //{
1490   //  LOG(GNUNET_ERROR_TYPE_DEBUG, "No BETA specified in the config\n");
1491   //}
1492   //LOG(GNUNET_ERROR_TYPE_DEBUG, "BETA is %f\n", beta);
1493
1494
1495
1496
1497   peer_map = GNUNET_CONTAINER_multipeermap_create(est_size, GNUNET_NO);
1498
1499
1500   /* Initialise sampler and gossip list */
1501   struct Sampler *s;
1502
1503   //sampler_list = GNUNET_CONTAINER_slist_create();
1504   samplers = SAMPLER_samplers_init(est_size);
1505
1506   //if ( gossip_list_size == sampler_list_size ) {
1507   //  for ( i = 0 ; i < sampler_list_size ; i++ ) {
1508   //    /* Init sampler list */
1509   //    s = SAMPLER_init();
1510   //    GNUNET_CONTAINER_slist_add(sampler_list,
1511   //                               GNUNET_CONTAINER_SLIST_DISPOSITION_DYNAMIC, // TODO DEPRECATED
1512   //                               s,
1513   //                               sizeof(struct Sampler));
1514   //    /* Init gossip list */
1515   //      // TODO init gossip list
1516   //      // What do we need to do here?
1517   //  }
1518   //} else {
1519   //  for ( i = 0 ; i < gossip_list_size ; i++ ) {
1520   //    // TODO init gossip list
1521   //  }
1522   //  for ( i = 0 ; i < sampler_list_size ; i++ ) {
1523   //    // TODO init RPF func
1524   //    // TODO init Sample list
1525   //    // TODO init Sampled list
1526   //  }
1527   //}
1528   //uint64_t tmp_s = (uint64_t) GNUNET_CONTAINER_slist_count(sampler_list);
1529   //LOG(GNUNET_ERROR_TYPE_DEBUG, "Initialised sampler list %" PRIu64 "\n", tmp_s);
1530
1531
1532
1533   push_list = GNUNET_CONTAINER_slist_create();
1534   pull_list = GNUNET_CONTAINER_slist_create();
1535
1536
1537
1538   static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1539     {&handle_peer_push        , GNUNET_MESSAGE_TYPE_RPS_PP_PUSH        , 0},
1540     {&handle_peer_pull_request, GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REQUEST, 0},
1541     {&handle_peer_pull_reply  , GNUNET_MESSAGE_TYPE_RPS_PP_PULL_REPLY  , 0},
1542     {NULL, 0, 0}
1543   };
1544
1545   const uint32_t ports[] = {GNUNET_RPS_CADET_PORT, 0}; // _PORT specified in src/rps/rps.h
1546   cadet_handle = GNUNET_CADET_connect(cfg,
1547                                     cls,
1548                                     &handle_inbound_channel,
1549                                     &cleanup_channel,
1550                                     cadet_handlers,
1551                                     ports);
1552   LOG(GNUNET_ERROR_TYPE_DEBUG, "Connected to CADET\n");
1553
1554
1555   LOG(GNUNET_ERROR_TYPE_DEBUG, "Requesting peers from CADET\n");
1556   GNUNET_CADET_get_peers(cadet_handle, &init_peer_cb, server);
1557   // FIXME use magic 0000 PeerID to _start_ the service
1558
1559   // TODO send push/pull to each of those peers?
1560
1561
1562
1563 }
1564
1565
1566 /**
1567  * The main function for the rps service.
1568  *
1569  * @param argc number of arguments from the command line
1570  * @param argv command line arguments
1571  * @return 0 ok, 1 on error
1572  */
1573 int
1574 main (int argc, char *const *argv)
1575 {
1576   return (GNUNET_OK ==
1577           GNUNET_SERVICE_run (argc,
1578                               argv,
1579                               "rps",
1580                               GNUNET_SERVICE_OPTION_NONE,
1581                               &run, NULL)) ? 0 : 1;
1582 }
1583
1584 /* end of gnunet-service-rps.c */