f7b5e311d328087e82631343414da7c3936b3712
[oweals/gnunet.git] / src / nse / gnunet-service-nse.c
1 /*
2   This file is part of GNUnet.
3   (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
4
5   GNUnet is free software; you can redistribute it and/or modify
6   it under the terms of the GNU General Public License as published
7   by the Free Software Foundation; either version 3, or (at your
8   option) any later version.
9
10   GNUnet is distributed in the hope that it will be useful, but
11   WITHOUT ANY WARRANTY; without even the implied warranty of
12   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13   General Public License for more details.
14
15   You should have received a copy of the GNU General Public License
16   along with GNUnet; see the file COPYING.  If not, write to the
17   Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18   Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file nse/gnunet-service-nse.c
23  * @brief network size estimation service
24  * @author Nathan Evans
25  * @author Christian Grothoff
26  *
27  * The purpose of this service is to estimate the size of the network.
28  * Given a specified interval, each peer hashes the most recent
29  * timestamp which is evenly divisible by that interval.  This hash is
30  * compared in distance to the peer identity to choose an offset.  The
31  * closer the peer identity to the hashed timestamp, the earlier the
32  * peer sends out a "nearest peer" message.  The closest peer's
33  * message should thus be received before any others, which stops
34  * those peer from sending their messages at a later duration.  So
35  * every peer should receive the same nearest peer message, and from
36  * this can calculate the expected number of peers in the network.
37  */
38 #include "platform.h"
39 #include <math.h>
40 #include "gnunet_util_lib.h"
41 #include "gnunet_constants.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_statistics_service.h"
45 #include "gnunet_core_service.h"
46 #include "gnunet_nse_service.h"
47 #include "nse.h"
48
49 /**
50  * Should messages be delayed randomly?  This option should be set to
51  * GNUNET_NO only for experiments, not in production.  It should also
52  * be removed once the initial experiments have been completed.
53  */
54 #define USE_RANDOM_DELAYS GNUNET_YES
55
56 /**
57  * Should we generate a histogram with the time stamps of when we received
58  * NSE messages to disk? (for performance evaluation only, not useful in
59  * production).  The associated code should also probably be removed
60  * once we're done with experiments.
61  */
62 #define ENABLE_HISTOGRAM GNUNET_NO
63
64 /**
65  * Over how many values do we calculate the weighted average?
66  */
67 #define HISTORY_SIZE 64
68
69 /**
70  * Size of the queue to core.
71  */
72 #define CORE_QUEUE_SIZE 2
73
74 /**
75  * Message priority to use.
76  */
77 #define NSE_PRIORITY 5
78
79 #if FREEBSD
80 #define log2(a) (log(a)/log(2))
81 #endif
82
83 /**
84  * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
85  */
86 static unsigned long long nse_work_required;
87
88 /**
89  * Interval for sending network size estimation flood requests.
90  */
91 static struct GNUNET_TIME_Relative gnunet_nse_interval;
92
93 /**
94  * Interval between proof find runs.
95  */
96 static struct GNUNET_TIME_Relative proof_find_delay;
97
98 #if ENABLE_HISTOGRAM
99 /**
100  * Handle for writing when we received messages to disk.
101  */
102 static struct GNUNET_BIO_WriteHandle *wh;
103 #endif
104
105
106 /**
107  * Per-peer information.
108  */
109 struct NSEPeerEntry
110 {
111
112   /**
113    * Pending message for this peer.
114    */
115   struct GNUNET_MessageHeader *pending_message;
116
117   /**
118    * Core handle for sending messages to this peer.
119    */
120   struct GNUNET_CORE_TransmitHandle *th;
121
122   /**
123    * What is the identity of the peer?
124    */
125   struct GNUNET_PeerIdentity id;
126
127   /**
128    * Task scheduled to send message to this peer.
129    */
130   GNUNET_SCHEDULER_TaskIdentifier transmit_task;
131
132   /**
133    * Did we receive or send a message about the previous round
134    * to this peer yet?   GNUNET_YES if the previous round has
135    * been taken care of.
136    */
137   int previous_round;
138 };
139
140
141 /**
142  * Network size estimate reply; sent when "this"
143  * peer's timer has run out before receiving a
144  * valid reply from another peer.
145  */
146 struct GNUNET_NSE_FloodMessage
147 {
148   /**
149    * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
150    */
151   struct GNUNET_MessageHeader header;
152
153   /**
154    * Number of hops this message has taken so far.
155    */
156   uint32_t hop_count GNUNET_PACKED;
157
158   /**
159    * Purpose.
160    */
161   struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
162
163   /**
164    * The current timestamp value (which all
165    * peers should agree on).
166    */
167   struct GNUNET_TIME_AbsoluteNBO timestamp;
168
169   /**
170    * Number of matching bits between the hash
171    * of timestamp and the initiator's public
172    * key.
173    */
174   uint32_t matching_bits GNUNET_PACKED;
175
176   /**
177    * Public key of the originator.
178    */
179   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
180
181   /**
182    * Proof of work, causing leading zeros when hashed with pkey.
183    */
184   uint64_t proof_of_work GNUNET_PACKED;
185
186   /**
187    * Signature (over range specified in purpose).
188    */
189   struct GNUNET_CRYPTO_RsaSignature signature;
190 };
191
192
193 /**
194  * Handle to our current configuration.
195  */
196 static const struct GNUNET_CONFIGURATION_Handle *cfg;
197
198 /**
199  * Handle to the statistics service.
200  */
201 static struct GNUNET_STATISTICS_Handle *stats;
202
203 /**
204  * Handle to the core service.
205  */
206 static struct GNUNET_CORE_Handle *coreAPI;
207
208 /**
209  * Map of all connected peers.
210  */
211 static struct GNUNET_CONTAINER_MultiHashMap *peers;
212
213 /**
214  * The current network size estimate.  Number of bits matching on
215  * average thus far.
216  */
217 static double current_size_estimate;
218
219 /**
220  * The standard deviation of the last HISTORY_SIZE network
221  * size estimates.
222  */
223 static double current_std_dev = NAN;
224
225 /**
226  * Current hop counter estimate (estimate for network diameter).
227  */
228 static uint32_t hop_count_max;
229
230 /**
231  * Message for the next round, if we got any.
232  */
233 static struct GNUNET_NSE_FloodMessage next_message;
234
235 /**
236  * Array of recent size estimate messages.
237  */
238 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
239
240 /**
241  * Index of most recent estimate.
242  */
243 static unsigned int estimate_index;
244
245 /**
246  * Number of valid entries in the history.
247  */
248 static unsigned int estimate_count;
249
250 /**
251  * Task scheduled to update our flood message for the next round.
252  */
253 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
254
255 /**
256  * Task scheduled to compute our proof.
257  */
258 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
259
260 /**
261  * Notification context, simplifies client broadcasts.
262  */
263 static struct GNUNET_SERVER_NotificationContext *nc;
264
265 /**
266  * The next major time.
267  */
268 static struct GNUNET_TIME_Absolute next_timestamp;
269
270 /**
271  * The current major time.
272  */
273 static struct GNUNET_TIME_Absolute current_timestamp;
274
275 /**
276  * The public key of this peer.
277  */
278 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
279
280 /**
281  * The private key of this peer.
282  */
283 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
284
285 /**
286  * The peer identity of this peer.
287  */
288 static struct GNUNET_PeerIdentity my_identity;
289
290 /**
291  * Proof of work for this peer.
292  */
293 static uint64_t my_proof;
294
295
296 /**
297  * Initialize a message to clients with the current network
298  * size estimate.
299  *
300  * @param em message to fill in
301  */
302 static void
303 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
304 {
305   unsigned int i;
306   unsigned int j;
307   double mean;
308   double sum;
309   double std_dev;
310   double variance;
311   double val;
312   double nsize;
313
314   /* Weighted incremental algorithm for stddev according to West (1979) */
315 #if WEST
316   double sumweight;
317   double weight;
318   double q;
319   double r;
320   double temp;
321
322   mean = 0.0;
323   sum = 0.0;
324   sumweight = 0.0;
325   for (i = 0; i < estimate_count; i++)
326   {
327     j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
328     val = htonl (size_estimate_messages[j].matching_bits);
329     weight = 1.0;              /* was: estimate_count + 1 - i; */
330
331     temp = weight + sumweight;
332     q = val - mean;
333     r = q * weight / temp;
334     mean += r;
335     sum += sumweight * q * r;
336     sumweight = temp;
337   }
338   if (estimate_count > 0)
339     variance = (sum / sumweight) * estimate_count / (estimate_count - 1.0);
340 #else
341   /* trivial version for debugging */
342   double vsq;
343
344   /* non-weighted trivial version */
345   sum = 0.0;
346   vsq = 0.0;
347   variance = 0.0;
348   mean = 0.0;
349
350   for (i = 0; i < estimate_count; i++)
351   {
352     j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
353     val = htonl (size_estimate_messages[j].matching_bits);
354     sum += val;
355     vsq += val * val;
356   }
357   if (0 != estimate_count)
358   {
359     mean = sum / estimate_count;
360     variance = (vsq - mean * sum) / (estimate_count - 1.0); // terrible for numerical stability...
361     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
362                 "(%f - %f) / %u = %f\n", 
363                 vsq, mean * sum, estimate_count - 1, variance);
364
365   }
366 #endif
367   GNUNET_assert (variance >= 0);
368   std_dev = sqrt (variance);
369   current_std_dev = std_dev;
370   current_size_estimate = mean;
371
372   em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage));
373   em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
374   em->reserved = htonl (0);
375   em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
376   em->size_estimate = mean - 0.332747;
377   nsize = log2 (GNUNET_CONTAINER_multihashmap_size (peers) + 1);
378   if (em->size_estimate < nsize)
379     em->size_estimate = nsize;
380   em->std_deviation = std_dev;
381   GNUNET_STATISTICS_set (stats, "# nodes in the network (estimate)",
382                          (uint64_t) pow (2, mean - 1.0 / 3.0), GNUNET_NO);
383 }
384
385
386 /**
387  * Handler for START message from client, triggers an
388  * immediate current network estimate notification.
389  * Also, we remember the client for updates upon future
390  * estimate measurements.
391  *
392  * @param cls unused
393  * @param client who sent the message
394  * @param message the message received
395  */
396 static void
397 handle_start_message (void *cls, struct GNUNET_SERVER_Client *client,
398                       const struct GNUNET_MessageHeader *message)
399 {
400   struct GNUNET_NSE_ClientMessage em;
401
402 #if DEBUG_NSE
403   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n");
404 #endif
405   GNUNET_SERVER_notification_context_add (nc, client);
406   setup_estimate_message (&em);
407   GNUNET_SERVER_notification_context_unicast (nc, client, &em.header,
408                                               GNUNET_YES);
409   GNUNET_SERVER_receive_done (client, GNUNET_OK);
410 }
411
412
413 /**
414  * How long should we delay a message to go the given number of
415  * matching bits?
416  *
417  * @param matching_bits number of matching bits to consider
418  */
419 static double
420 get_matching_bits_delay (uint32_t matching_bits)
421 {
422   /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */
423   // S is next_timestamp (ignored in return value)
424   // f is frequency (gnunet_nse_interval)
425   // x is matching_bits
426   // p' is current_size_estimate
427   return ((double) gnunet_nse_interval.rel_value / (double) 2.0) -
428       ((gnunet_nse_interval.rel_value / M_PI) *
429        atan (matching_bits - current_size_estimate));
430 }
431
432
433 /**
434  * What delay randomization should we apply for a given number of matching bits?
435  *
436  * @param matching_bits number of matching bits
437  * @return random delay to apply
438  */
439 static struct GNUNET_TIME_Relative
440 get_delay_randomization (uint32_t matching_bits)
441 {
442 #if USE_RANDOM_DELAYS
443   struct GNUNET_TIME_Relative ret;
444
445   if (matching_bits == 0)
446     return GNUNET_TIME_UNIT_ZERO;
447   ret.rel_value =
448       GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
449                                 (uint32_t) (get_matching_bits_delay
450                                             (matching_bits -
451                                              1) / (double) (hop_count_max +
452                                                             1)));
453   return ret;
454 #else
455   return GNUNET_TIME_UNIT_ZERO;
456 #endif
457 }
458
459
460 /**
461  * Get the number of matching bits that the given timestamp has to the given peer ID.
462  *
463  * @param timestamp time to generate key
464  * @param id peer identity to compare with
465  * @return number of matching bits
466  */
467 static uint32_t
468 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
469                    const struct GNUNET_PeerIdentity *id)
470 {
471   GNUNET_HashCode timestamp_hash;
472
473   GNUNET_CRYPTO_hash (&timestamp.abs_value, sizeof (timestamp.abs_value),
474                       &timestamp_hash);
475   return GNUNET_CRYPTO_hash_matching_bits (&timestamp_hash, &id->hashPubKey);
476 }
477
478
479 /**
480  * Get the transmission delay that should be applied for a
481  * particular round.
482  *
483  * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
484  *                      0 for the current round (based on our proximity to time key)
485  * @return delay that should be applied
486  */
487 static struct GNUNET_TIME_Relative
488 get_transmit_delay (int round_offset)
489 {
490   struct GNUNET_TIME_Relative ret;
491   struct GNUNET_TIME_Absolute tgt;
492   double dist_delay;
493   uint32_t matching_bits;
494
495   switch (round_offset)
496   {
497   case -1:
498     /* previous round is randomized between 0 and 50 ms */
499 #if USE_RANDOM_DELAYS
500     ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
501 #else
502     ret = GNUNET_TIME_UNIT_ZERO;
503 #endif
504 #if DEBUG_NSE
505     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
506                 "Transmitting previous round behind schedule in %llu ms\n",
507                 (unsigned long long) ret.rel_value);
508 #endif
509     return ret;
510   case 0:
511     /* current round is based on best-known matching_bits */
512     matching_bits =
513         ntohl (size_estimate_messages[estimate_index].matching_bits);
514     dist_delay = get_matching_bits_delay (matching_bits);
515     dist_delay += get_delay_randomization (matching_bits).rel_value;
516     ret.rel_value = (uint64_t) dist_delay;
517 #if DEBUG_NSE
518     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
519                 "For round %llu, delay for %u matching bits is %llu ms\n",
520                 (unsigned long long) current_timestamp.abs_value,
521                 (unsigned int) matching_bits,
522                 (unsigned long long) ret.rel_value);
523 #endif
524     /* now consider round start time and add delay to it */
525     tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
526     return GNUNET_TIME_absolute_get_remaining (tgt);
527   }
528   GNUNET_break (0);
529   return GNUNET_TIME_UNIT_FOREVER_REL;
530 }
531
532
533 /**
534  * Task that triggers a NSE P2P transmission.
535  *
536  * @param cls the 'struct NSEPeerEntry'
537  * @param tc scheduler context
538  */
539 static void
540 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
541
542
543 /**
544  * Called when core is ready to send a message we asked for
545  * out to the destination.
546  *
547  * @param cls closure (NULL)
548  * @param size number of bytes available in buf
549  * @param buf where the callee should write the message
550  * @return number of bytes written to buf
551  */
552 static size_t
553 transmit_ready (void *cls, size_t size, void *buf)
554 {
555   struct NSEPeerEntry *peer_entry = cls;
556   unsigned int idx;
557
558   peer_entry->th = NULL;
559   if (buf == NULL)
560   {
561     /* client disconnected */
562     return 0;
563   }
564   GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
565   idx = estimate_index;
566   if (peer_entry->previous_round == GNUNET_NO)
567   {
568     idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
569     peer_entry->previous_round = GNUNET_YES;
570     peer_entry->transmit_task =
571         GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), &transmit_task,
572                                       peer_entry);
573   }
574   if ((ntohl (size_estimate_messages[idx].hop_count) == 0) &&
575       (GNUNET_SCHEDULER_NO_TASK != proof_task))
576   {
577     GNUNET_STATISTICS_update (stats,
578                               "# flood messages not generated (no proof yet)",
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   GNUNET_assert (GNUNET_OK ==
669                  GNUNET_CRYPTO_rsa_sign (my_private_key, &fm->purpose,
670                                          &fm->signature));
671 }
672
673
674 /**
675  * Schedule transmission for the given peer for the current round based
676  * on what we know about the desired delay.
677  *
678  * @param cls unused
679  * @param key hash of peer identity
680  * @param value the 'struct NSEPeerEntry'
681  * @return GNUNET_OK (continue to iterate)
682  */
683 static int
684 schedule_current_round (void *cls, const GNUNET_HashCode * key, void *value)
685 {
686   struct NSEPeerEntry *peer_entry = value;
687   struct GNUNET_TIME_Relative delay;
688
689   if (peer_entry->th != NULL)
690   {
691     peer_entry->previous_round = GNUNET_NO;
692     return GNUNET_OK;
693   }
694   if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
695   {
696     GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
697     peer_entry->previous_round = GNUNET_NO;
698   }
699   delay =
700       get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
701   peer_entry->transmit_task =
702       GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
703   return GNUNET_OK;
704 }
705
706
707 /**
708  * Update our flood message to be sent (and our timestamps).
709  *
710  * @param cls unused
711  * @param tc context for this message
712  */
713 static void
714 update_flood_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
715 {
716   struct GNUNET_TIME_Relative offset;
717   unsigned int i;
718
719   flood_task = GNUNET_SCHEDULER_NO_TASK;
720   offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
721   if (0 != offset.rel_value)
722   {
723     /* somehow run early, delay more */
724     flood_task =
725         GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL);
726     return;
727   }
728   current_timestamp = next_timestamp;
729   next_timestamp =
730       GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
731   estimate_index = (estimate_index + 1) % HISTORY_SIZE;
732   if (estimate_count < HISTORY_SIZE)
733     estimate_count++;
734   if (next_timestamp.abs_value ==
735       GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
736   {
737     /* we received a message for this round way early, use it! */
738     size_estimate_messages[estimate_index] = next_message;
739     size_estimate_messages[estimate_index].hop_count =
740         htonl (1 + ntohl (next_message.hop_count));
741   }
742   else
743     setup_flood_message (estimate_index, current_timestamp);
744   next_message.matching_bits = htonl (0);       /* reset for 'next' round */
745   hop_count_max = 0;
746   for (i = 0; i < HISTORY_SIZE; i++)
747     hop_count_max =
748         GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max);
749   GNUNET_CONTAINER_multihashmap_iterate (peers, &schedule_current_round, NULL);
750   flood_task =
751       GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
752                                     (next_timestamp), &update_flood_message,
753                                     NULL);
754 }
755
756
757 /**
758  * Count the leading zeroes in hash.
759  *
760  * @param hash
761  * @return the number of leading zero bits.
762  */
763 static unsigned int
764 count_leading_zeroes (const GNUNET_HashCode * hash)
765 {
766   unsigned int hash_count;
767
768   hash_count = 0;
769   while ((0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)))
770     hash_count++;
771   return hash_count;
772 }
773
774
775 /**
776  * Check whether the given public key
777  * and integer are a valid proof of work.
778  *
779  * @param pkey the public key
780  * @param val the integer
781  *
782  * @return GNUNET_YES if valid, GNUNET_NO if not
783  */
784 static int
785 check_proof_of_work (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
786                      uint64_t val)
787 {
788   char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
789            sizeof (val)];
790   GNUNET_HashCode result;
791
792   memcpy (buf, &val, sizeof (val));
793   memcpy (&buf[sizeof (val)], pkey,
794           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
795   GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
796   return (count_leading_zeroes (&result) >=
797           nse_work_required) ? GNUNET_YES : GNUNET_NO;
798 }
799
800
801 /**
802  * Write our current proof to disk.
803  */
804 static void
805 write_proof ()
806 {
807   char *proof;
808
809   if (GNUNET_OK !=
810       GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
811     return;
812   if (sizeof (my_proof) !=
813       GNUNET_DISK_fn_write (proof, &my_proof, sizeof (my_proof),
814                             GNUNET_DISK_PERM_USER_READ |
815                             GNUNET_DISK_PERM_USER_WRITE))
816     GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof);
817   GNUNET_free (proof);
818
819 }
820
821
822 /**
823  * Find our proof of work.
824  *
825  * @param cls closure (unused)
826  * @param tc task context
827  */
828 static void
829 find_proof (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
830 {
831 #define ROUND_SIZE 10
832   uint64_t counter;
833   char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
834            sizeof (uint64_t)];
835   GNUNET_HashCode result;
836   unsigned int i;
837
838   proof_task = GNUNET_SCHEDULER_NO_TASK;
839   memcpy (&buf[sizeof (uint64_t)], &my_public_key,
840           sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
841   i = 0;
842   counter = my_proof;
843   while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
844   {
845     memcpy (buf, &counter, sizeof (uint64_t));
846     GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
847     if (nse_work_required <= count_leading_zeroes (&result))
848     {
849       my_proof = counter;
850 #if DEBUG_NSE
851       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Proof of work found: %llu!\n",
852                   (unsigned long long) GNUNET_ntohll (counter));
853 #endif
854       for (i = 0; i < HISTORY_SIZE; i++)
855         if (ntohl (size_estimate_messages[i].hop_count) == 0)
856         {
857           size_estimate_messages[i].proof_of_work = my_proof;
858           GNUNET_assert (GNUNET_OK ==
859                          GNUNET_CRYPTO_rsa_sign (my_private_key,
860                                                  &size_estimate_messages
861                                                  [i].purpose,
862                                                  &size_estimate_messages
863                                                  [i].signature));
864         }
865       write_proof ();
866       return;
867     }
868     counter++;
869     i++;
870   }
871   if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
872   {
873 #if DEBUG_NSE
874     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Testing proofs currently at %llu\n",
875                 (unsigned long long) counter);
876 #endif
877     /* remember progress every 100 rounds */
878     my_proof = counter;
879     write_proof ();
880   }
881   else
882   {
883     my_proof = counter;
884   }
885   proof_task =
886       GNUNET_SCHEDULER_add_delayed (proof_find_delay, &find_proof, NULL);
887 }
888
889
890 /**
891  * An incoming flood message has been received which claims
892  * to have more bits matching than any we know in this time
893  * period.  Verify the signature and/or proof of work.
894  *
895  * @param incoming_flood the message to verify
896  *
897  * @return GNUNET_YES if the message is verified
898  *         GNUNET_NO if the key/signature don't verify
899  */
900 static int
901 verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
902 {
903   if (GNUNET_YES !=
904       check_proof_of_work (&incoming_flood->pkey,
905                            incoming_flood->proof_of_work))
906   {
907     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Proof of work invalid: %llu!\n"),
908                 (unsigned long long)
909                 GNUNET_ntohll (incoming_flood->proof_of_work));
910     GNUNET_break_op (0);
911     return GNUNET_NO;
912   }
913   if (GNUNET_OK !=
914       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
915                                 &incoming_flood->purpose,
916                                 &incoming_flood->signature,
917                                 &incoming_flood->pkey))
918   {
919     GNUNET_break_op (0);
920     return GNUNET_NO;
921   }
922   return GNUNET_YES;
923 }
924
925
926 /**
927  * Update transmissions for the given peer for the current round based
928  * on updated proximity information.
929  *
930  * @param cls peer entry to exclude from updates
931  * @param key hash of peer identity
932  * @param value the 'struct NSEPeerEntry'
933  * @return GNUNET_OK (continue to iterate)
934  */
935 static int
936 update_flood_times (void *cls, const GNUNET_HashCode * key, void *value)
937 {
938   struct NSEPeerEntry *exclude = cls;
939   struct NSEPeerEntry *peer_entry = value;
940   struct GNUNET_TIME_Relative delay;
941
942   if (peer_entry->th != NULL)
943     return GNUNET_OK;           /* already active */
944   if (peer_entry == exclude)
945     return GNUNET_OK;           /* trigger of the update */
946   if (peer_entry->previous_round == GNUNET_NO)
947   {
948     /* still stuck in previous round, no point to update, check that
949      * we are active here though... */
950     GNUNET_break ((peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
951                   (peer_entry->th != NULL));
952     return GNUNET_OK;
953   }
954   if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
955   {
956     GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
957     peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
958   }
959   delay = get_transmit_delay (0);
960   peer_entry->transmit_task =
961       GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
962   return GNUNET_OK;
963 }
964
965
966 /**
967  * Core handler for size estimate flooding messages.
968  *
969  * @param cls closure unused
970  * @param message message
971  * @param peer peer identity this message is from (ignored)
972  * @param atsi performance data (ignored)
973  * @param atsi_count number of records in 'atsi'
974  */
975 static int
976 handle_p2p_size_estimate (void *cls, const struct GNUNET_PeerIdentity *peer,
977                           const struct GNUNET_MessageHeader *message,
978                           const struct GNUNET_ATS_Information *atsi,
979                           unsigned int atsi_count)
980 {
981   const struct GNUNET_NSE_FloodMessage *incoming_flood;
982   struct GNUNET_TIME_Absolute ts;
983   struct NSEPeerEntry *peer_entry;
984   uint32_t matching_bits;
985   unsigned int idx;
986
987 #if ENABLE_HISTOGRAM
988   if (NULL != wh)
989     GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
990 #endif
991   incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
992   GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
993   matching_bits = ntohl (incoming_flood->matching_bits);
994 #if DEBUG_NSE
995   {
996     char origin[5];
997     char pred[5];
998     struct GNUNET_PeerIdentity os;
999
1000     GNUNET_CRYPTO_hash (&incoming_flood->pkey,
1001                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1002                         &os.hashPubKey);
1003     GNUNET_snprintf (origin, sizeof (origin), "%s", GNUNET_i2s (&os));
1004     GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer));
1005     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1006                 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
1007                 (unsigned long long)
1008                 GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1009                 origin, pred, GNUNET_i2s (&my_identity),
1010                 (unsigned int) matching_bits);
1011   }
1012 #endif
1013
1014   peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1015   if (NULL == peer_entry)
1016   {
1017     GNUNET_break (0);
1018     return GNUNET_OK;
1019   }
1020
1021   ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1022
1023   if (ts.abs_value == current_timestamp.abs_value)
1024     idx = estimate_index;
1025   else if (ts.abs_value ==
1026            current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1027     idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1028   else if (ts.abs_value ==
1029            next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1030   {
1031     if (matching_bits <= ntohl (next_message.matching_bits))
1032       return GNUNET_OK;         /* ignore, simply too early/late */
1033     if (GNUNET_YES != verify_message_crypto (incoming_flood))
1034     {
1035       GNUNET_break_op (0);
1036       return GNUNET_OK;
1037     }
1038     next_message = *incoming_flood;
1039     return GNUNET_OK;
1040   }
1041   else
1042   {
1043     GNUNET_STATISTICS_update (stats,
1044                               "# flood messages discarded (clock skew too large)",
1045                               1, GNUNET_NO);
1046     return GNUNET_OK;
1047   }
1048   if (0 == (memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity))))
1049   {
1050     /* send to self, update our own estimate IF this also comes from us! */
1051     if (0 ==
1052         memcmp (&incoming_flood->pkey, &my_public_key, sizeof (my_public_key)))
1053       update_network_size_estimate ();
1054     return GNUNET_OK;
1055   }
1056   if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1057   {
1058     /* cancel transmission from us to this peer for this round */
1059     if (idx == estimate_index)
1060     {
1061       if (peer_entry->previous_round == GNUNET_YES)
1062       {
1063         /* cancel any activity for current round */
1064         if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1065         {
1066           GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1067           peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1068         }
1069         if (peer_entry->th != NULL)
1070         {
1071           GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1072           peer_entry->th = NULL;
1073         }
1074       }
1075     }
1076     else
1077     {
1078       /* cancel previous round only */
1079       peer_entry->previous_round = GNUNET_YES;
1080     }
1081   }
1082   if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1083     return GNUNET_OK;
1084   if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1085   {
1086     if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
1087       peer_entry->previous_round = GNUNET_NO;
1088     /* push back our result now, that peer is spreading bad information... */
1089     if (NULL == peer_entry->th)
1090     {
1091       if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1092         GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1093       peer_entry->transmit_task =
1094           GNUNET_SCHEDULER_add_now (&transmit_task, peer_entry);
1095     }
1096     /* Not closer than our most recent message, no need to do work here */
1097     GNUNET_STATISTICS_update (stats,
1098                               "# flood messages ignored (had closer already)",
1099                               1, GNUNET_NO);
1100     return GNUNET_OK;
1101   }
1102   if (GNUNET_YES != verify_message_crypto (incoming_flood))
1103   {
1104     GNUNET_break_op (0);
1105     return GNUNET_OK;
1106   }
1107   size_estimate_messages[idx] = *incoming_flood;
1108   size_estimate_messages[idx].hop_count =
1109       htonl (ntohl (incoming_flood->hop_count) + 1);
1110   hop_count_max =
1111       GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
1112
1113   /* have a new, better size estimate, inform clients */
1114   update_network_size_estimate ();
1115
1116   /* flood to rest */
1117   GNUNET_CONTAINER_multihashmap_iterate (peers, &update_flood_times,
1118                                          peer_entry);
1119   return GNUNET_OK;
1120 }
1121
1122
1123
1124 /**
1125  * Method called whenever a peer connects.
1126  *
1127  * @param cls closure
1128  * @param peer peer identity this notification is about
1129  * @param atsi performance data
1130  * @param atsi_count number of records in 'atsi'
1131  */
1132 static void
1133 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
1134                      const struct GNUNET_ATS_Information *atsi,
1135                      unsigned int atsi_count)
1136 {
1137   struct NSEPeerEntry *peer_entry;
1138
1139 #if DEBUG_NSE
1140   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' connected to us\n",
1141               GNUNET_i2s (peer));
1142 #endif
1143   peer_entry = GNUNET_malloc (sizeof (struct NSEPeerEntry));
1144   peer_entry->id = *peer;
1145   GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_entry,
1146                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1147   peer_entry->transmit_task =
1148       GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), &transmit_task,
1149                                     peer_entry);
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 }
1186
1187
1188 /**
1189  * Task run during shutdown.
1190  *
1191  * @param cls unused
1192  * @param tc unused
1193  */
1194 static void
1195 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1196 {
1197   if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1198   {
1199     GNUNET_SCHEDULER_cancel (flood_task);
1200     flood_task = GNUNET_SCHEDULER_NO_TASK;
1201   }
1202   if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1203   {
1204     GNUNET_SCHEDULER_cancel (proof_task);
1205     proof_task = GNUNET_SCHEDULER_NO_TASK;
1206     write_proof ();             /* remember progress */
1207   }
1208   if (nc != NULL)
1209   {
1210     GNUNET_SERVER_notification_context_destroy (nc);
1211     nc = NULL;
1212   }
1213   if (coreAPI != NULL)
1214   {
1215     GNUNET_CORE_disconnect (coreAPI);
1216     coreAPI = NULL;
1217   }
1218   if (stats != NULL)
1219   {
1220     GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1221     stats = NULL;
1222   }
1223   if (peers != NULL)
1224   {
1225     GNUNET_CONTAINER_multihashmap_destroy (peers);
1226     peers = NULL;
1227   }
1228   if (my_private_key != NULL)
1229   {
1230     GNUNET_CRYPTO_rsa_key_free (my_private_key);
1231     my_private_key = NULL;
1232   }
1233 #if ENABLE_HISTOGRAM
1234   if (wh != NULL)
1235   {
1236     GNUNET_BIO_write_close (wh);
1237     wh = NULL;
1238   }
1239 #endif
1240 }
1241
1242
1243 /**
1244  * Called on core init/fail.
1245  *
1246  * @param cls service closure
1247  * @param server handle to the server for this service
1248  * @param identity the public identity of this peer
1249  */
1250 static void
1251 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1252            const struct GNUNET_PeerIdentity *identity)
1253 {
1254   struct GNUNET_TIME_Absolute now;
1255   struct GNUNET_TIME_Absolute prev_time;
1256   unsigned int i;
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
1276   for (i = 0; i < HISTORY_SIZE; i++)
1277   {
1278     prev_time.abs_value =
1279         current_timestamp.abs_value - (HISTORY_SIZE - i -
1280                                        1) * gnunet_nse_interval.rel_value;
1281     setup_flood_message (i, prev_time);
1282   }
1283   estimate_index = HISTORY_SIZE - 1;
1284   estimate_count = 2;
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                                  CORE_QUEUE_SIZE,       /* queue size */
1394                                  NULL,  /* Closure passed to functions */
1395                                  &core_init,    /* Call core_init once connected */
1396                                  &handle_core_connect,  /* Handle connects */
1397                                  &handle_core_disconnect,       /* Handle disconnects */
1398                                  NULL,  /* Don't want notified about all incoming messages */
1399                                  GNUNET_NO,     /* For header only inbound notification */
1400                                  NULL,  /* Don't want notified about all outbound messages */
1401                                  GNUNET_NO,     /* For header only outbound notification */
1402                                  core_handlers);        /* Register these handlers */
1403   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1404                                 NULL);
1405 #if ENABLE_HISTOGRAM
1406   if (GNUNET_OK ==
1407       GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "HISTOGRAM", &proof))
1408   {
1409     wh = GNUNET_BIO_write_open (proof);
1410     GNUNET_free (proof);
1411   }
1412 #endif
1413   if (coreAPI == NULL)
1414   {
1415     GNUNET_SCHEDULER_shutdown ();
1416     return;
1417   }
1418   stats = GNUNET_STATISTICS_create ("nse", cfg);
1419 }
1420
1421
1422 /**
1423  * The main function for the statistics service.
1424  *
1425  * @param argc number of arguments from the command line
1426  * @param argv command line arguments
1427  * @return 0 ok, 1 on error
1428  */
1429 int
1430 main (int argc, char *const *argv)
1431 {
1432   return (GNUNET_OK ==
1433           GNUNET_SERVICE_run (argc, argv, "nse", GNUNET_SERVICE_OPTION_NONE,
1434                               &run, NULL)) ? 0 : 1;
1435 }
1436
1437 /* end of gnunet-service-nse.c */