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