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