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