2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
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.
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.
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.
22 * @file nse/gnunet-service-nse.c
23 * @brief network size estimation service
24 * @author Nathan Evans
25 * @author Christian Grothoff
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.
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"
49 * Over how many values do we calculate the weighted average?
51 #define HISTORY_SIZE 8
54 * Size of the queue to core.
56 #define CORE_QUEUE_SIZE 2
59 * Message priority to use.
61 #define NSE_PRIORITY 5
64 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
66 static unsigned long long nse_work_required;
69 * Interval for sending network size estimation flood requests.
71 static struct GNUNET_TIME_Relative gnunet_nse_interval;
74 * Interval between proof find runs.
76 static struct GNUNET_TIME_Relative proof_find_delay;
80 * Per-peer information.
86 * Pending message for this peer.
88 struct GNUNET_MessageHeader *pending_message;
91 * Core handle for sending messages to this peer.
93 struct GNUNET_CORE_TransmitHandle *th;
96 * What is the identity of the peer?
98 struct GNUNET_PeerIdentity id;
101 * Task scheduled to send message to this peer.
103 GNUNET_SCHEDULER_TaskIdentifier transmit_task;
106 * Did we receive or send a message about the previous round
107 * to this peer yet? GNUNET_YES if the previous round has
108 * been taken care of.
115 * Network size estimate reply; sent when "this"
116 * peer's timer has run out before receiving a
117 * valid reply from another peer.
119 struct GNUNET_NSE_FloodMessage
122 * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
124 struct GNUNET_MessageHeader header;
127 * Number of hops this message has taken so far.
134 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
137 * The current timestamp value (which all
138 * peers should agree on).
140 struct GNUNET_TIME_AbsoluteNBO timestamp;
143 * Number of matching bits between the hash
144 * of timestamp and the initiator's public
147 uint32_t matching_bits;
150 * Public key of the originator.
152 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
155 * Proof of work, causing leading zeros when hashed with pkey.
157 uint64_t proof_of_work;
160 * Signature (over range specified in purpose).
162 struct GNUNET_CRYPTO_RsaSignature signature;
167 * Handle to our current configuration.
169 static const struct GNUNET_CONFIGURATION_Handle *cfg;
172 * Handle to the statistics service.
174 static struct GNUNET_STATISTICS_Handle *stats;
177 * Handle to the core service.
179 static struct GNUNET_CORE_Handle *coreAPI;
182 * Map of all connected peers.
184 static struct GNUNET_CONTAINER_MultiHashMap *peers;
187 * The current network size estimate. Number of bits matching on
190 static double current_size_estimate;
193 * The standard deviation of the last HISTORY_SIZE network
196 static double current_std_dev = NAN;
199 * Current hop counter estimate (estimate for network diameter).
201 static uint32_t hop_count_max;
204 * Message for the next round, if we got any.
206 static struct GNUNET_NSE_FloodMessage next_message;
209 * Array of recent size estimate messages.
211 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
214 * Index of most recent estimate.
216 static unsigned int estimate_index;
219 * Number of valid entries in the history.
221 static unsigned int estimate_count;
224 * Task scheduled to update our flood message for the next round.
226 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
229 * Task scheduled to compute our proof.
231 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
234 * Notification context, simplifies client broadcasts.
236 static struct GNUNET_SERVER_NotificationContext *nc;
239 * The next major time.
241 static struct GNUNET_TIME_Absolute next_timestamp;
244 * The current major time.
246 static struct GNUNET_TIME_Absolute current_timestamp;
249 * The public key of this peer.
251 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
254 * The private key of this peer.
256 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
259 * The peer identity of this peer.
261 static struct GNUNET_PeerIdentity my_identity;
264 * Proof of work for this peer.
266 static uint64_t my_proof;
270 * Initialize a message to clients with the current network
273 * @param em message to fill in
276 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
290 /* Weighted incremental algorithm for stddev according to West (1979) */
294 for (i=0;i<estimate_count; i++)
296 val = htonl (size_estimate_messages[(estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE].matching_bits);
297 weight = estimate_count + 1 - i;
299 temp = weight + sumweight;
301 r = q * weight / temp;
302 sum += sumweight * q * r;
306 variance = sum / (sumweight - 1.0);
307 GNUNET_assert (variance >= 0);
308 std_dev = sqrt (variance);
309 current_std_dev = std_dev;
310 current_size_estimate = mean;
313 = htons (sizeof(struct GNUNET_NSE_ClientMessage));
315 = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
316 em->reserved = htonl (0);
317 em->size_estimate = mean - 0.5;
318 em->std_deviation = std_dev;
319 GNUNET_STATISTICS_set (stats,
320 "# nodes in the network (estimate)",
321 (uint64_t) pow (2, mean - 0.5), GNUNET_NO);
326 * Handler for START message from client, triggers an
327 * immediate current network estimate notification.
328 * Also, we remember the client for updates upon future
329 * estimate measurements.
332 * @param client who sent the message
333 * @param message the message received
336 handle_start_message(void *cls, struct GNUNET_SERVER_Client *client,
337 const struct GNUNET_MessageHeader *message)
339 struct GNUNET_NSE_ClientMessage em;
342 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
343 "Received START message from client\n");
345 GNUNET_SERVER_notification_context_add (nc, client);
346 setup_estimate_message (&em);
347 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header, GNUNET_YES);
348 GNUNET_SERVER_receive_done (client, GNUNET_OK);
353 * How long should we delay a message to go the given number of
356 * @param matching_bits number of matching bits to consider
359 get_matching_bits_delay (uint32_t matching_bits)
361 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p'))*/
362 // S is next_timestamp (ignored in return value)
363 // f is frequency (gnunet_nse_interval)
364 // x is matching_bits
365 // p' is current_size_estimate
366 return ((double) gnunet_nse_interval.rel_value / (double) 2.0)
367 - ((gnunet_nse_interval.rel_value / M_PI) * atan (matching_bits - current_size_estimate));
372 * What delay randomization should we apply for a given number of matching bits?
374 * @param matching_bits number of matching bits
375 * @return random delay to apply
377 static struct GNUNET_TIME_Relative
378 get_delay_randomization (uint32_t matching_bits)
380 struct GNUNET_TIME_Relative ret;
382 if (matching_bits == 0)
383 return GNUNET_TIME_UNIT_ZERO;
384 ret.rel_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
385 (uint32_t) (get_matching_bits_delay (matching_bits - 1) / (double) (hop_count_max + 1)));
391 * Get the number of matching bits that the given timestamp has to the given peer ID.
393 * @param timestamp time to generate key
394 * @param id peer identity to compare with
395 * @return number of matching bits
398 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
399 const struct GNUNET_PeerIdentity *id)
401 GNUNET_HashCode timestamp_hash;
403 GNUNET_CRYPTO_hash (×tamp.abs_value,
404 sizeof(timestamp.abs_value),
406 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash,
412 * Get the transmission delay that should be applied for a
415 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
416 * 0 for the current round (based on our proximity to time key)
417 * @return delay that should be applied
419 static struct GNUNET_TIME_Relative
420 get_transmit_delay (int round_offset)
422 struct GNUNET_TIME_Relative ret;
423 struct GNUNET_TIME_Absolute tgt;
425 uint32_t matching_bits;
427 switch (round_offset)
430 /* previous round is randomized between 0 and 50 ms */
431 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
434 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
435 "Transmitting previous round behind schedule in %llu ms\n",
436 (unsigned long long) ret.rel_value);
440 /* current round is based on best-known matching_bits */
441 matching_bits = ntohl (size_estimate_messages[estimate_index].matching_bits);
442 dist_delay = get_matching_bits_delay (matching_bits);
443 dist_delay += get_delay_randomization (matching_bits).rel_value;
444 ret.rel_value = (uint64_t) dist_delay;
446 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
447 "For round %llu, delay for %u matching bits is %llu ms\n",
448 (unsigned long long) current_timestamp.abs_value,
449 (unsigned int) matching_bits,
450 (unsigned long long) ret.rel_value);
452 /* now consider round start time and add delay to it */
453 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
454 return GNUNET_TIME_absolute_get_remaining (tgt);
457 return GNUNET_TIME_UNIT_FOREVER_REL;
462 * Task that triggers a NSE P2P transmission.
464 * @param cls the 'struct NSEPeerEntry'
465 * @param tc scheduler context
468 transmit_task (void *cls,
469 const struct GNUNET_SCHEDULER_TaskContext *tc);
473 * Called when core is ready to send a message we asked for
474 * out to the destination.
476 * @param cls closure (NULL)
477 * @param size number of bytes available in buf
478 * @param buf where the callee should write the message
479 * @return number of bytes written to buf
482 transmit_ready (void *cls, size_t size, void *buf)
484 struct NSEPeerEntry *peer_entry = cls;
487 peer_entry->th = NULL;
490 /* client disconnected */
493 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
494 idx = estimate_index;
495 if (peer_entry->previous_round == GNUNET_NO)
497 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
498 peer_entry->previous_round = GNUNET_YES;
499 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0),
503 if ( (ntohl (size_estimate_messages[idx].hop_count) == 0) &&
504 (GNUNET_SCHEDULER_NO_TASK != proof_task) )
506 GNUNET_STATISTICS_update (stats,
507 "# flood messages not generated (no proof yet)",
513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
514 "In round %llu, sending to `%s' estimate with %u bits\n",
515 (unsigned long long) GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].timestamp).abs_value,
516 GNUNET_i2s (&peer_entry->id),
517 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
519 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
520 GNUNET_STATISTICS_update (stats,
521 "# flood messages started",
524 GNUNET_STATISTICS_update (stats,
525 "# flood messages transmitted",
529 &size_estimate_messages[idx],
530 sizeof (struct GNUNET_NSE_FloodMessage));
531 GNUNET_STATISTICS_update (stats,
532 "# flood messages sent",
535 return sizeof (struct GNUNET_NSE_FloodMessage);
540 * Task that triggers a NSE P2P transmission.
542 * @param cls the 'struct NSEPeerEntry'
543 * @param tc scheduler context
546 transmit_task (void *cls,
547 const struct GNUNET_SCHEDULER_TaskContext *tc)
549 struct NSEPeerEntry *peer_entry = cls;
551 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
553 = GNUNET_CORE_notify_transmit_ready (coreAPI,
556 GNUNET_TIME_UNIT_FOREVER_REL,
558 sizeof (struct GNUNET_NSE_FloodMessage),
559 &transmit_ready, peer_entry);
564 * We've sent on our flood message or one that we received which was
565 * validated and closer than ours. Update the global list of recent
566 * messages and the average. Also re-broadcast the message to any
570 update_network_size_estimate ()
572 struct GNUNET_NSE_ClientMessage em;
574 setup_estimate_message (&em);
575 GNUNET_SERVER_notification_context_broadcast (nc,
582 * Setup a flood message in our history array at the given
583 * slot offset for the given timestamp.
585 * @param slot index to use
586 * @param ts timestamp to use
589 setup_flood_message (unsigned int slot,
590 struct GNUNET_TIME_Absolute ts)
592 struct GNUNET_NSE_FloodMessage *fm;
593 uint32_t matching_bits;
595 matching_bits = get_matching_bits (ts, &my_identity);
596 fm = &size_estimate_messages[slot];
597 fm->header.size = htons (sizeof(struct GNUNET_NSE_FloodMessage));
598 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
599 fm->hop_count = htonl (0);
600 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
601 fm->purpose.size = htonl (sizeof(struct GNUNET_NSE_FloodMessage)
602 - sizeof (struct GNUNET_MessageHeader)
604 - sizeof (struct GNUNET_CRYPTO_RsaSignature));
605 fm->matching_bits = htonl (matching_bits);
606 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
607 fm->pkey = my_public_key;
608 fm->proof_of_work = my_proof;
609 GNUNET_CRYPTO_rsa_sign (my_private_key,
616 * Schedule transmission for the given peer for the current round based
617 * on what we know about the desired delay.
620 * @param key hash of peer identity
621 * @param value the 'struct NSEPeerEntry'
622 * @return GNUNET_OK (continue to iterate)
625 schedule_current_round (void *cls,
626 const GNUNET_HashCode *key,
629 struct NSEPeerEntry *peer_entry = value;
630 struct GNUNET_TIME_Relative delay;
632 if (peer_entry->th != NULL)
634 peer_entry->previous_round = GNUNET_NO;
637 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
639 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
640 peer_entry->previous_round = GNUNET_NO;
642 delay = get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
643 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
651 * Update our flood message to be sent (and our timestamps).
654 * @param tc context for this message
657 update_flood_message(void *cls,
658 const struct GNUNET_SCHEDULER_TaskContext *tc)
660 struct GNUNET_TIME_Relative offset;
663 flood_task = GNUNET_SCHEDULER_NO_TASK;
664 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
665 if (0 != offset.rel_value)
667 /* somehow run early, delay more */
669 = GNUNET_SCHEDULER_add_delayed (offset,
670 &update_flood_message,
674 current_timestamp = next_timestamp;
675 next_timestamp = GNUNET_TIME_absolute_add (current_timestamp,
676 gnunet_nse_interval);
677 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
678 if (estimate_count < HISTORY_SIZE)
680 if (next_timestamp.abs_value ==
681 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
683 /* we received a message for this round way early, use it! */
684 size_estimate_messages[estimate_index] = next_message;
685 size_estimate_messages[estimate_index].hop_count
686 = htonl (1 + ntohl (next_message.hop_count));
689 setup_flood_message (estimate_index, current_timestamp);
690 next_message.matching_bits = htonl (0); /* reset for 'next' round */
692 for (i=0;i<HISTORY_SIZE;i++)
693 hop_count_max = GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count),
695 GNUNET_CONTAINER_multihashmap_iterate (peers,
696 &schedule_current_round,
698 flood_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
699 &update_flood_message, NULL);
704 * Count the leading zeroes in hash.
707 * @return the number of leading zero bits.
710 count_leading_zeroes(const GNUNET_HashCode *hash)
712 unsigned int hash_count;
715 while ((0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count)))
722 * Check whether the given public key
723 * and integer are a valid proof of work.
725 * @param pkey the public key
726 * @param val the integer
728 * @return GNUNET_YES if valid, GNUNET_NO if not
731 check_proof_of_work(const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
734 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(val)];
735 GNUNET_HashCode result;
740 memcpy (&buf[sizeof(val)],
742 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
743 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
744 return (count_leading_zeroes (&result) >= nse_work_required) ? GNUNET_YES : GNUNET_NO;
749 * Write our current proof to disk.
757 GNUNET_CONFIGURATION_get_value_filename (cfg,
761 if (sizeof (my_proof) !=
762 GNUNET_DISK_fn_write (proof,
765 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE))
766 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
775 * Find our proof of work.
777 * @param cls closure (unused)
778 * @param tc task context
781 find_proof (void *cls,
782 const struct GNUNET_SCHEDULER_TaskContext *tc)
784 #define ROUND_SIZE 10
786 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(uint64_t)];
787 GNUNET_HashCode result;
790 proof_task = GNUNET_SCHEDULER_NO_TASK;
791 memcpy (&buf[sizeof(uint64_t)],
793 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
796 while ( (counter != UINT64_MAX) && (i < ROUND_SIZE) )
801 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
802 if (nse_work_required <= count_leading_zeroes(&result))
805 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
806 _("Proof of work found: %llu!\n"),
807 (unsigned long long) GNUNET_ntohll (counter));
808 for (i=0;i<HISTORY_SIZE;i++)
809 if (ntohl (size_estimate_messages[i].hop_count) == 0)
811 size_estimate_messages[i].proof_of_work = my_proof;
812 GNUNET_CRYPTO_rsa_sign (my_private_key,
813 &size_estimate_messages[i].purpose,
814 &size_estimate_messages[i].signature);
822 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
825 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
826 "Testing proofs currently at %llu\n",
827 (unsigned long long) counter);
829 /* remember progress every 100 rounds */
837 proof_task = GNUNET_SCHEDULER_add_delayed (proof_find_delay,
844 * An incoming flood message has been received which claims
845 * to have more bits matching than any we know in this time
846 * period. Verify the signature and/or proof of work.
848 * @param incoming_flood the message to verify
850 * @return GNUNET_YES if the message is verified
851 * GNUNET_NO if the key/signature don't verify
854 verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood)
857 check_proof_of_work (&incoming_flood->pkey,
858 incoming_flood->proof_of_work))
860 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
861 _("Proof of work invalid: %llu!\n"),
862 (unsigned long long) GNUNET_ntohll (incoming_flood->proof_of_work));
867 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
868 &incoming_flood->purpose,
869 &incoming_flood->signature,
870 &incoming_flood->pkey))
880 * Update transmissions for the given peer for the current round based
881 * on updated proximity information.
883 * @param cls peer entry to exclude from updates
884 * @param key hash of peer identity
885 * @param value the 'struct NSEPeerEntry'
886 * @return GNUNET_OK (continue to iterate)
889 update_flood_times (void *cls,
890 const GNUNET_HashCode *key,
893 struct NSEPeerEntry *exclude = cls;
894 struct NSEPeerEntry *peer_entry = value;
895 struct GNUNET_TIME_Relative delay;
897 if (peer_entry->th != NULL)
898 return GNUNET_OK; /* already active */
899 if (peer_entry == exclude)
900 return GNUNET_OK; /* trigger of the update */
901 if (peer_entry->previous_round == GNUNET_NO)
903 /* still stuck in previous round, no point to update, check that
904 we are active here though... */
905 GNUNET_break (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK);
908 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
910 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
911 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
913 delay = get_transmit_delay (0);
914 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
922 * Core handler for size estimate flooding messages.
924 * @param cls closure unused
925 * @param message message
926 * @param peer peer identity this message is from (ignored)
927 * @param atsi performance data (ignored)
931 handle_p2p_size_estimate(void *cls,
932 const struct GNUNET_PeerIdentity *peer,
933 const struct GNUNET_MessageHeader *message,
934 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
936 const struct GNUNET_NSE_FloodMessage *incoming_flood;
937 struct GNUNET_TIME_Absolute ts;
938 struct NSEPeerEntry *peer_entry;
939 uint32_t matching_bits;
942 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
943 GNUNET_STATISTICS_update (stats,
944 "# flood messages received",
947 matching_bits = ntohl (incoming_flood->matching_bits);
952 struct GNUNET_PeerIdentity os;
954 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
955 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
957 GNUNET_snprintf (origin, sizeof (origin),
960 GNUNET_snprintf (pred, sizeof (pred),
963 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
964 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
965 (unsigned long long) GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
968 GNUNET_i2s (&my_identity),
969 (unsigned int) matching_bits);
973 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
974 if (NULL == peer_entry)
979 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
980 if (ts.abs_value == current_timestamp.abs_value)
981 idx = estimate_index;
982 else if (ts.abs_value == current_timestamp.abs_value - gnunet_nse_interval.rel_value)
983 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
984 else if (ts.abs_value == next_timestamp.abs_value - gnunet_nse_interval.rel_value)
986 if (matching_bits <= ntohl (next_message.matching_bits))
987 return GNUNET_OK; /* ignore, simply too early */
989 verify_message_crypto (incoming_flood))
994 next_message = *incoming_flood;
999 GNUNET_STATISTICS_update (stats,
1000 "# flood messages discarded (clock skew too large)",
1003 GNUNET_break_op (0);
1006 if (0 == (memcmp (peer, &my_identity, sizeof(struct GNUNET_PeerIdentity))))
1008 /* send to self, update our own estimate IF this also comes from us! */
1009 if (0 == memcmp (&incoming_flood->pkey,
1011 sizeof (my_public_key)))
1012 update_network_size_estimate ();
1015 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1017 /* cancel transmission from us to this peer for this round */
1018 if (idx == estimate_index)
1020 if (peer_entry->previous_round == GNUNET_YES)
1022 /* cancel any activity for current round */
1023 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1025 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1026 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1028 if (peer_entry->th != NULL)
1030 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1031 peer_entry->th = NULL;
1037 /* cancel previous round only */
1038 peer_entry->previous_round = GNUNET_YES;
1041 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1043 /* Not closer than our most recent message, no need to do work here */
1044 GNUNET_STATISTICS_update (stats,
1045 "# flood messages ignored (had closer already)",
1051 verify_message_crypto (incoming_flood))
1053 GNUNET_break_op (0);
1056 size_estimate_messages[idx] = *incoming_flood;
1057 size_estimate_messages[idx].hop_count = htonl (ntohl (incoming_flood->hop_count) + 1);
1058 hop_count_max = GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
1061 /* have a new, better size estimate, inform clients */
1062 update_network_size_estimate ();
1065 GNUNET_CONTAINER_multihashmap_iterate (peers,
1066 &update_flood_times,
1074 * Method called whenever a peer connects.
1076 * @param cls closure
1077 * @param peer peer identity this notification is about
1078 * @param atsi performance data
1081 handle_core_connect(void *cls, const struct GNUNET_PeerIdentity *peer,
1082 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1084 struct NSEPeerEntry *peer_entry;
1087 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1088 "Peer `%s' connected to us\n",
1091 peer_entry = GNUNET_malloc(sizeof(struct NSEPeerEntry));
1092 peer_entry->id = *peer;
1093 GNUNET_CONTAINER_multihashmap_put (peers,
1096 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1097 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
1104 * Method called whenever a peer disconnects.
1106 * @param cls closure
1107 * @param peer peer identity this notification is about
1110 handle_core_disconnect(void *cls, const struct GNUNET_PeerIdentity *peer)
1112 struct NSEPeerEntry *pos;
1115 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1116 "Peer `%s' disconnected from us\n",
1119 pos = GNUNET_CONTAINER_multihashmap_get (peers,
1126 GNUNET_assert (GNUNET_YES ==
1127 GNUNET_CONTAINER_multihashmap_remove (peers,
1130 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1131 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1132 if (pos->th != NULL)
1133 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1139 * Task run during shutdown.
1145 shutdown_task(void *cls,
1146 const struct GNUNET_SCHEDULER_TaskContext *tc)
1148 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1150 GNUNET_SCHEDULER_cancel (flood_task);
1151 flood_task = GNUNET_SCHEDULER_NO_TASK;
1153 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1155 GNUNET_SCHEDULER_cancel (proof_task);
1156 proof_task = GNUNET_SCHEDULER_NO_TASK;
1157 write_proof (); /* remember progress */
1161 GNUNET_SERVER_notification_context_destroy (nc);
1164 if (coreAPI != NULL)
1166 GNUNET_CORE_disconnect (coreAPI);
1171 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1176 GNUNET_CONTAINER_multihashmap_destroy (peers);
1179 if (my_private_key != NULL)
1181 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1182 my_private_key = NULL;
1188 * Called on core init/fail.
1190 * @param cls service closure
1191 * @param server handle to the server for this service
1192 * @param identity the public identity of this peer
1193 * @param publicKey the public key of this peer
1196 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1197 const struct GNUNET_PeerIdentity *identity,
1198 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1200 struct GNUNET_TIME_Absolute now;
1201 struct GNUNET_TIME_Absolute prev_time;
1207 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1208 "Connection to core FAILED!\n");
1210 GNUNET_SCHEDULER_shutdown ();
1213 GNUNET_assert (0 == memcmp (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity)));
1214 now = GNUNET_TIME_absolute_get ();
1215 current_timestamp.abs_value = (now.abs_value / gnunet_nse_interval.rel_value) * gnunet_nse_interval.rel_value;
1216 next_timestamp.abs_value = current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1218 for (i=0;i<HISTORY_SIZE;i++)
1220 prev_time.abs_value = current_timestamp.abs_value - (HISTORY_SIZE - i - 1) * gnunet_nse_interval.rel_value;
1221 setup_flood_message (i, prev_time);
1223 estimate_index = HISTORY_SIZE - 1;
1226 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
1227 &update_flood_message, NULL);
1232 * Handle network size estimate clients.
1234 * @param cls closure
1235 * @param server the initialized server
1236 * @param c configuration to use
1239 run(void *cls, struct GNUNET_SERVER_Handle *server,
1240 const struct GNUNET_CONFIGURATION_Handle *c)
1245 static const struct GNUNET_SERVER_MessageHandler handlers[] =
1247 { &handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START, sizeof (struct GNUNET_MessageHeader) },
1248 { NULL, NULL, 0, 0 }
1250 static const struct GNUNET_CORE_MessageHandler core_handlers[] =
1252 { &handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, sizeof (struct GNUNET_NSE_FloodMessage) },
1258 GNUNET_CONFIGURATION_get_value_time (cfg,
1260 &gnunet_nse_interval)) ||
1262 GNUNET_CONFIGURATION_get_value_time (cfg,
1264 &proof_find_delay)) ||
1266 GNUNET_CONFIGURATION_get_value_number (cfg,
1268 &nse_work_required)) )
1270 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1271 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1272 GNUNET_SCHEDULER_shutdown ();
1275 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1277 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1278 _ ("Invalid work requirement for NSE service. Exiting.\n"));
1279 GNUNET_SCHEDULER_shutdown ();
1285 GNUNET_CONFIGURATION_get_value_filename (cfg,
1286 "GNUNETD", "HOSTKEY",
1289 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1290 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1291 GNUNET_SCHEDULER_shutdown ();
1294 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1295 GNUNET_free (keyfile);
1296 if (my_private_key == NULL)
1298 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1299 _("NSE service could not access hostkey. Exiting.\n"));
1300 GNUNET_SCHEDULER_shutdown ();
1303 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1304 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_identity.hashPubKey);
1306 GNUNET_CONFIGURATION_get_value_filename (cfg,
1310 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1311 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1312 if (my_private_key != NULL)
1314 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1315 my_private_key = NULL;
1317 GNUNET_SCHEDULER_shutdown ();
1320 if ( (GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1321 (sizeof (my_proof) !=
1322 GNUNET_DISK_fn_read (proof,
1324 sizeof (my_proof))) )
1326 GNUNET_free (proof);
1327 proof_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1331 peers = GNUNET_CONTAINER_multihashmap_create (128);
1332 GNUNET_SERVER_add_handlers (server, handlers);
1333 nc = GNUNET_SERVER_notification_context_create (server, 1);
1334 /* Connect to core service and register core handlers */
1335 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1336 CORE_QUEUE_SIZE, /* queue size */
1337 NULL, /* Closure passed to functions */
1338 &core_init, /* Call core_init once connected */
1339 &handle_core_connect, /* Handle connects */
1340 &handle_core_disconnect, /* Handle disconnects */
1341 NULL, /* Do we care about "status" updates? */
1342 NULL, /* Don't want notified about all incoming messages */
1343 GNUNET_NO, /* For header only inbound notification */
1344 NULL, /* Don't want notified about all outbound messages */
1345 GNUNET_NO, /* For header only outbound notification */
1346 core_handlers); /* Register these handlers */
1347 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1348 &shutdown_task, NULL);
1349 if (coreAPI == NULL)
1351 GNUNET_SCHEDULER_shutdown ();
1354 stats = GNUNET_STATISTICS_create ("nse", cfg);
1359 * The main function for the statistics service.
1361 * @param argc number of arguments from the command line
1362 * @param argv command line arguments
1363 * @return 0 ok, 1 on error
1366 main(int argc, char * const *argv)
1368 return (GNUNET_OK == GNUNET_SERVICE_run (argc, argv,
1370 GNUNET_SERVICE_OPTION_NONE, &run,
1374 /* end of gnunet-service-nse.c */