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