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