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