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