- Fixed simplified variance code
[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 64
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   variance = 0.0;
348   mean = 0.0;
349
350   for (i = 0; i < estimate_count; i++)
351   {
352     int j;
353
354     j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
355     val = htonl (size_estimate_messages[j].matching_bits);
356     sum += val;
357     vsq += val * val;
358   }
359   if (0 != estimate_count)
360   {
361     mean = sum / estimate_count;
362     variance = (vsq - mean * sum) / estimate_count; // terrible for numerical stability...
363     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "(%f - %f) / %u = %f\n", 
364       vsq, mean * sum, estimate_count, variance);
365
366   }
367 #endif
368   GNUNET_assert (variance >= 0);
369   std_dev = sqrt (variance);
370   current_std_dev = std_dev;
371   current_size_estimate = mean;
372
373   em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage));
374   em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
375   em->reserved = htonl (0);
376   em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
377   em->size_estimate = mean - 0.332747;
378   nsize = log2 (GNUNET_CONTAINER_multihashmap_size (peers) + 1);
379   if (em->size_estimate < nsize)
380     em->size_estimate = nsize;
381   em->std_deviation = std_dev;
382   GNUNET_STATISTICS_set (stats, "# nodes in the network (estimate)",
383                          (uint64_t) pow (2, mean - 1.0 / 3.0), GNUNET_NO);
384 }
385
386
387 /**
388  * Handler for START message from client, triggers an
389  * immediate current network estimate notification.
390  * Also, we remember the client for updates upon future
391  * estimate measurements.
392  *
393  * @param cls unused
394  * @param client who sent the message
395  * @param message the message received
396  */
397 static void
398 handle_start_message (void *cls, struct GNUNET_SERVER_Client *client,
399                       const struct GNUNET_MessageHeader *message)
400 {
401   struct GNUNET_NSE_ClientMessage em;
402
403 #if DEBUG_NSE
404   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n");
405 #endif
406   GNUNET_SERVER_notification_context_add (nc, client);
407   setup_estimate_message (&em);
408   GNUNET_SERVER_notification_context_unicast (nc, client, &em.header,
409                                               GNUNET_YES);
410   GNUNET_SERVER_receive_done (client, GNUNET_OK);
411 }
412
413
414 /**
415  * How long should we delay a message to go the given number of
416  * matching bits?
417  *
418  * @param matching_bits number of matching bits to consider
419  */
420 static double
421 get_matching_bits_delay (uint32_t matching_bits)
422 {
423   /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */
424   // S is next_timestamp (ignored in return value)
425   // f is frequency (gnunet_nse_interval)
426   // x is matching_bits
427   // p' is current_size_estimate
428   return ((double) gnunet_nse_interval.rel_value / (double) 2.0) -
429       ((gnunet_nse_interval.rel_value / M_PI) *
430        atan (matching_bits - current_size_estimate));
431 }
432
433
434 /**
435  * What delay randomization should we apply for a given number of matching bits?
436  *
437  * @param matching_bits number of matching bits
438  * @return random delay to apply
439  */
440 static struct GNUNET_TIME_Relative
441 get_delay_randomization (uint32_t matching_bits)
442 {
443 #if USE_RANDOM_DELAYS
444   struct GNUNET_TIME_Relative ret;
445
446   if (matching_bits == 0)
447     return GNUNET_TIME_UNIT_ZERO;
448   ret.rel_value =
449       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
450                                 (uint32_t) (get_matching_bits_delay
451                                             (matching_bits -
452                                              1) / (double) (hop_count_max +
453                                                             1)));
454   return ret;
455 #else
456   return GNUNET_TIME_UNIT_ZERO;
457 #endif
458 }
459
460
461 /**
462  * Get the number of matching bits that the given timestamp has to the given peer ID.
463  *
464  * @param timestamp time to generate key
465  * @param id peer identity to compare with
466  * @return number of matching bits
467  */
468 static uint32_t
469 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
470                    const struct GNUNET_PeerIdentity *id)
471 {
472   GNUNET_HashCode timestamp_hash;
473
474   GNUNET_CRYPTO_hash (&timestamp.abs_value, sizeof (timestamp.abs_value),
475                       &timestamp_hash);
476   return GNUNET_CRYPTO_hash_matching_bits (&timestamp_hash, &id->hashPubKey);
477 }
478
479
480 /**
481  * Get the transmission delay that should be applied for a
482  * particular round.
483  *
484  * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
485  *                      0 for the current round (based on our proximity to time key)
486  * @return delay that should be applied
487  */
488 static struct GNUNET_TIME_Relative
489 get_transmit_delay (int round_offset)
490 {
491   struct GNUNET_TIME_Relative ret;
492   struct GNUNET_TIME_Absolute tgt;
493   double dist_delay;
494   uint32_t matching_bits;
495
496   switch (round_offset)
497   {
498   case -1:
499     /* previous round is randomized between 0 and 50 ms */
500 #if USE_RANDOM_DELAYS
501     ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
502 #else
503     ret = GNUNET_TIME_UNIT_ZERO;
504 #endif
505 #if DEBUG_NSE
506     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
507                 "Transmitting previous round behind schedule in %llu ms\n",
508                 (unsigned long long) ret.rel_value);
509 #endif
510     return ret;
511   case 0:
512     /* current round is based on best-known matching_bits */
513     matching_bits =
514         ntohl (size_estimate_messages[estimate_index].matching_bits);
515     dist_delay = get_matching_bits_delay (matching_bits);
516     dist_delay += get_delay_randomization (matching_bits).rel_value;
517     ret.rel_value = (uint64_t) dist_delay;
518 #if DEBUG_NSE
519     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
520                 "For round %llu, delay for %u matching bits is %llu ms\n",
521                 (unsigned long long) current_timestamp.abs_value,
522                 (unsigned int) matching_bits,
523                 (unsigned long long) ret.rel_value);
524 #endif
525     /* now consider round start time and add delay to it */
526     tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
527     return GNUNET_TIME_absolute_get_remaining (tgt);
528   }
529   GNUNET_break (0);
530   return GNUNET_TIME_UNIT_FOREVER_REL;
531 }
532
533
534 /**
535  * Task that triggers a NSE P2P transmission.
536  *
537  * @param cls the 'struct NSEPeerEntry'
538  * @param tc scheduler context
539  */
540 static void
541 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
542
543
544 /**
545  * Called when core is ready to send a message we asked for
546  * out to the destination.
547  *
548  * @param cls closure (NULL)
549  * @param size number of bytes available in buf
550  * @param buf where the callee should write the message
551  * @return number of bytes written to buf
552  */
553 static size_t
554 transmit_ready (void *cls, size_t size, void *buf)
555 {
556   struct NSEPeerEntry *peer_entry = cls;
557   unsigned int idx;
558
559   peer_entry->th = NULL;
560   if (buf == NULL)
561   {
562     /* client disconnected */
563     return 0;
564   }
565   GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
566   idx = estimate_index;
567   if (peer_entry->previous_round == GNUNET_NO)
568   {
569     idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
570     peer_entry->previous_round = GNUNET_YES;
571     peer_entry->transmit_task =
572         GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), &transmit_task,
573                                       peer_entry);
574   }
575   if ((ntohl (size_estimate_messages[idx].hop_count) == 0) &&
576       (GNUNET_SCHEDULER_NO_TASK != proof_task))
577   {
578     GNUNET_STATISTICS_update (stats,
579                               "# flood messages not generated (no proof yet)",
580                               1, GNUNET_NO);
581     return 0;
582   }
583 #if DEBUG_NSE
584   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
585               "In round %llu, sending to `%s' estimate with %u bits\n",
586               (unsigned long long)
587               GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].
588                                          timestamp).abs_value,
589               GNUNET_i2s (&peer_entry->id),
590               (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
591 #endif
592   if (ntohl (size_estimate_messages[idx].hop_count) == 0)
593     GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO);
594   GNUNET_STATISTICS_update (stats, "# flood messages transmitted", 1,
595                             GNUNET_NO);
596   memcpy (buf, &size_estimate_messages[idx],
597           sizeof (struct GNUNET_NSE_FloodMessage));
598   GNUNET_STATISTICS_update (stats, "# flood messages sent", 1, GNUNET_NO);
599   return sizeof (struct GNUNET_NSE_FloodMessage);
600 }
601
602
603 /**
604  * Task that triggers a NSE P2P transmission.
605  *
606  * @param cls the 'struct NSEPeerEntry'
607  * @param tc scheduler context
608  */
609 static void
610 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
611 {
612   struct NSEPeerEntry *peer_entry = cls;
613
614   peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
615   GNUNET_assert (NULL == peer_entry->th);
616   peer_entry->th =
617       GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO, NSE_PRIORITY,
618                                          GNUNET_TIME_UNIT_FOREVER_REL,
619                                          &peer_entry->id,
620                                          sizeof (struct
621                                                  GNUNET_NSE_FloodMessage),
622                                          &transmit_ready, peer_entry);
623 }
624
625
626 /**
627  * We've sent on our flood message or one that we received which was
628  * validated and closer than ours.  Update the global list of recent
629  * messages and the average.  Also re-broadcast the message to any
630  * clients.
631  */
632 static void
633 update_network_size_estimate ()
634 {
635   struct GNUNET_NSE_ClientMessage em;
636
637   setup_estimate_message (&em);
638   GNUNET_SERVER_notification_context_broadcast (nc, &em.header, GNUNET_YES);
639 }
640
641
642 /**
643  * Setup a flood message in our history array at the given
644  * slot offset for the given timestamp.
645  *
646  * @param slot index to use
647  * @param ts timestamp to use
648  */
649 static void
650 setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts)
651 {
652   struct GNUNET_NSE_FloodMessage *fm;
653   uint32_t matching_bits;
654
655   matching_bits = get_matching_bits (ts, &my_identity);
656   fm = &size_estimate_messages[slot];
657   fm->header.size = htons (sizeof (struct GNUNET_NSE_FloodMessage));
658   fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
659   fm->hop_count = htonl (0);
660   fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
661   fm->purpose.size =
662       htonl (sizeof (struct GNUNET_NSE_FloodMessage) -
663              sizeof (struct GNUNET_MessageHeader) - sizeof (uint32_t) -
664              sizeof (struct GNUNET_CRYPTO_RsaSignature));
665   fm->matching_bits = htonl (matching_bits);
666   fm->timestamp = GNUNET_TIME_absolute_hton (ts);
667   fm->pkey = my_public_key;
668   fm->proof_of_work = my_proof;
669   GNUNET_assert (GNUNET_OK ==
670                  GNUNET_CRYPTO_rsa_sign (my_private_key, &fm->purpose,
671                                          &fm->signature));
672 }
673
674
675 /**
676  * Schedule transmission for the given peer for the current round based
677  * on what we know about the desired delay.
678  *
679  * @param cls unused
680  * @param key hash of peer identity
681  * @param value the 'struct NSEPeerEntry'
682  * @return GNUNET_OK (continue to iterate)
683  */
684 static int
685 schedule_current_round (void *cls, const GNUNET_HashCode * key, void *value)
686 {
687   struct NSEPeerEntry *peer_entry = value;
688   struct GNUNET_TIME_Relative delay;
689
690   if (peer_entry->th != NULL)
691   {
692     peer_entry->previous_round = GNUNET_NO;
693     return GNUNET_OK;
694   }
695   if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
696   {
697     GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
698     peer_entry->previous_round = GNUNET_NO;
699   }
700   delay =
701       get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
702   peer_entry->transmit_task =
703       GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
704   return GNUNET_OK;
705 }
706
707
708 /**
709  * Update our flood message to be sent (and our timestamps).
710  *
711  * @param cls unused
712  * @param tc context for this message
713  */
714 static void
715 update_flood_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
716 {
717   struct GNUNET_TIME_Relative offset;
718   unsigned int i;
719
720   flood_task = GNUNET_SCHEDULER_NO_TASK;
721   offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
722   if (0 != offset.rel_value)
723   {
724     /* somehow run early, delay more */
725     flood_task =
726         GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL);
727     return;
728   }
729   current_timestamp = next_timestamp;
730   next_timestamp =
731       GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
732   estimate_index = (estimate_index + 1) % HISTORY_SIZE;
733   if (estimate_count < HISTORY_SIZE)
734     estimate_count++;
735   if (next_timestamp.abs_value ==
736       GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
737   {
738     /* we received a message for this round way early, use it! */
739     size_estimate_messages[estimate_index] = next_message;
740     size_estimate_messages[estimate_index].hop_count =
741         htonl (1 + ntohl (next_message.hop_count));
742   }
743   else
744     setup_flood_message (estimate_index, current_timestamp);
745   next_message.matching_bits = htonl (0);       /* reset for 'next' round */
746   hop_count_max = 0;
747   for (i = 0; i < HISTORY_SIZE; i++)
748     hop_count_max =
749         GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max);
750   GNUNET_CONTAINER_multihashmap_iterate (peers, &schedule_current_round, NULL);
751   flood_task =
752       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
753                                     (next_timestamp), &update_flood_message,
754                                     NULL);
755 }
756
757
758 /**
759  * Count the leading zeroes in hash.
760  *
761  * @param hash
762  * @return the number of leading zero bits.
763  */
764 static unsigned int
765 count_leading_zeroes (const GNUNET_HashCode * hash)
766 {
767   unsigned int hash_count;
768
769   hash_count = 0;
770   while ((0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)))
771     hash_count++;
772   return hash_count;
773 }
774
775
776 /**
777  * Check whether the given public key
778  * and integer are a valid proof of work.
779  *
780  * @param pkey the public key
781  * @param val the integer
782  *
783  * @return GNUNET_YES if valid, GNUNET_NO if not
784  */
785 static int
786 check_proof_of_work (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
787                      uint64_t val)
788 {
789   char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
790            sizeof (val)];
791   GNUNET_HashCode result;
792
793   memcpy (buf, &val, sizeof (val));
794   memcpy (&buf[sizeof (val)], pkey,
795           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
796   GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
797   return (count_leading_zeroes (&result) >=
798           nse_work_required) ? GNUNET_YES : GNUNET_NO;
799 }
800
801
802 /**
803  * Write our current proof to disk.
804  */
805 static void
806 write_proof ()
807 {
808   char *proof;
809
810   if (GNUNET_OK !=
811       GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
812     return;
813   if (sizeof (my_proof) !=
814       GNUNET_DISK_fn_write (proof, &my_proof, sizeof (my_proof),
815                             GNUNET_DISK_PERM_USER_READ |
816                             GNUNET_DISK_PERM_USER_WRITE))
817     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof);
818   GNUNET_free (proof);
819
820 }
821
822
823 /**
824  * Find our proof of work.
825  *
826  * @param cls closure (unused)
827  * @param tc task context
828  */
829 static void
830 find_proof (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
831 {
832 #define ROUND_SIZE 10
833   uint64_t counter;
834   char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
835            sizeof (uint64_t)];
836   GNUNET_HashCode result;
837   unsigned int i;
838
839   proof_task = GNUNET_SCHEDULER_NO_TASK;
840   memcpy (&buf[sizeof (uint64_t)], &my_public_key,
841           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
842   i = 0;
843   counter = my_proof;
844   while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
845   {
846     memcpy (buf, &counter, sizeof (uint64_t));
847     GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
848     if (nse_work_required <= count_leading_zeroes (&result))
849     {
850       my_proof = counter;
851 #if DEBUG_NSE
852       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Proof of work found: %llu!\n",
853                   (unsigned long long) GNUNET_ntohll (counter));
854 #endif
855       for (i = 0; i < HISTORY_SIZE; i++)
856         if (ntohl (size_estimate_messages[i].hop_count) == 0)
857         {
858           size_estimate_messages[i].proof_of_work = my_proof;
859           GNUNET_assert (GNUNET_OK ==
860                          GNUNET_CRYPTO_rsa_sign (my_private_key,
861                                                  &size_estimate_messages
862                                                  [i].purpose,
863                                                  &size_estimate_messages
864                                                  [i].signature));
865         }
866       write_proof ();
867       return;
868     }
869     counter++;
870     i++;
871   }
872   if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
873   {
874 #if DEBUG_NSE
875     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Testing proofs currently at %llu\n",
876                 (unsigned long long) counter);
877 #endif
878     /* remember progress every 100 rounds */
879     my_proof = counter;
880     write_proof ();
881   }
882   else
883   {
884     my_proof = counter;
885   }
886   proof_task =
887       GNUNET_SCHEDULER_add_delayed (proof_find_delay, &find_proof, NULL);
888 }
889
890
891 /**
892  * An incoming flood message has been received which claims
893  * to have more bits matching than any we know in this time
894  * period.  Verify the signature and/or proof of work.
895  *
896  * @param incoming_flood the message to verify
897  *
898  * @return GNUNET_YES if the message is verified
899  *         GNUNET_NO if the key/signature don't verify
900  */
901 static int
902 verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
903 {
904   if (GNUNET_YES !=
905       check_proof_of_work (&incoming_flood->pkey,
906                            incoming_flood->proof_of_work))
907   {
908     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Proof of work invalid: %llu!\n"),
909                 (unsigned long long)
910                 GNUNET_ntohll (incoming_flood->proof_of_work));
911     GNUNET_break_op (0);
912     return GNUNET_NO;
913   }
914   if (GNUNET_OK !=
915       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
916                                 &incoming_flood->purpose,
917                                 &incoming_flood->signature,
918                                 &incoming_flood->pkey))
919   {
920     GNUNET_break_op (0);
921     return GNUNET_NO;
922   }
923   return GNUNET_YES;
924 }
925
926
927 /**
928  * Update transmissions for the given peer for the current round based
929  * on updated proximity information.
930  *
931  * @param cls peer entry to exclude from updates
932  * @param key hash of peer identity
933  * @param value the 'struct NSEPeerEntry'
934  * @return GNUNET_OK (continue to iterate)
935  */
936 static int
937 update_flood_times (void *cls, const GNUNET_HashCode * key, void *value)
938 {
939   struct NSEPeerEntry *exclude = cls;
940   struct NSEPeerEntry *peer_entry = value;
941   struct GNUNET_TIME_Relative delay;
942
943   if (peer_entry->th != NULL)
944     return GNUNET_OK;           /* already active */
945   if (peer_entry == exclude)
946     return GNUNET_OK;           /* trigger of the update */
947   if (peer_entry->previous_round == GNUNET_NO)
948   {
949     /* still stuck in previous round, no point to update, check that
950      * we are active here though... */
951     GNUNET_break ((peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
952                   (peer_entry->th != NULL));
953     return GNUNET_OK;
954   }
955   if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
956   {
957     GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
958     peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
959   }
960   delay = get_transmit_delay (0);
961   peer_entry->transmit_task =
962       GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
963   return GNUNET_OK;
964 }
965
966
967 /**
968  * Core handler for size estimate flooding messages.
969  *
970  * @param cls closure unused
971  * @param message message
972  * @param peer peer identity this message is from (ignored)
973  * @param atsi performance data (ignored)
974  * @param atsi_count number of records in 'atsi'
975  */
976 static int
977 handle_p2p_size_estimate (void *cls, const struct GNUNET_PeerIdentity *peer,
978                           const struct GNUNET_MessageHeader *message,
979                           const struct GNUNET_ATS_Information *atsi,
980                           unsigned int atsi_count)
981 {
982   const struct GNUNET_NSE_FloodMessage *incoming_flood;
983   struct GNUNET_TIME_Absolute ts;
984   struct NSEPeerEntry *peer_entry;
985   uint32_t matching_bits;
986   unsigned int idx;
987
988 #if ENABLE_HISTOGRAM
989   if (NULL != wh)
990     GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
991 #endif
992   incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
993   GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
994   matching_bits = ntohl (incoming_flood->matching_bits);
995 #if DEBUG_NSE
996   {
997     char origin[5];
998     char pred[5];
999     struct GNUNET_PeerIdentity os;
1000
1001     GNUNET_CRYPTO_hash (&incoming_flood->pkey,
1002                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1003                         &os.hashPubKey);
1004     GNUNET_snprintf (origin, sizeof (origin), "%s", GNUNET_i2s (&os));
1005     GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer));
1006     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007                 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
1008                 (unsigned long long)
1009                 GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1010                 origin, pred, GNUNET_i2s (&my_identity),
1011                 (unsigned int) matching_bits);
1012   }
1013 #endif
1014
1015   peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1016   if (NULL == peer_entry)
1017   {
1018     GNUNET_break (0);
1019     return GNUNET_OK;
1020   }
1021
1022   ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1023
1024   if (ts.abs_value == current_timestamp.abs_value)
1025     idx = estimate_index;
1026   else if (ts.abs_value ==
1027            current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1028     idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1029   else if (ts.abs_value ==
1030            next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1031   {
1032     if (matching_bits <= ntohl (next_message.matching_bits))
1033       return GNUNET_OK;         /* ignore, simply too early/late */
1034     if (GNUNET_YES != verify_message_crypto (incoming_flood))
1035     {
1036       GNUNET_break_op (0);
1037       return GNUNET_OK;
1038     }
1039     next_message = *incoming_flood;
1040     return GNUNET_OK;
1041   }
1042   else
1043   {
1044     GNUNET_STATISTICS_update (stats,
1045                               "# flood messages discarded (clock skew too large)",
1046                               1, GNUNET_NO);
1047     return GNUNET_OK;
1048   }
1049   if (0 == (memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity))))
1050   {
1051     /* send to self, update our own estimate IF this also comes from us! */
1052     if (0 ==
1053         memcmp (&incoming_flood->pkey, &my_public_key, sizeof (my_public_key)))
1054       update_network_size_estimate ();
1055     return GNUNET_OK;
1056   }
1057   if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1058   {
1059     /* cancel transmission from us to this peer for this round */
1060     if (idx == estimate_index)
1061     {
1062       if (peer_entry->previous_round == GNUNET_YES)
1063       {
1064         /* cancel any activity for current round */
1065         if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1066         {
1067           GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1068           peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1069         }
1070         if (peer_entry->th != NULL)
1071         {
1072           GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1073           peer_entry->th = NULL;
1074         }
1075       }
1076     }
1077     else
1078     {
1079       /* cancel previous round only */
1080       peer_entry->previous_round = GNUNET_YES;
1081     }
1082   }
1083   if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1084     return GNUNET_OK;
1085   if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1086   {
1087     if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
1088       peer_entry->previous_round = GNUNET_NO;
1089     /* push back our result now, that peer is spreading bad information... */
1090     if (NULL == peer_entry->th)
1091     {
1092       if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1093         GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1094       peer_entry->transmit_task =
1095           GNUNET_SCHEDULER_add_now (&transmit_task, peer_entry);
1096     }
1097     /* Not closer than our most recent message, no need to do work here */
1098     GNUNET_STATISTICS_update (stats,
1099                               "# flood messages ignored (had closer already)",
1100                               1, GNUNET_NO);
1101     return GNUNET_OK;
1102   }
1103   if (GNUNET_YES != verify_message_crypto (incoming_flood))
1104   {
1105     GNUNET_break_op (0);
1106     return GNUNET_OK;
1107   }
1108   size_estimate_messages[idx] = *incoming_flood;
1109   size_estimate_messages[idx].hop_count =
1110       htonl (ntohl (incoming_flood->hop_count) + 1);
1111   hop_count_max =
1112       GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
1113
1114   /* have a new, better size estimate, inform clients */
1115   update_network_size_estimate ();
1116
1117   /* flood to rest */
1118   GNUNET_CONTAINER_multihashmap_iterate (peers, &update_flood_times,
1119                                          peer_entry);
1120   return GNUNET_OK;
1121 }
1122
1123
1124
1125 /**
1126  * Method called whenever a peer connects.
1127  *
1128  * @param cls closure
1129  * @param peer peer identity this notification is about
1130  * @param atsi performance data
1131  * @param atsi_count number of records in 'atsi'
1132  */
1133 static void
1134 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
1135                      const struct GNUNET_ATS_Information *atsi,
1136                      unsigned int atsi_count)
1137 {
1138   struct NSEPeerEntry *peer_entry;
1139
1140 #if DEBUG_NSE
1141   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' connected to us\n",
1142               GNUNET_i2s (peer));
1143 #endif
1144   peer_entry = GNUNET_malloc (sizeof (struct NSEPeerEntry));
1145   peer_entry->id = *peer;
1146   GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_entry,
1147                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1148   peer_entry->transmit_task =
1149       GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), &transmit_task,
1150                                     peer_entry);
1151 }
1152
1153
1154 /**
1155  * Method called whenever a peer disconnects.
1156  *
1157  * @param cls closure
1158  * @param peer peer identity this notification is about
1159  */
1160 static void
1161 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1162 {
1163   struct NSEPeerEntry *pos;
1164
1165 #if DEBUG_NSE
1166   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' disconnected from us\n",
1167               GNUNET_i2s (peer));
1168 #endif
1169   pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1170   if (NULL == pos)
1171   {
1172     GNUNET_break (0);
1173     return;
1174   }
1175   GNUNET_assert (GNUNET_YES ==
1176                  GNUNET_CONTAINER_multihashmap_remove (peers, &peer->hashPubKey,
1177                                                        pos));
1178   if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1179     GNUNET_SCHEDULER_cancel (pos->transmit_task);
1180   if (pos->th != NULL)
1181   {
1182     GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1183     pos->th = NULL;
1184   }
1185   GNUNET_free (pos);
1186 }
1187
1188
1189 /**
1190  * Task run during shutdown.
1191  *
1192  * @param cls unused
1193  * @param tc unused
1194  */
1195 static void
1196 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1197 {
1198   if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1199   {
1200     GNUNET_SCHEDULER_cancel (flood_task);
1201     flood_task = GNUNET_SCHEDULER_NO_TASK;
1202   }
1203   if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1204   {
1205     GNUNET_SCHEDULER_cancel (proof_task);
1206     proof_task = GNUNET_SCHEDULER_NO_TASK;
1207     write_proof ();             /* remember progress */
1208   }
1209   if (nc != NULL)
1210   {
1211     GNUNET_SERVER_notification_context_destroy (nc);
1212     nc = NULL;
1213   }
1214   if (coreAPI != NULL)
1215   {
1216     GNUNET_CORE_disconnect (coreAPI);
1217     coreAPI = NULL;
1218   }
1219   if (stats != NULL)
1220   {
1221     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1222     stats = NULL;
1223   }
1224   if (peers != NULL)
1225   {
1226     GNUNET_CONTAINER_multihashmap_destroy (peers);
1227     peers = NULL;
1228   }
1229   if (my_private_key != NULL)
1230   {
1231     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1232     my_private_key = NULL;
1233   }
1234 #if ENABLE_HISTOGRAM
1235   if (wh != NULL)
1236   {
1237     GNUNET_BIO_write_close (wh);
1238     wh = NULL;
1239   }
1240 #endif
1241 }
1242
1243
1244 /**
1245  * Called on core init/fail.
1246  *
1247  * @param cls service closure
1248  * @param server handle to the server for this service
1249  * @param identity the public identity of this peer
1250  */
1251 static void
1252 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1253            const struct GNUNET_PeerIdentity *identity)
1254 {
1255   struct GNUNET_TIME_Absolute now;
1256   struct GNUNET_TIME_Absolute prev_time;
1257   unsigned int i;
1258
1259   if (server == NULL)
1260   {
1261 #if DEBUG_NSE
1262     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection to core FAILED!\n");
1263 #endif
1264     GNUNET_SCHEDULER_shutdown ();
1265     return;
1266   }
1267   GNUNET_assert (0 ==
1268                  memcmp (&my_identity, identity,
1269                          sizeof (struct GNUNET_PeerIdentity)));
1270   now = GNUNET_TIME_absolute_get ();
1271   current_timestamp.abs_value =
1272       (now.abs_value / gnunet_nse_interval.rel_value) *
1273       gnunet_nse_interval.rel_value;
1274   next_timestamp.abs_value =
1275       current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1276
1277   for (i = 0; i < HISTORY_SIZE; i++)
1278   {
1279     prev_time.abs_value =
1280         current_timestamp.abs_value - (HISTORY_SIZE - i -
1281                                        1) * gnunet_nse_interval.rel_value;
1282     setup_flood_message (i, prev_time);
1283   }
1284   estimate_index = HISTORY_SIZE - 1;
1285   estimate_count = 2;
1286   flood_task =
1287       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1288                                     (next_timestamp), &update_flood_message,
1289                                     NULL);
1290 }
1291
1292
1293 /**
1294  * Handle network size estimate clients.
1295  *
1296  * @param cls closure
1297  * @param server the initialized server
1298  * @param c configuration to use
1299  */
1300 static void
1301 run (void *cls, struct GNUNET_SERVER_Handle *server,
1302      const struct GNUNET_CONFIGURATION_Handle *c)
1303 {
1304   char *keyfile;
1305   char *proof;
1306
1307   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1308     {&handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START,
1309      sizeof (struct GNUNET_MessageHeader)},
1310     {NULL, NULL, 0, 0}
1311   };
1312   static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
1313     {&handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD,
1314      sizeof (struct GNUNET_NSE_FloodMessage)},
1315     {NULL, 0, 0}
1316   };
1317   cfg = c;
1318
1319   if ((GNUNET_OK !=
1320        GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "INTERVAL",
1321                                             &gnunet_nse_interval)) ||
1322       (GNUNET_OK !=
1323        GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "WORKDELAY",
1324                                             &proof_find_delay)) ||
1325       (GNUNET_OK !=
1326        GNUNET_CONFIGURATION_get_value_number (cfg, "NSE", "WORKBITS",
1327                                               &nse_work_required)))
1328   {
1329     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1330                 _
1331                 ("NSE service is lacking key configuration settings.  Exiting.\n"));
1332     GNUNET_SCHEDULER_shutdown ();
1333     return;
1334   }
1335   if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1336   {
1337     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1338                 _("Invalid work requirement for NSE service. Exiting.\n"));
1339     GNUNET_SCHEDULER_shutdown ();
1340     return;
1341   }
1342
1343
1344   if (GNUNET_OK !=
1345       GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
1346                                                &keyfile))
1347   {
1348     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1349                 _
1350                 ("NSE service is lacking key configuration settings.  Exiting.\n"));
1351     GNUNET_SCHEDULER_shutdown ();
1352     return;
1353   }
1354   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1355   GNUNET_free (keyfile);
1356   if (my_private_key == NULL)
1357   {
1358     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1359                 _("NSE service could not access hostkey.  Exiting.\n"));
1360     GNUNET_SCHEDULER_shutdown ();
1361     return;
1362   }
1363   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1364   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1365                       &my_identity.hashPubKey);
1366   if (GNUNET_OK !=
1367       GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
1368   {
1369     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1370                 _
1371                 ("NSE service is lacking key configuration settings.  Exiting.\n"));
1372     if (my_private_key != NULL)
1373     {
1374       GNUNET_CRYPTO_rsa_key_free (my_private_key);
1375       my_private_key = NULL;
1376     }
1377     GNUNET_SCHEDULER_shutdown ();
1378     return;
1379   }
1380   if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1381       (sizeof (my_proof) !=
1382        GNUNET_DISK_fn_read (proof, &my_proof, sizeof (my_proof))))
1383     my_proof = 0;
1384   GNUNET_free (proof);
1385   proof_task =
1386       GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1387                                           &find_proof, NULL);
1388
1389   peers = GNUNET_CONTAINER_multihashmap_create (128);
1390   GNUNET_SERVER_add_handlers (server, handlers);
1391   nc = GNUNET_SERVER_notification_context_create (server, 1);
1392   /* Connect to core service and register core handlers */
1393   coreAPI = GNUNET_CORE_connect (cfg,   /* Main configuration */
1394                                  CORE_QUEUE_SIZE,       /* queue size */
1395                                  NULL,  /* Closure passed to functions */
1396                                  &core_init,    /* Call core_init once connected */
1397                                  &handle_core_connect,  /* Handle connects */
1398                                  &handle_core_disconnect,       /* Handle disconnects */
1399                                  NULL,  /* Don't want notified about all incoming messages */
1400                                  GNUNET_NO,     /* For header only inbound notification */
1401                                  NULL,  /* Don't want notified about all outbound messages */
1402                                  GNUNET_NO,     /* For header only outbound notification */
1403                                  core_handlers);        /* Register these handlers */
1404   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1405                                 NULL);
1406 #if ENABLE_HISTOGRAM
1407   if (GNUNET_OK ==
1408       GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "HISTOGRAM", &proof))
1409   {
1410     wh = GNUNET_BIO_write_open (proof);
1411     GNUNET_free (proof);
1412   }
1413 #endif
1414   if (coreAPI == NULL)
1415   {
1416     GNUNET_SCHEDULER_shutdown ();
1417     return;
1418   }
1419   stats = GNUNET_STATISTICS_create ("nse", cfg);
1420 }
1421
1422
1423 /**
1424  * The main function for the statistics service.
1425  *
1426  * @param argc number of arguments from the command line
1427  * @param argv command line arguments
1428  * @return 0 ok, 1 on error
1429  */
1430 int
1431 main (int argc, char *const *argv)
1432 {
1433   return (GNUNET_OK ==
1434           GNUNET_SERVICE_run (argc, argv, "nse", GNUNET_SERVICE_OPTION_NONE,
1435                               &run, NULL)) ? 0 : 1;
1436 }
1437
1438 /* end of gnunet-service-nse.c */