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