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