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