simpler alternative to the West algorithm to convince ourselves that we can still...
[oweals/gnunet.git] / src / nse / gnunet-service-nse.c
1 /*
2   This file is part of GNUnet.
3   (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
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 nse/gnunet-service-nse.c
23  * @brief network size estimation service
24  * @author Nathan Evans
25  * @author Christian Grothoff
26  *
27  * The purpose of this service is to estimate the size of the network.
28  * Given a specified interval, each peer hashes the most recent
29  * timestamp which is evenly divisible by that interval.  This hash is
30  * compared in distance to the peer identity to choose an offset.  The
31  * closer the peer identity to the hashed timestamp, the earlier the
32  * peer sends out a "nearest peer" message.  The closest peer's
33  * message should thus be received before any others, which stops
34  * those peer from sending their messages at a later duration.  So
35  * every peer should receive the same nearest peer message, and from
36  * this can calculate the expected number of peers in the network.
37  */
38 #include "platform.h"
39 #include <math.h>
40 #include "gnunet_util_lib.h"
41 #include "gnunet_constants.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_statistics_service.h"
45 #include "gnunet_core_service.h"
46 #include "gnunet_nse_service.h"
47 #include "nse.h"
48
49 /**
50  * Should messages be delayed randomly?  This option should be set to
51  * GNUNET_NO only for experiments, not in production.  It should also
52  * be removed once the initial experiments have been completed.
53  */
54 #define USE_RANDOM_DELAYS GNUNET_YES
55
56 /**
57  * Should we generate a histogram with the time stamps of when we received
58  * NSE messages to disk? (for performance evaluation only, not useful in
59  * production).  The associated code should also probably be removed
60  * once we're done with experiments.
61  */
62 #define ENABLE_HISTOGRAM GNUNET_NO
63
64 /**
65  * Over how many values do we calculate the weighted average?
66  */
67 #define HISTORY_SIZE 8
68
69 /**
70  * Size of the queue to core.
71  */
72 #define CORE_QUEUE_SIZE 2
73
74 /**
75  * Message priority to use.
76  */
77 #define NSE_PRIORITY 5
78
79 #if FREEBSD
80 #define log2(a) (log(a)/log(2))
81 #endif
82
83 /**
84  * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
85  */
86 static unsigned long long nse_work_required;
87
88 /**
89  * Interval for sending network size estimation flood requests.
90  */
91 static struct GNUNET_TIME_Relative gnunet_nse_interval;
92
93 /**
94  * Interval between proof find runs.
95  */
96 static struct GNUNET_TIME_Relative proof_find_delay;
97
98 #if ENABLE_HISTOGRAM
99 /**
100  * Handle for writing when we received messages to disk.
101  */
102 static struct GNUNET_BIO_WriteHandle *wh;
103 #endif
104
105
106 /**
107  * Per-peer information.
108  */
109 struct NSEPeerEntry
110 {
111
112   /**
113    * Pending message for this peer.
114    */
115   struct GNUNET_MessageHeader *pending_message;
116
117   /**
118    * Core handle for sending messages to this peer.
119    */
120   struct GNUNET_CORE_TransmitHandle *th;
121
122   /**
123    * What is the identity of the peer?
124    */
125   struct GNUNET_PeerIdentity id;
126
127   /**
128    * Task scheduled to send message to this peer.
129    */
130   GNUNET_SCHEDULER_TaskIdentifier transmit_task;
131
132   /**
133    * Did we receive or send a message about the previous round
134    * to this peer yet?   GNUNET_YES if the previous round has
135    * been taken care of.
136    */
137   int previous_round;
138 };
139
140
141 /**
142  * Network size estimate reply; sent when "this"
143  * peer's timer has run out before receiving a
144  * valid reply from another peer.
145  */
146 struct GNUNET_NSE_FloodMessage
147 {
148   /**
149    * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
150    */
151   struct GNUNET_MessageHeader header;
152
153   /**
154    * Number of hops this message has taken so far.
155    */
156   uint32_t hop_count GNUNET_PACKED;
157
158   /**
159    * Purpose.
160    */
161   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
162
163   /**
164    * The current timestamp value (which all
165    * peers should agree on).
166    */
167   struct GNUNET_TIME_AbsoluteNBO timestamp;
168
169   /**
170    * Number of matching bits between the hash
171    * of timestamp and the initiator's public
172    * key.
173    */
174   uint32_t matching_bits GNUNET_PACKED;
175
176   /**
177    * Public key of the originator.
178    */
179   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
180
181   /**
182    * Proof of work, causing leading zeros when hashed with pkey.
183    */
184   uint64_t proof_of_work GNUNET_PACKED;
185
186   /**
187    * Signature (over range specified in purpose).
188    */
189   struct GNUNET_CRYPTO_RsaSignature signature;
190 };
191
192
193 /**
194  * Handle to our current configuration.
195  */
196 static const struct GNUNET_CONFIGURATION_Handle *cfg;
197
198 /**
199  * Handle to the statistics service.
200  */
201 static struct GNUNET_STATISTICS_Handle *stats;
202
203 /**
204  * Handle to the core service.
205  */
206 static struct GNUNET_CORE_Handle *coreAPI;
207
208 /**
209  * Map of all connected peers.
210  */
211 static struct GNUNET_CONTAINER_MultiHashMap *peers;
212
213 /**
214  * The current network size estimate.  Number of bits matching on
215  * average thus far.
216  */
217 static double current_size_estimate;
218
219 /**
220  * The standard deviation of the last HISTORY_SIZE network
221  * size estimates.
222  */
223 static double current_std_dev = NAN;
224
225 /**
226  * Current hop counter estimate (estimate for network diameter).
227  */
228 static uint32_t hop_count_max;
229
230 /**
231  * Message for the next round, if we got any.
232  */
233 static struct GNUNET_NSE_FloodMessage next_message;
234
235 /**
236  * Array of recent size estimate messages.
237  */
238 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
239
240 /**
241  * Index of most recent estimate.
242  */
243 static unsigned int estimate_index;
244
245 /**
246  * Number of valid entries in the history.
247  */
248 static unsigned int estimate_count;
249
250 /**
251  * Task scheduled to update our flood message for the next round.
252  */
253 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
254
255 /**
256  * Task scheduled to compute our proof.
257  */
258 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
259
260 /**
261  * Notification context, simplifies client broadcasts.
262  */
263 static struct GNUNET_SERVER_NotificationContext *nc;
264
265 /**
266  * The next major time.
267  */
268 static struct GNUNET_TIME_Absolute next_timestamp;
269
270 /**
271  * The current major time.
272  */
273 static struct GNUNET_TIME_Absolute current_timestamp;
274
275 /**
276  * The public key of this peer.
277  */
278 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
279
280 /**
281  * The private key of this peer.
282  */
283 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
284
285 /**
286  * The peer identity of this peer.
287  */
288 static struct GNUNET_PeerIdentity my_identity;
289
290 /**
291  * Proof of work for this peer.
292  */
293 static uint64_t my_proof;
294
295
296 /**
297  * Initialize a message to clients with the current network
298  * size estimate.
299  *
300  * @param em message to fill in
301  */
302 static void
303 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
304 {
305   unsigned int i;
306   double mean;
307   double sum;
308   double std_dev;
309   double variance;
310   double val;
311   double nsize;
312
313   /* Weighted incremental algorithm for stddev according to West (1979) */
314 #if WEST
315   double sumweight;
316   double weight;
317   double q;
318   double r;
319   double temp;
320
321   mean = 0.0;
322   sum = 0.0;
323   sumweight = 0.0;
324   for (i = 0; i < estimate_count; i++)
325   {
326     val =
327         htonl (size_estimate_messages
328                [(estimate_index - i +
329                  HISTORY_SIZE) % HISTORY_SIZE].matching_bits);
330     weight = 1;                 /* was: estimate_count + 1 - i; */
331
332     temp = weight + sumweight;
333     q = val - mean;
334     r = q * weight / temp;
335     sum += sumweight * q * r;
336     mean += r;
337     sumweight = temp;
338   }
339   variance = sum / (sumweight - 1.0);
340 #else
341   /* trivial version for debugging */
342   double vsq;
343
344   /* non-weighted trivial version */
345   sum = 0.0;
346   vsq = 0.0;
347   for (i = 0; i < estimate_count; i++)
348   {
349     val = htonl (size_estimate_messages
350                  [(estimate_index - i +
351                    HISTORY_SIZE) % HISTORY_SIZE].matching_bits);
352     sum += val;
353     vsq += val * val;    
354   }  
355   mean = sum / estimate_count;
356   variance = vsq + mean * mean - 2 * mean * sum; // terrible for numerical stability...
357 #endif
358   GNUNET_assert (variance >= 0);
359   std_dev = sqrt (variance);
360   current_std_dev = std_dev;
361   current_size_estimate = mean;
362
363   em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage));
364   em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
365   em->reserved = htonl (0);
366   em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
367   em->size_estimate = mean - 0.332747;
368   nsize = log2 (GNUNET_CONTAINER_multihashmap_size (peers) + 1);
369   if (em->size_estimate < nsize)
370     em->size_estimate = nsize;
371   em->std_deviation = std_dev;
372   GNUNET_STATISTICS_set (stats, "# nodes in the network (estimate)",
373                          (uint64_t) pow (2, mean - 1.0 / 3.0), GNUNET_NO);
374 }
375
376
377 /**
378  * Handler for START message from client, triggers an
379  * immediate current network estimate notification.
380  * Also, we remember the client for updates upon future
381  * estimate measurements.
382  *
383  * @param cls unused
384  * @param client who sent the message
385  * @param message the message received
386  */
387 static void
388 handle_start_message (void *cls, struct GNUNET_SERVER_Client *client,
389                       const struct GNUNET_MessageHeader *message)
390 {
391   struct GNUNET_NSE_ClientMessage em;
392
393 #if DEBUG_NSE
394   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n");
395 #endif
396   GNUNET_SERVER_notification_context_add (nc, client);
397   setup_estimate_message (&em);
398   GNUNET_SERVER_notification_context_unicast (nc, client, &em.header,
399                                               GNUNET_YES);
400   GNUNET_SERVER_receive_done (client, GNUNET_OK);
401 }
402
403
404 /**
405  * How long should we delay a message to go the given number of
406  * matching bits?
407  *
408  * @param matching_bits number of matching bits to consider
409  */
410 static double
411 get_matching_bits_delay (uint32_t matching_bits)
412 {
413   /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */
414   // S is next_timestamp (ignored in return value)
415   // f is frequency (gnunet_nse_interval)
416   // x is matching_bits
417   // p' is current_size_estimate
418   return ((double) gnunet_nse_interval.rel_value / (double) 2.0) -
419       ((gnunet_nse_interval.rel_value / M_PI) *
420        atan (matching_bits - current_size_estimate));
421 }
422
423
424 /**
425  * What delay randomization should we apply for a given number of matching bits?
426  *
427  * @param matching_bits number of matching bits
428  * @return random delay to apply
429  */
430 static struct GNUNET_TIME_Relative
431 get_delay_randomization (uint32_t matching_bits)
432 {
433 #if USE_RANDOM_DELAYS
434   struct GNUNET_TIME_Relative ret;
435
436   if (matching_bits == 0)
437     return GNUNET_TIME_UNIT_ZERO;
438   ret.rel_value =
439       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
440                                 (uint32_t) (get_matching_bits_delay
441                                             (matching_bits -
442                                              1) / (double) (hop_count_max +
443                                                             1)));
444   return ret;
445 #else
446   return GNUNET_TIME_UNIT_ZERO;
447 #endif
448 }
449
450
451 /**
452  * Get the number of matching bits that the given timestamp has to the given peer ID.
453  *
454  * @param timestamp time to generate key
455  * @param id peer identity to compare with
456  * @return number of matching bits
457  */
458 static uint32_t
459 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
460                    const struct GNUNET_PeerIdentity *id)
461 {
462   GNUNET_HashCode timestamp_hash;
463
464   GNUNET_CRYPTO_hash (&timestamp.abs_value, sizeof (timestamp.abs_value),
465                       &timestamp_hash);
466   return GNUNET_CRYPTO_hash_matching_bits (&timestamp_hash, &id->hashPubKey);
467 }
468
469
470 /**
471  * Get the transmission delay that should be applied for a
472  * particular round.
473  *
474  * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
475  *                      0 for the current round (based on our proximity to time key)
476  * @return delay that should be applied
477  */
478 static struct GNUNET_TIME_Relative
479 get_transmit_delay (int round_offset)
480 {
481   struct GNUNET_TIME_Relative ret;
482   struct GNUNET_TIME_Absolute tgt;
483   double dist_delay;
484   uint32_t matching_bits;
485
486   switch (round_offset)
487   {
488   case -1:
489     /* previous round is randomized between 0 and 50 ms */
490 #if USE_RANDOM_DELAYS
491     ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
492 #else
493     ret = GNUNET_TIME_UNIT_ZERO;
494 #endif
495 #if DEBUG_NSE
496     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
497                 "Transmitting previous round behind schedule in %llu ms\n",
498                 (unsigned long long) ret.rel_value);
499 #endif
500     return ret;
501   case 0:
502     /* current round is based on best-known matching_bits */
503     matching_bits =
504         ntohl (size_estimate_messages[estimate_index].matching_bits);
505     dist_delay = get_matching_bits_delay (matching_bits);
506     dist_delay += get_delay_randomization (matching_bits).rel_value;
507     ret.rel_value = (uint64_t) dist_delay;
508 #if DEBUG_NSE
509     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
510                 "For round %llu, delay for %u matching bits is %llu ms\n",
511                 (unsigned long long) current_timestamp.abs_value,
512                 (unsigned int) matching_bits,
513                 (unsigned long long) ret.rel_value);
514 #endif
515     /* now consider round start time and add delay to it */
516     tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
517     return GNUNET_TIME_absolute_get_remaining (tgt);
518   }
519   GNUNET_break (0);
520   return GNUNET_TIME_UNIT_FOREVER_REL;
521 }
522
523
524 /**
525  * Task that triggers a NSE P2P transmission.
526  *
527  * @param cls the 'struct NSEPeerEntry'
528  * @param tc scheduler context
529  */
530 static void
531 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
532
533
534 /**
535  * Called when core is ready to send a message we asked for
536  * out to the destination.
537  *
538  * @param cls closure (NULL)
539  * @param size number of bytes available in buf
540  * @param buf where the callee should write the message
541  * @return number of bytes written to buf
542  */
543 static size_t
544 transmit_ready (void *cls, size_t size, void *buf)
545 {
546   struct NSEPeerEntry *peer_entry = cls;
547   unsigned int idx;
548
549   peer_entry->th = NULL;
550   if (buf == NULL)
551   {
552     /* client disconnected */
553     return 0;
554   }
555   GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
556   idx = estimate_index;
557   if (peer_entry->previous_round == GNUNET_NO)
558   {
559     idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
560     peer_entry->previous_round = GNUNET_YES;
561     peer_entry->transmit_task =
562         GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), &transmit_task,
563                                       peer_entry);
564   }
565   if ((ntohl (size_estimate_messages[idx].hop_count) == 0) &&
566       (GNUNET_SCHEDULER_NO_TASK != proof_task))
567   {
568     GNUNET_STATISTICS_update (stats,
569                               "# flood messages not generated (no proof yet)",
570                               1, GNUNET_NO);
571     return 0;
572   }
573 #if DEBUG_NSE
574   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
575               "In round %llu, sending to `%s' estimate with %u bits\n",
576               (unsigned long long)
577               GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].
578                                          timestamp).abs_value,
579               GNUNET_i2s (&peer_entry->id),
580               (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
581 #endif
582   if (ntohl (size_estimate_messages[idx].hop_count) == 0)
583     GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO);
584   GNUNET_STATISTICS_update (stats, "# flood messages transmitted", 1,
585                             GNUNET_NO);
586   memcpy (buf, &size_estimate_messages[idx],
587           sizeof (struct GNUNET_NSE_FloodMessage));
588   GNUNET_STATISTICS_update (stats, "# flood messages sent", 1, GNUNET_NO);
589   return sizeof (struct GNUNET_NSE_FloodMessage);
590 }
591
592
593 /**
594  * Task that triggers a NSE P2P transmission.
595  *
596  * @param cls the 'struct NSEPeerEntry'
597  * @param tc scheduler context
598  */
599 static void
600 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
601 {
602   struct NSEPeerEntry *peer_entry = cls;
603
604   peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
605   GNUNET_assert (NULL == peer_entry->th);
606   peer_entry->th =
607       GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO, NSE_PRIORITY,
608                                          GNUNET_TIME_UNIT_FOREVER_REL,
609                                          &peer_entry->id,
610                                          sizeof (struct
611                                                  GNUNET_NSE_FloodMessage),
612                                          &transmit_ready, peer_entry);
613 }
614
615
616 /**
617  * We've sent on our flood message or one that we received which was
618  * validated and closer than ours.  Update the global list of recent
619  * messages and the average.  Also re-broadcast the message to any
620  * clients.
621  */
622 static void
623 update_network_size_estimate ()
624 {
625   struct GNUNET_NSE_ClientMessage em;
626
627   setup_estimate_message (&em);
628   GNUNET_SERVER_notification_context_broadcast (nc, &em.header, GNUNET_YES);
629 }
630
631
632 /**
633  * Setup a flood message in our history array at the given
634  * slot offset for the given timestamp.
635  *
636  * @param slot index to use
637  * @param ts timestamp to use
638  */
639 static void
640 setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts)
641 {
642   struct GNUNET_NSE_FloodMessage *fm;
643   uint32_t matching_bits;
644
645   matching_bits = get_matching_bits (ts, &my_identity);
646   fm = &size_estimate_messages[slot];
647   fm->header.size = htons (sizeof (struct GNUNET_NSE_FloodMessage));
648   fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
649   fm->hop_count = htonl (0);
650   fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
651   fm->purpose.size =
652       htonl (sizeof (struct GNUNET_NSE_FloodMessage) -
653              sizeof (struct GNUNET_MessageHeader) - sizeof (uint32_t) -
654              sizeof (struct GNUNET_CRYPTO_RsaSignature));
655   fm->matching_bits = htonl (matching_bits);
656   fm->timestamp = GNUNET_TIME_absolute_hton (ts);
657   fm->pkey = my_public_key;
658   fm->proof_of_work = my_proof;
659   GNUNET_assert (GNUNET_OK ==
660                  GNUNET_CRYPTO_rsa_sign (my_private_key, &fm->purpose,
661                                          &fm->signature));
662 }
663
664
665 /**
666  * Schedule transmission for the given peer for the current round based
667  * on what we know about the desired delay.
668  *
669  * @param cls unused
670  * @param key hash of peer identity
671  * @param value the 'struct NSEPeerEntry'
672  * @return GNUNET_OK (continue to iterate)
673  */
674 static int
675 schedule_current_round (void *cls, const GNUNET_HashCode * key, void *value)
676 {
677   struct NSEPeerEntry *peer_entry = value;
678   struct GNUNET_TIME_Relative delay;
679
680   if (peer_entry->th != NULL)
681   {
682     peer_entry->previous_round = GNUNET_NO;
683     return GNUNET_OK;
684   }
685   if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
686   {
687     GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
688     peer_entry->previous_round = GNUNET_NO;
689   }
690   delay =
691       get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
692   peer_entry->transmit_task =
693       GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
694   return GNUNET_OK;
695 }
696
697
698 /**
699  * Update our flood message to be sent (and our timestamps).
700  *
701  * @param cls unused
702  * @param tc context for this message
703  */
704 static void
705 update_flood_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
706 {
707   struct GNUNET_TIME_Relative offset;
708   unsigned int i;
709
710   flood_task = GNUNET_SCHEDULER_NO_TASK;
711   offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
712   if (0 != offset.rel_value)
713   {
714     /* somehow run early, delay more */
715     flood_task =
716         GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL);
717     return;
718   }
719   current_timestamp = next_timestamp;
720   next_timestamp =
721       GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
722   estimate_index = (estimate_index + 1) % HISTORY_SIZE;
723   if (estimate_count < HISTORY_SIZE)
724     estimate_count++;
725   if (next_timestamp.abs_value ==
726       GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
727   {
728     /* we received a message for this round way early, use it! */
729     size_estimate_messages[estimate_index] = next_message;
730     size_estimate_messages[estimate_index].hop_count =
731         htonl (1 + ntohl (next_message.hop_count));
732   }
733   else
734     setup_flood_message (estimate_index, current_timestamp);
735   next_message.matching_bits = htonl (0);       /* reset for 'next' round */
736   hop_count_max = 0;
737   for (i = 0; i < HISTORY_SIZE; i++)
738     hop_count_max =
739         GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max);
740   GNUNET_CONTAINER_multihashmap_iterate (peers, &schedule_current_round, NULL);
741   flood_task =
742       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
743                                     (next_timestamp), &update_flood_message,
744                                     NULL);
745 }
746
747
748 /**
749  * Count the leading zeroes in hash.
750  *
751  * @param hash
752  * @return the number of leading zero bits.
753  */
754 static unsigned int
755 count_leading_zeroes (const GNUNET_HashCode * hash)
756 {
757   unsigned int hash_count;
758
759   hash_count = 0;
760   while ((0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)))
761     hash_count++;
762   return hash_count;
763 }
764
765
766 /**
767  * Check whether the given public key
768  * and integer are a valid proof of work.
769  *
770  * @param pkey the public key
771  * @param val the integer
772  *
773  * @return GNUNET_YES if valid, GNUNET_NO if not
774  */
775 static int
776 check_proof_of_work (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
777                      uint64_t val)
778 {
779   char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
780            sizeof (val)];
781   GNUNET_HashCode result;
782
783   memcpy (buf, &val, sizeof (val));
784   memcpy (&buf[sizeof (val)], pkey,
785           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
786   GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
787   return (count_leading_zeroes (&result) >=
788           nse_work_required) ? GNUNET_YES : GNUNET_NO;
789 }
790
791
792 /**
793  * Write our current proof to disk.
794  */
795 static void
796 write_proof ()
797 {
798   char *proof;
799
800   if (GNUNET_OK !=
801       GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
802     return;
803   if (sizeof (my_proof) !=
804       GNUNET_DISK_fn_write (proof, &my_proof, sizeof (my_proof),
805                             GNUNET_DISK_PERM_USER_READ |
806                             GNUNET_DISK_PERM_USER_WRITE))
807     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof);
808   GNUNET_free (proof);
809
810 }
811
812
813 /**
814  * Find our proof of work.
815  *
816  * @param cls closure (unused)
817  * @param tc task context
818  */
819 static void
820 find_proof (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
821 {
822 #define ROUND_SIZE 10
823   uint64_t counter;
824   char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
825            sizeof (uint64_t)];
826   GNUNET_HashCode result;
827   unsigned int i;
828
829   proof_task = GNUNET_SCHEDULER_NO_TASK;
830   memcpy (&buf[sizeof (uint64_t)], &my_public_key,
831           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
832   i = 0;
833   counter = my_proof;
834   while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
835   {
836     memcpy (buf, &counter, sizeof (uint64_t));
837     GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
838     if (nse_work_required <= count_leading_zeroes (&result))
839     {
840       my_proof = counter;
841 #if DEBUG_NSE
842       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Proof of work found: %llu!\n",
843                   (unsigned long long) GNUNET_ntohll (counter));
844 #endif
845       for (i = 0; i < HISTORY_SIZE; i++)
846         if (ntohl (size_estimate_messages[i].hop_count) == 0)
847         {
848           size_estimate_messages[i].proof_of_work = my_proof;
849           GNUNET_assert (GNUNET_OK ==
850                          GNUNET_CRYPTO_rsa_sign (my_private_key,
851                                                  &size_estimate_messages
852                                                  [i].purpose,
853                                                  &size_estimate_messages
854                                                  [i].signature));
855         }
856       write_proof ();
857       return;
858     }
859     counter++;
860     i++;
861   }
862   if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
863   {
864 #if DEBUG_NSE
865     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Testing proofs currently at %llu\n",
866                 (unsigned long long) counter);
867 #endif
868     /* remember progress every 100 rounds */
869     my_proof = counter;
870     write_proof ();
871   }
872   else
873   {
874     my_proof = counter;
875   }
876   proof_task =
877       GNUNET_SCHEDULER_add_delayed (proof_find_delay, &find_proof, NULL);
878 }
879
880
881 /**
882  * An incoming flood message has been received which claims
883  * to have more bits matching than any we know in this time
884  * period.  Verify the signature and/or proof of work.
885  *
886  * @param incoming_flood the message to verify
887  *
888  * @return GNUNET_YES if the message is verified
889  *         GNUNET_NO if the key/signature don't verify
890  */
891 static int
892 verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
893 {
894   if (GNUNET_YES !=
895       check_proof_of_work (&incoming_flood->pkey,
896                            incoming_flood->proof_of_work))
897   {
898     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Proof of work invalid: %llu!\n"),
899                 (unsigned long long)
900                 GNUNET_ntohll (incoming_flood->proof_of_work));
901     GNUNET_break_op (0);
902     return GNUNET_NO;
903   }
904   if (GNUNET_OK !=
905       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
906                                 &incoming_flood->purpose,
907                                 &incoming_flood->signature,
908                                 &incoming_flood->pkey))
909   {
910     GNUNET_break_op (0);
911     return GNUNET_NO;
912   }
913   return GNUNET_YES;
914 }
915
916
917 /**
918  * Update transmissions for the given peer for the current round based
919  * on updated proximity information.
920  *
921  * @param cls peer entry to exclude from updates
922  * @param key hash of peer identity
923  * @param value the 'struct NSEPeerEntry'
924  * @return GNUNET_OK (continue to iterate)
925  */
926 static int
927 update_flood_times (void *cls, const GNUNET_HashCode * key, void *value)
928 {
929   struct NSEPeerEntry *exclude = cls;
930   struct NSEPeerEntry *peer_entry = value;
931   struct GNUNET_TIME_Relative delay;
932
933   if (peer_entry->th != NULL)
934     return GNUNET_OK;           /* already active */
935   if (peer_entry == exclude)
936     return GNUNET_OK;           /* trigger of the update */
937   if (peer_entry->previous_round == GNUNET_NO)
938   {
939     /* still stuck in previous round, no point to update, check that
940      * we are active here though... */
941     GNUNET_break ((peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
942                   (peer_entry->th != NULL));
943     return GNUNET_OK;
944   }
945   if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
946   {
947     GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
948     peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
949   }
950   delay = get_transmit_delay (0);
951   peer_entry->transmit_task =
952       GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
953   return GNUNET_OK;
954 }
955
956
957 /**
958  * Core handler for size estimate flooding messages.
959  *
960  * @param cls closure unused
961  * @param message message
962  * @param peer peer identity this message is from (ignored)
963  * @param atsi performance data (ignored)
964  * @param atsi_count number of records in 'atsi'
965  */
966 static int
967 handle_p2p_size_estimate (void *cls, const struct GNUNET_PeerIdentity *peer,
968                           const struct GNUNET_MessageHeader *message,
969                           const struct GNUNET_ATS_Information *atsi,
970                           unsigned int atsi_count)
971 {
972   const struct GNUNET_NSE_FloodMessage *incoming_flood;
973   struct GNUNET_TIME_Absolute ts;
974   struct NSEPeerEntry *peer_entry;
975   uint32_t matching_bits;
976   unsigned int idx;
977
978 #if ENABLE_HISTOGRAM
979   if (NULL != wh)
980     GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
981 #endif
982   incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
983   GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
984   matching_bits = ntohl (incoming_flood->matching_bits);
985 #if DEBUG_NSE
986   {
987     char origin[5];
988     char pred[5];
989     struct GNUNET_PeerIdentity os;
990
991     GNUNET_CRYPTO_hash (&incoming_flood->pkey,
992                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
993                         &os.hashPubKey);
994     GNUNET_snprintf (origin, sizeof (origin), "%s", GNUNET_i2s (&os));
995     GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer));
996     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
997                 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
998                 (unsigned long long)
999                 GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1000                 origin, pred, GNUNET_i2s (&my_identity),
1001                 (unsigned int) matching_bits);
1002   }
1003 #endif
1004
1005   peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1006   if (NULL == peer_entry)
1007   {
1008     GNUNET_break (0);
1009     return GNUNET_OK;
1010   }
1011
1012   ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1013
1014   if (ts.abs_value == current_timestamp.abs_value)
1015     idx = estimate_index;
1016   else if (ts.abs_value ==
1017            current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1018     idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1019   else if (ts.abs_value ==
1020            next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1021   {
1022     if (matching_bits <= ntohl (next_message.matching_bits))
1023       return GNUNET_OK;         /* ignore, simply too early/late */
1024     if (GNUNET_YES != verify_message_crypto (incoming_flood))
1025     {
1026       GNUNET_break_op (0);
1027       return GNUNET_OK;
1028     }
1029     next_message = *incoming_flood;
1030     return GNUNET_OK;
1031   }
1032   else
1033   {
1034     GNUNET_STATISTICS_update (stats,
1035                               "# flood messages discarded (clock skew too large)",
1036                               1, GNUNET_NO);
1037     return GNUNET_OK;
1038   }
1039   if (0 == (memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity))))
1040   {
1041     /* send to self, update our own estimate IF this also comes from us! */
1042     if (0 ==
1043         memcmp (&incoming_flood->pkey, &my_public_key, sizeof (my_public_key)))
1044       update_network_size_estimate ();
1045     return GNUNET_OK;
1046   }
1047   if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1048   {
1049     /* cancel transmission from us to this peer for this round */
1050     if (idx == estimate_index)
1051     {
1052       if (peer_entry->previous_round == GNUNET_YES)
1053       {
1054         /* cancel any activity for current round */
1055         if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1056         {
1057           GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1058           peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1059         }
1060         if (peer_entry->th != NULL)
1061         {
1062           GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1063           peer_entry->th = NULL;
1064         }
1065       }
1066     }
1067     else
1068     {
1069       /* cancel previous round only */
1070       peer_entry->previous_round = GNUNET_YES;
1071     }
1072   }
1073   if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1074     return GNUNET_OK;
1075   if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1076   {
1077     if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
1078       peer_entry->previous_round = GNUNET_NO;
1079     /* push back our result now, that peer is spreading bad information... */
1080     if (NULL == peer_entry->th)
1081     {
1082       if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1083         GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1084       peer_entry->transmit_task =
1085           GNUNET_SCHEDULER_add_now (&transmit_task, peer_entry);
1086     }
1087     /* Not closer than our most recent message, no need to do work here */
1088     GNUNET_STATISTICS_update (stats,
1089                               "# flood messages ignored (had closer already)",
1090                               1, GNUNET_NO);
1091     return GNUNET_OK;
1092   }
1093   if (GNUNET_YES != verify_message_crypto (incoming_flood))
1094   {
1095     GNUNET_break_op (0);
1096     return GNUNET_OK;
1097   }
1098   size_estimate_messages[idx] = *incoming_flood;
1099   size_estimate_messages[idx].hop_count =
1100       htonl (ntohl (incoming_flood->hop_count) + 1);
1101   hop_count_max =
1102       GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
1103
1104   /* have a new, better size estimate, inform clients */
1105   update_network_size_estimate ();
1106
1107   /* flood to rest */
1108   GNUNET_CONTAINER_multihashmap_iterate (peers, &update_flood_times,
1109                                          peer_entry);
1110   return GNUNET_OK;
1111 }
1112
1113
1114
1115 /**
1116  * Method called whenever a peer connects.
1117  *
1118  * @param cls closure
1119  * @param peer peer identity this notification is about
1120  * @param atsi performance data
1121  * @param atsi_count number of records in 'atsi'
1122  */
1123 static void
1124 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
1125                      const struct GNUNET_ATS_Information *atsi,
1126                      unsigned int atsi_count)
1127 {
1128   struct NSEPeerEntry *peer_entry;
1129
1130 #if DEBUG_NSE
1131   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' connected to us\n",
1132               GNUNET_i2s (peer));
1133 #endif
1134   peer_entry = GNUNET_malloc (sizeof (struct NSEPeerEntry));
1135   peer_entry->id = *peer;
1136   GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_entry,
1137                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1138   peer_entry->transmit_task =
1139       GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), &transmit_task,
1140                                     peer_entry);
1141 }
1142
1143
1144 /**
1145  * Method called whenever a peer disconnects.
1146  *
1147  * @param cls closure
1148  * @param peer peer identity this notification is about
1149  */
1150 static void
1151 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1152 {
1153   struct NSEPeerEntry *pos;
1154
1155 #if DEBUG_NSE
1156   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' disconnected from us\n",
1157               GNUNET_i2s (peer));
1158 #endif
1159   pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1160   if (NULL == pos)
1161   {
1162     GNUNET_break (0);
1163     return;
1164   }
1165   GNUNET_assert (GNUNET_YES ==
1166                  GNUNET_CONTAINER_multihashmap_remove (peers, &peer->hashPubKey,
1167                                                        pos));
1168   if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1169     GNUNET_SCHEDULER_cancel (pos->transmit_task);
1170   if (pos->th != NULL)
1171   {
1172     GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1173     pos->th = NULL;
1174   }
1175   GNUNET_free (pos);
1176 }
1177
1178
1179 /**
1180  * Task run during shutdown.
1181  *
1182  * @param cls unused
1183  * @param tc unused
1184  */
1185 static void
1186 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1187 {
1188   if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1189   {
1190     GNUNET_SCHEDULER_cancel (flood_task);
1191     flood_task = GNUNET_SCHEDULER_NO_TASK;
1192   }
1193   if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1194   {
1195     GNUNET_SCHEDULER_cancel (proof_task);
1196     proof_task = GNUNET_SCHEDULER_NO_TASK;
1197     write_proof ();             /* remember progress */
1198   }
1199   if (nc != NULL)
1200   {
1201     GNUNET_SERVER_notification_context_destroy (nc);
1202     nc = NULL;
1203   }
1204   if (coreAPI != NULL)
1205   {
1206     GNUNET_CORE_disconnect (coreAPI);
1207     coreAPI = NULL;
1208   }
1209   if (stats != NULL)
1210   {
1211     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1212     stats = NULL;
1213   }
1214   if (peers != NULL)
1215   {
1216     GNUNET_CONTAINER_multihashmap_destroy (peers);
1217     peers = NULL;
1218   }
1219   if (my_private_key != NULL)
1220   {
1221     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1222     my_private_key = NULL;
1223   }
1224 #if ENABLE_HISTOGRAM
1225   if (wh != NULL)
1226   {
1227     GNUNET_BIO_write_close (wh);
1228     wh = NULL;
1229   }
1230 #endif
1231 }
1232
1233
1234 /**
1235  * Called on core init/fail.
1236  *
1237  * @param cls service closure
1238  * @param server handle to the server for this service
1239  * @param identity the public identity of this peer
1240  */
1241 static void
1242 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1243            const struct GNUNET_PeerIdentity *identity)
1244 {
1245   struct GNUNET_TIME_Absolute now;
1246   struct GNUNET_TIME_Absolute prev_time;
1247   unsigned int i;
1248
1249   if (server == NULL)
1250   {
1251 #if DEBUG_NSE
1252     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection to core FAILED!\n");
1253 #endif
1254     GNUNET_SCHEDULER_shutdown ();
1255     return;
1256   }
1257   GNUNET_assert (0 ==
1258                  memcmp (&my_identity, identity,
1259                          sizeof (struct GNUNET_PeerIdentity)));
1260   now = GNUNET_TIME_absolute_get ();
1261   current_timestamp.abs_value =
1262       (now.abs_value / gnunet_nse_interval.rel_value) *
1263       gnunet_nse_interval.rel_value;
1264   next_timestamp.abs_value =
1265       current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1266
1267   for (i = 0; i < HISTORY_SIZE; i++)
1268   {
1269     prev_time.abs_value =
1270         current_timestamp.abs_value - (HISTORY_SIZE - i -
1271                                        1) * gnunet_nse_interval.rel_value;
1272     setup_flood_message (i, prev_time);
1273   }
1274   estimate_index = HISTORY_SIZE - 1;
1275   estimate_count = 2;
1276   flood_task =
1277       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1278                                     (next_timestamp), &update_flood_message,
1279                                     NULL);
1280 }
1281
1282
1283 /**
1284  * Handle network size estimate clients.
1285  *
1286  * @param cls closure
1287  * @param server the initialized server
1288  * @param c configuration to use
1289  */
1290 static void
1291 run (void *cls, struct GNUNET_SERVER_Handle *server,
1292      const struct GNUNET_CONFIGURATION_Handle *c)
1293 {
1294   char *keyfile;
1295   char *proof;
1296
1297   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1298     {&handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START,
1299      sizeof (struct GNUNET_MessageHeader)},
1300     {NULL, NULL, 0, 0}
1301   };
1302   static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
1303     {&handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD,
1304      sizeof (struct GNUNET_NSE_FloodMessage)},
1305     {NULL, 0, 0}
1306   };
1307   cfg = c;
1308
1309   if ((GNUNET_OK !=
1310        GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "INTERVAL",
1311                                             &gnunet_nse_interval)) ||
1312       (GNUNET_OK !=
1313        GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "WORKDELAY",
1314                                             &proof_find_delay)) ||
1315       (GNUNET_OK !=
1316        GNUNET_CONFIGURATION_get_value_number (cfg, "NSE", "WORKBITS",
1317                                               &nse_work_required)))
1318   {
1319     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1320                 _
1321                 ("NSE service is lacking key configuration settings.  Exiting.\n"));
1322     GNUNET_SCHEDULER_shutdown ();
1323     return;
1324   }
1325   if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1326   {
1327     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1328                 _("Invalid work requirement for NSE service. Exiting.\n"));
1329     GNUNET_SCHEDULER_shutdown ();
1330     return;
1331   }
1332
1333
1334   if (GNUNET_OK !=
1335       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
1336                                                &keyfile))
1337   {
1338     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1339                 _
1340                 ("NSE service is lacking key configuration settings.  Exiting.\n"));
1341     GNUNET_SCHEDULER_shutdown ();
1342     return;
1343   }
1344   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1345   GNUNET_free (keyfile);
1346   if (my_private_key == NULL)
1347   {
1348     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1349                 _("NSE service could not access hostkey.  Exiting.\n"));
1350     GNUNET_SCHEDULER_shutdown ();
1351     return;
1352   }
1353   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1354   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1355                       &my_identity.hashPubKey);
1356   if (GNUNET_OK !=
1357       GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
1358   {
1359     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1360                 _
1361                 ("NSE service is lacking key configuration settings.  Exiting.\n"));
1362     if (my_private_key != NULL)
1363     {
1364       GNUNET_CRYPTO_rsa_key_free (my_private_key);
1365       my_private_key = NULL;
1366     }
1367     GNUNET_SCHEDULER_shutdown ();
1368     return;
1369   }
1370   if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1371       (sizeof (my_proof) !=
1372        GNUNET_DISK_fn_read (proof, &my_proof, sizeof (my_proof))))
1373     my_proof = 0;
1374   GNUNET_free (proof);
1375   proof_task =
1376       GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1377                                           &find_proof, NULL);
1378
1379   peers = GNUNET_CONTAINER_multihashmap_create (128);
1380   GNUNET_SERVER_add_handlers (server, handlers);
1381   nc = GNUNET_SERVER_notification_context_create (server, 1);
1382   /* Connect to core service and register core handlers */
1383   coreAPI = GNUNET_CORE_connect (cfg,   /* Main configuration */
1384                                  CORE_QUEUE_SIZE,       /* queue size */
1385                                  NULL,  /* Closure passed to functions */
1386                                  &core_init,    /* Call core_init once connected */
1387                                  &handle_core_connect,  /* Handle connects */
1388                                  &handle_core_disconnect,       /* Handle disconnects */
1389                                  NULL,  /* Don't want notified about all incoming messages */
1390                                  GNUNET_NO,     /* For header only inbound notification */
1391                                  NULL,  /* Don't want notified about all outbound messages */
1392                                  GNUNET_NO,     /* For header only outbound notification */
1393                                  core_handlers);        /* Register these handlers */
1394   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1395                                 NULL);
1396 #if ENABLE_HISTOGRAM
1397   if (GNUNET_OK ==
1398       GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "HISTOGRAM", &proof))
1399   {
1400     wh = GNUNET_BIO_write_open (proof);
1401     GNUNET_free (proof);
1402   }
1403 #endif
1404   if (coreAPI == NULL)
1405   {
1406     GNUNET_SCHEDULER_shutdown ();
1407     return;
1408   }
1409   stats = GNUNET_STATISTICS_create ("nse", cfg);
1410 }
1411
1412
1413 /**
1414  * The main function for the statistics service.
1415  *
1416  * @param argc number of arguments from the command line
1417  * @param argv command line arguments
1418  * @return 0 ok, 1 on error
1419  */
1420 int
1421 main (int argc, char *const *argv)
1422 {
1423   return (GNUNET_OK ==
1424           GNUNET_SERVICE_run (argc, argv, "nse", GNUNET_SERVICE_OPTION_NONE,
1425                               &run, NULL)) ? 0 : 1;
1426 }
1427
1428 /* end of gnunet-service-nse.c */