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