generate histograms
[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 - 0.5;
330   em->std_deviation = std_dev;
331   GNUNET_STATISTICS_set (stats, 
332                          "# nodes in the network (estimate)",
333                          (uint64_t) pow (2, mean - 0.5), 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           GNUNET_log (GNUNET_ERROR_TYPE_INFO,
818                       _("Proof of work found: %llu!\n"),
819                       (unsigned long long) GNUNET_ntohll (counter));
820           for (i=0;i<HISTORY_SIZE;i++)      
821             if (ntohl (size_estimate_messages[i].hop_count) == 0) 
822               {
823                 size_estimate_messages[i].proof_of_work = my_proof;
824                 GNUNET_CRYPTO_rsa_sign (my_private_key, 
825                                         &size_estimate_messages[i].purpose,
826                                         &size_estimate_messages[i].signature);
827               }
828           write_proof ();
829           return;
830         }
831       counter++;
832       i++;
833     }
834   if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
835     {
836 #if DEBUG_NSE
837       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
838                   "Testing proofs currently at %llu\n",
839                   (unsigned long long) counter);
840 #endif
841       /* remember progress every 100 rounds */
842       my_proof = counter;
843       write_proof (); 
844     }
845   else
846     {
847       my_proof = counter;
848     }
849   proof_task = GNUNET_SCHEDULER_add_delayed (proof_find_delay,
850                                              &find_proof,
851                                              NULL);
852 }
853
854
855 /**
856  * An incoming flood message has been received which claims
857  * to have more bits matching than any we know in this time
858  * period.  Verify the signature and/or proof of work.
859  *
860  * @param incoming_flood the message to verify
861  *
862  * @return GNUNET_YES if the message is verified
863  *         GNUNET_NO if the key/signature don't verify
864  */
865 static int 
866 verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood)
867 {
868   if (GNUNET_YES !=
869       check_proof_of_work (&incoming_flood->pkey,
870                            incoming_flood->proof_of_work))
871     {
872       GNUNET_log (GNUNET_ERROR_TYPE_INFO,
873                   _("Proof of work invalid: %llu!\n"),
874                   (unsigned long long) GNUNET_ntohll (incoming_flood->proof_of_work));
875       GNUNET_break_op (0);
876       return GNUNET_NO;
877     }
878   if (GNUNET_OK != 
879       GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
880                                 &incoming_flood->purpose,
881                                 &incoming_flood->signature,
882                                 &incoming_flood->pkey))
883     {
884       GNUNET_break_op (0);
885       return GNUNET_NO;
886     }
887   return GNUNET_YES;
888 }
889
890
891 /**
892  * Update transmissions for the given peer for the current round based
893  * on updated proximity information.
894  *
895  * @param cls peer entry to exclude from updates
896  * @param key hash of peer identity
897  * @param value the 'struct NSEPeerEntry'
898  * @return GNUNET_OK (continue to iterate)
899  */
900 static int
901 update_flood_times (void *cls,
902                     const GNUNET_HashCode *key,
903                     void *value)
904 {
905   struct NSEPeerEntry *exclude = cls;
906   struct NSEPeerEntry *peer_entry = value;
907   struct GNUNET_TIME_Relative delay;
908
909   if (peer_entry->th != NULL)
910     return GNUNET_OK; /* already active */
911   if (peer_entry == exclude)
912     return GNUNET_OK; /* trigger of the update */
913   if (peer_entry->previous_round == GNUNET_NO)
914     {
915       /* still stuck in previous round, no point to update, check that 
916          we are active here though... */
917       GNUNET_break (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK);
918       return GNUNET_OK; 
919     }
920   if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
921     {
922       GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
923       peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
924     }
925   delay = get_transmit_delay (0);
926   peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
927                                                             &transmit_task,
928                                                             peer_entry);
929   return GNUNET_OK;
930 }
931
932
933 /**
934  * Core handler for size estimate flooding messages.
935  *
936  * @param cls closure unused
937  * @param message message
938  * @param peer peer identity this message is from (ignored)
939  * @param atsi performance data (ignored)
940  *
941  */
942 static int
943 handle_p2p_size_estimate(void *cls, 
944                          const struct GNUNET_PeerIdentity *peer,
945                          const struct GNUNET_MessageHeader *message,
946                          const struct GNUNET_TRANSPORT_ATS_Information *atsi)
947 {
948   const struct GNUNET_NSE_FloodMessage *incoming_flood;
949   struct GNUNET_TIME_Absolute ts;
950   struct NSEPeerEntry *peer_entry;
951   uint32_t matching_bits;  
952   unsigned int idx;
953
954 #if ENABLE_HISTOGRAM
955   if (NULL != wh)
956     GNUNET_BIO_write_int64 (wh, GNUNET_htonll (GNUNET_TIME_absolute_get ().abs_value));
957 #endif
958   incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
959   GNUNET_STATISTICS_update (stats, 
960                             "# flood messages received", 
961                             1,
962                             GNUNET_NO);
963   matching_bits = ntohl (incoming_flood->matching_bits);
964 #if DEBUG_NSE
965   {
966     char origin[5];
967     char pred[5];
968     struct GNUNET_PeerIdentity os;
969
970     GNUNET_CRYPTO_hash (&incoming_flood->pkey,
971                         sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
972                         &os.hashPubKey);
973     GNUNET_snprintf (origin, sizeof (origin),
974                      "%s",
975                      GNUNET_i2s (&os));
976     GNUNET_snprintf (pred, sizeof (pred),
977                      "%s",
978                      GNUNET_i2s (peer));
979     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980                 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
981                 (unsigned long long) GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
982                 origin,
983                 pred,
984                 GNUNET_i2s (&my_identity),
985                 (unsigned int) matching_bits);
986   }
987 #endif  
988
989   peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
990   if (NULL == peer_entry)
991     {
992       GNUNET_break (0);
993       return GNUNET_OK;
994     }
995   ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
996   if (ts.abs_value == current_timestamp.abs_value)
997     idx = estimate_index;
998   else if (ts.abs_value == current_timestamp.abs_value - gnunet_nse_interval.rel_value)
999     idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1000   else if (ts.abs_value == next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1001     {
1002       if (matching_bits <= ntohl (next_message.matching_bits))
1003         return GNUNET_OK; /* ignore, simply too early/late */
1004       if (GNUNET_YES !=
1005           verify_message_crypto (incoming_flood))
1006         {
1007           GNUNET_break_op (0);
1008           return GNUNET_OK;
1009         }
1010       next_message = *incoming_flood;
1011       return GNUNET_OK;
1012     }
1013   else
1014     {
1015       GNUNET_STATISTICS_update (stats,
1016                                 "# flood messages discarded (clock skew too large)",
1017                                 1,
1018                                 GNUNET_NO);
1019       GNUNET_break_op (0);
1020       return GNUNET_OK;
1021     }
1022   if (0 == (memcmp (peer, &my_identity, sizeof(struct GNUNET_PeerIdentity))))
1023     {
1024       /* send to self, update our own estimate IF this also comes from us! */
1025       if (0 == memcmp (&incoming_flood->pkey,
1026                        &my_public_key,
1027                        sizeof (my_public_key)))                
1028         update_network_size_estimate ();
1029       return GNUNET_OK; 
1030     }
1031   if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))        
1032     {      
1033       /* cancel transmission from us to this peer for this round */
1034       if (idx == estimate_index)
1035         {
1036           if (peer_entry->previous_round == GNUNET_YES)
1037             {
1038               /* cancel any activity for current round */
1039               if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1040                 {
1041                   GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1042                   peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1043                 }
1044               if (peer_entry->th != NULL)
1045                 {
1046                   GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1047                   peer_entry->th = NULL;
1048                 }
1049             }
1050         }
1051       else
1052         {
1053           /* cancel previous round only */
1054           peer_entry->previous_round = GNUNET_YES;
1055         } 
1056     }
1057   if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits)) 
1058     {
1059       /* Not closer than our most recent message, no need to do work here */
1060       GNUNET_STATISTICS_update (stats,
1061                                 "# flood messages ignored (had closer already)",
1062                                 1,
1063                                 GNUNET_NO);
1064       return GNUNET_OK;
1065     }
1066   if (GNUNET_YES !=
1067       verify_message_crypto (incoming_flood))
1068     {
1069       GNUNET_break_op (0);
1070       return GNUNET_OK;
1071     }
1072   size_estimate_messages[idx] = *incoming_flood;
1073   size_estimate_messages[idx].hop_count = htonl (ntohl (incoming_flood->hop_count) + 1);
1074   hop_count_max = GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
1075                               hop_count_max);
1076
1077   /* have a new, better size estimate, inform clients */
1078   update_network_size_estimate ();
1079
1080   /* flood to rest */
1081   GNUNET_CONTAINER_multihashmap_iterate (peers,
1082                                          &update_flood_times,
1083                                          peer_entry);
1084   return GNUNET_OK;
1085 }
1086
1087
1088
1089 /**
1090  * Method called whenever a peer connects.
1091  *
1092  * @param cls closure
1093  * @param peer peer identity this notification is about
1094  * @param atsi performance data
1095  */
1096 static void
1097 handle_core_connect(void *cls, const struct GNUNET_PeerIdentity *peer,
1098                     const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1099 {
1100   struct NSEPeerEntry *peer_entry;
1101
1102  #if DEBUG_NSE
1103   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
1104              "Peer `%s' connected to us\n",
1105              GNUNET_i2s (peer));
1106 #endif
1107   peer_entry = GNUNET_malloc(sizeof(struct NSEPeerEntry));
1108   peer_entry->id = *peer;
1109   GNUNET_CONTAINER_multihashmap_put (peers,
1110                                      &peer->hashPubKey,
1111                                      peer_entry,
1112                                      GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1113   peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
1114                                                             &transmit_task,
1115                                                             peer_entry);
1116 }
1117
1118
1119 /**
1120  * Method called whenever a peer disconnects.
1121  *
1122  * @param cls closure
1123  * @param peer peer identity this notification is about
1124  */
1125 static void
1126 handle_core_disconnect(void *cls, const struct GNUNET_PeerIdentity *peer)
1127 {
1128   struct NSEPeerEntry *pos;
1129
1130  #if DEBUG_NSE
1131   GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, 
1132              "Peer `%s' disconnected from us\n",
1133              GNUNET_i2s (peer));
1134 #endif
1135  pos = GNUNET_CONTAINER_multihashmap_get (peers,
1136                                            &peer->hashPubKey);
1137   if (NULL == pos)
1138     {
1139       GNUNET_break (0);
1140       return;
1141     }
1142   GNUNET_assert (GNUNET_YES ==
1143                  GNUNET_CONTAINER_multihashmap_remove (peers, 
1144                                                        &peer->hashPubKey,
1145                                                        pos));
1146   if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1147     GNUNET_SCHEDULER_cancel (pos->transmit_task);
1148   if (pos->th != NULL)
1149     GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1150   GNUNET_free(pos);
1151 }
1152
1153
1154 /**
1155  * Task run during shutdown.
1156  *
1157  * @param cls unused
1158  * @param tc unused
1159  */
1160 static void
1161 shutdown_task(void *cls,
1162               const struct GNUNET_SCHEDULER_TaskContext *tc)
1163 {
1164   if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1165     {
1166       GNUNET_SCHEDULER_cancel (flood_task);
1167       flood_task = GNUNET_SCHEDULER_NO_TASK;
1168     }
1169   if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1170     {
1171       GNUNET_SCHEDULER_cancel (proof_task);
1172       proof_task = GNUNET_SCHEDULER_NO_TASK;
1173       write_proof (); /* remember progress */
1174     }
1175   if (nc != NULL)
1176     {
1177       GNUNET_SERVER_notification_context_destroy (nc);
1178       nc = NULL;
1179     }
1180   if (coreAPI != NULL)
1181     {
1182       GNUNET_CORE_disconnect (coreAPI);
1183       coreAPI = NULL;
1184     }
1185   if (stats != NULL)
1186     {
1187       GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1188       stats = NULL;
1189     }
1190   if (peers != NULL)
1191     {
1192       GNUNET_CONTAINER_multihashmap_destroy (peers);
1193       peers = NULL;
1194     }
1195   if (my_private_key != NULL)
1196     {
1197       GNUNET_CRYPTO_rsa_key_free (my_private_key);
1198       my_private_key = NULL;
1199     }
1200 #if ENABLE_HISTOGRAM
1201   if (wh != NULL)
1202     {
1203       GNUNET_BIO_write_close (wh);
1204       wh = NULL;
1205     }
1206 #endif
1207 }
1208
1209
1210 /**
1211  * Called on core init/fail.
1212  *
1213  * @param cls service closure
1214  * @param server handle to the server for this service
1215  * @param identity the public identity of this peer
1216  * @param publicKey the public key of this peer
1217  */
1218 static void
1219 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1220            const struct GNUNET_PeerIdentity *identity,
1221            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1222 {
1223   struct GNUNET_TIME_Absolute now;
1224   struct GNUNET_TIME_Absolute prev_time;
1225   unsigned int i;
1226
1227   if (server == NULL)
1228     {
1229 #if DEBUG_NSE
1230       GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
1231                   "Connection to core FAILED!\n");
1232 #endif
1233       GNUNET_SCHEDULER_shutdown ();
1234       return;
1235     }
1236   GNUNET_assert (0 == memcmp (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity)));
1237   now = GNUNET_TIME_absolute_get ();
1238   current_timestamp.abs_value = (now.abs_value / gnunet_nse_interval.rel_value) * gnunet_nse_interval.rel_value;
1239   next_timestamp.abs_value = current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1240   
1241   for (i=0;i<HISTORY_SIZE;i++)
1242     {
1243       prev_time.abs_value = current_timestamp.abs_value - (HISTORY_SIZE - i - 1) * gnunet_nse_interval.rel_value;
1244       setup_flood_message (i, prev_time);
1245     }
1246   estimate_index = HISTORY_SIZE - 1;
1247   estimate_count = 2;
1248   flood_task
1249     = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
1250                                     &update_flood_message, NULL);
1251 }
1252
1253
1254 /**
1255  * Handle network size estimate clients.
1256  *
1257  * @param cls closure
1258  * @param server the initialized server
1259  * @param c configuration to use
1260  */
1261 static void
1262 run(void *cls, struct GNUNET_SERVER_Handle *server,
1263     const struct GNUNET_CONFIGURATION_Handle *c)
1264 {
1265   char *keyfile;
1266   char *proof;
1267
1268   static const struct GNUNET_SERVER_MessageHandler handlers[] =
1269     {
1270       { &handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START, sizeof (struct GNUNET_MessageHeader) },
1271       { NULL, NULL, 0, 0 } 
1272     };
1273   static const struct GNUNET_CORE_MessageHandler core_handlers[] =
1274     {
1275       { &handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, sizeof (struct GNUNET_NSE_FloodMessage) },
1276       { NULL, 0, 0 } 
1277     };
1278   cfg = c;
1279
1280   if ( (GNUNET_OK != 
1281         GNUNET_CONFIGURATION_get_value_time (cfg,
1282                                              "NSE", "INTERVAL",
1283                                              &gnunet_nse_interval)) ||
1284        (GNUNET_OK != 
1285         GNUNET_CONFIGURATION_get_value_time (cfg,
1286                                              "NSE", "WORKDELAY",
1287                                              &proof_find_delay)) ||
1288        (GNUNET_OK != 
1289         GNUNET_CONFIGURATION_get_value_number (cfg,
1290                                                "NSE", "WORKBITS",
1291                                                &nse_work_required)) )       
1292     {
1293       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1294                   _ ("NSE service is lacking key configuration settings.  Exiting.\n"));
1295       GNUNET_SCHEDULER_shutdown ();
1296       return;
1297     }
1298   if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1299     {
1300       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1301                   _ ("Invalid work requirement for NSE service. Exiting.\n"));
1302       GNUNET_SCHEDULER_shutdown ();
1303       return;
1304     }
1305
1306
1307   if (GNUNET_OK != 
1308       GNUNET_CONFIGURATION_get_value_filename (cfg,
1309                                                "GNUNETD", "HOSTKEY",
1310                                                &keyfile))
1311     {
1312       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1313                   _ ("NSE service is lacking key configuration settings.  Exiting.\n"));
1314       GNUNET_SCHEDULER_shutdown ();
1315       return;
1316     }
1317   my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1318   GNUNET_free (keyfile);
1319   if (my_private_key == NULL)
1320     {
1321       GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1322                   _("NSE service could not access hostkey.  Exiting.\n"));
1323       GNUNET_SCHEDULER_shutdown ();
1324       return;
1325     }
1326   GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1327   GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_identity.hashPubKey);
1328   if (GNUNET_OK != 
1329       GNUNET_CONFIGURATION_get_value_filename (cfg,
1330                                                "NSE", "PROOFFILE",
1331                                                &proof))
1332     {
1333       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 
1334                   _ ("NSE service is lacking key configuration settings.  Exiting.\n"));
1335       if (my_private_key != NULL)
1336         {
1337           GNUNET_CRYPTO_rsa_key_free (my_private_key);
1338           my_private_key = NULL;
1339         }
1340       GNUNET_SCHEDULER_shutdown ();
1341       return;
1342     }
1343   if ( (GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1344        (sizeof (my_proof) !=
1345         GNUNET_DISK_fn_read (proof,
1346                              &my_proof,
1347                              sizeof (my_proof))) )
1348     my_proof = 0; 
1349   GNUNET_free (proof);
1350   proof_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1351                                                    &find_proof,
1352                                                    NULL);
1353
1354   peers = GNUNET_CONTAINER_multihashmap_create (128);
1355   GNUNET_SERVER_add_handlers (server, handlers);
1356   nc = GNUNET_SERVER_notification_context_create (server, 1);
1357   /* Connect to core service and register core handlers */
1358   coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1359                                  CORE_QUEUE_SIZE, /* queue size */
1360                                  NULL, /* Closure passed to functions */
1361                                  &core_init, /* Call core_init once connected */
1362                                  &handle_core_connect, /* Handle connects */
1363                                  &handle_core_disconnect, /* Handle disconnects */
1364                                  NULL, /* Do we care about "status" updates? */
1365                                  NULL, /* Don't want notified about all incoming messages */
1366                                  GNUNET_NO, /* For header only inbound notification */
1367                                  NULL, /* Don't want notified about all outbound messages */
1368                                  GNUNET_NO, /* For header only outbound notification */
1369                                  core_handlers); /* Register these handlers */
1370   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1371                                 &shutdown_task, NULL);
1372 #if ENABLE_HISTOGRAM
1373   if (GNUNET_OK == 
1374       GNUNET_CONFIGURATION_get_value_filename (cfg,
1375                                                "NSE", "HISTOGRAM",
1376                                                &proof))
1377     {
1378       wh = GNUNET_BIO_write_open (proof);
1379       GNUNET_free (proof);
1380     }
1381 #endif
1382   if (coreAPI == NULL)
1383     {
1384       GNUNET_SCHEDULER_shutdown ();
1385       return;
1386     }
1387   stats = GNUNET_STATISTICS_create ("nse", cfg);
1388 }
1389
1390
1391 /**
1392  * The main function for the statistics service.
1393  *
1394  * @param argc number of arguments from the command line
1395  * @param argv command line arguments
1396  * @return 0 ok, 1 on error
1397  */
1398 int
1399 main(int argc, char * const *argv)
1400 {
1401   return (GNUNET_OK == GNUNET_SERVICE_run (argc, argv, 
1402                                            "nse",
1403                                            GNUNET_SERVICE_OPTION_NONE, &run,
1404                                            NULL)) ? 0 : 1;
1405 }
1406
1407 /* end of gnunet-service-nse.c */
1408