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