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"
48 #define DEBUG_NSE GNUNET_YES
51 * Over how many values do we calculate the weighted average?
53 #define HISTORY_SIZE 8
56 * Size of the queue to core.
58 #define CORE_QUEUE_SIZE 2
61 * Message priority to use.
63 #define NSE_PRIORITY 5
66 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
68 #define NSE_WORK_REQUIRED 8
71 * Interval for sending network size estimation flood requests.
73 #define GNUNET_NSE_INTERVAL GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 60)
76 * Interval between proof find runs.
78 #define PROOF_FIND_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 5)
82 * Per-peer information.
88 * Pending message for this peer.
90 struct GNUNET_MessageHeader *pending_message;
93 * Core handle for sending messages to this peer.
95 struct GNUNET_CORE_TransmitHandle *th;
98 * What is the identity of the peer?
100 struct GNUNET_PeerIdentity id;
103 * Task scheduled to send message to this peer.
105 GNUNET_SCHEDULER_TaskIdentifier transmit_task;
108 * Did we receive or send a message about the previous round
116 * Network size estimate reply; sent when "this"
117 * peer's timer has run out before receiving a
118 * valid reply from another peer.
120 struct GNUNET_NSE_FloodMessage
123 * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
125 struct GNUNET_MessageHeader header;
128 * Number of hops this message has taken so far.
135 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
138 * The current timestamp value (which all
139 * peers should agree on).
141 struct GNUNET_TIME_AbsoluteNBO timestamp;
144 * Number of matching bits between the hash
145 * of timestamp and the initiator's public
148 uint32_t matching_bits;
151 * Public key of the originator.
153 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
156 * Proof of work, causing leading zeros when hashed with pkey.
158 uint64_t proof_of_work;
161 * Signature (over range specified in purpose).
163 struct GNUNET_CRYPTO_RsaSignature signature;
168 * Handle to our current configuration.
170 static const struct GNUNET_CONFIGURATION_Handle *cfg;
173 * Handle to the statistics service.
175 static struct GNUNET_STATISTICS_Handle *stats;
178 * Handle to the core service.
180 static struct GNUNET_CORE_Handle *coreAPI;
183 * Map of all connected peers.
185 static struct GNUNET_CONTAINER_MultiHashMap *peers;
188 * The current network size estimate. Number of bits matching on
191 static double current_size_estimate;
194 * The standard deviation of the last HISTORY_SIZE network
197 static double current_std_dev = NAN;
200 * Current hop counter estimate (estimate for network diameter).
202 static uint32_t hop_count_max;
205 * Message for the next round, if we got any.
207 static struct GNUNET_NSE_FloodMessage next_message;
210 * Array of recent size estimate messages.
212 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
215 * Index of most recent estimate.
217 static unsigned int estimate_index;
220 * Number of valid entries in the history.
222 static unsigned int estimate_count;
225 * Task scheduled to update our flood message for the next round.
227 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
230 * Task scheduled to compute our proof.
232 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
235 * Notification context, simplifies client broadcasts.
237 static struct GNUNET_SERVER_NotificationContext *nc;
240 * The next major time.
242 static struct GNUNET_TIME_Absolute next_timestamp;
245 * The current major time.
247 static struct GNUNET_TIME_Absolute current_timestamp;
250 * The public key of this peer.
252 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
255 * The private key of this peer.
257 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
260 * The peer identity of this peer.
262 static struct GNUNET_PeerIdentity my_identity;
265 * Proof of work for this peer.
267 static uint64_t my_proof;
271 * Initialize a message to clients with the current network
274 * @param em message to fill in
277 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
291 /* Weighted incremental algorithm for stddev according to West (1979) */
295 for (i=0;i<estimate_count; i++)
297 val = htonl (size_estimate_messages[(estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE].matching_bits);
298 weight = estimate_count + 1 - i;
300 temp = weight + sumweight;
302 r = q * weight / temp;
303 sum += sumweight * q * r;
307 variance = sum / (sumweight - 1.0);
308 GNUNET_assert (variance >= 0);
309 std_dev = sqrt (variance);
310 current_std_dev = std_dev;
311 current_size_estimate = mean;
314 = htons (sizeof(struct GNUNET_NSE_ClientMessage));
316 = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
317 em->reserved = htonl (0);
318 em->size_estimate = mean - 0.5;
319 em->std_deviation = std_dev;
320 GNUNET_STATISTICS_set (stats,
321 "# nodes in the network (estimate)",
322 (uint64_t) pow (2, mean - 0.5), GNUNET_NO);
327 * Handler for START message from client, triggers an
328 * immediate current network estimate notification.
329 * Also, we remember the client for updates upon future
330 * estimate measurements.
333 * @param client who sent the message
334 * @param message the message received
337 handle_start_message(void *cls, struct GNUNET_SERVER_Client *client,
338 const struct GNUNET_MessageHeader *message)
340 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 (current_size_estimate - matching_bits));
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,
435 /* current round is based on best-known matching_bits */
436 matching_bits = ntohl (size_estimate_messages[estimate_index].matching_bits);
437 dist_delay = get_matching_bits_delay (matching_bits);
438 dist_delay += get_delay_randomization (matching_bits).rel_value;
439 ret.rel_value = (uint64_t) dist_delay;
440 /* now consider round start time and add delay to it */
441 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
442 return GNUNET_TIME_absolute_get_remaining (tgt);
445 return GNUNET_TIME_UNIT_FOREVER_REL;
450 * Task that triggers a NSE P2P transmission.
452 * @param cls the 'struct NSEPeerEntry'
453 * @param tc scheduler context
456 transmit_task (void *cls,
457 const struct GNUNET_SCHEDULER_TaskContext *tc);
461 * Called when core is ready to send a message we asked for
462 * out to the destination.
464 * @param cls closure (NULL)
465 * @param size number of bytes available in buf
466 * @param buf where the callee should write the message
467 * @return number of bytes written to buf
470 transmit_ready (void *cls, size_t size, void *buf)
472 struct NSEPeerEntry *peer_entry = cls;
475 peer_entry->th = NULL;
478 /* client disconnected */
481 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
483 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
484 "Sending size estimate to `%s'\n",
485 GNUNET_i2s (&peer_entry->id));
487 idx = estimate_index;
488 if (peer_entry->previous_round == GNUNET_YES)
490 idx = (idx + HISTORY_SIZE -1) % HISTORY_SIZE;
491 peer_entry->previous_round = GNUNET_NO;
492 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0),
496 if ( (ntohl (size_estimate_messages[idx].hop_count) == 0) &&
497 (GNUNET_SCHEDULER_NO_TASK != proof_task) )
499 GNUNET_STATISTICS_update (stats,
500 "# flood messages not generated (no proof yet)",
505 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
506 GNUNET_STATISTICS_update (stats,
507 "# flood messages started",
510 GNUNET_STATISTICS_update (stats,
511 "# flood messages transmitted",
515 &size_estimate_messages[idx],
516 sizeof (struct GNUNET_NSE_FloodMessage));
517 GNUNET_STATISTICS_update (stats,
518 "# flood messages sent",
521 return sizeof (struct GNUNET_NSE_FloodMessage);
526 * Task that triggers a NSE P2P transmission.
528 * @param cls the 'struct NSEPeerEntry'
529 * @param tc scheduler context
532 transmit_task (void *cls,
533 const struct GNUNET_SCHEDULER_TaskContext *tc)
535 struct NSEPeerEntry *peer_entry = cls;
537 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
539 = GNUNET_CORE_notify_transmit_ready (coreAPI,
542 GNUNET_TIME_UNIT_FOREVER_REL,
544 sizeof (struct GNUNET_NSE_FloodMessage),
545 &transmit_ready, peer_entry);
550 * We've sent on our flood message or one that we received which was
551 * validated and closer than ours. Update the global list of recent
552 * messages and the average. Also re-broadcast the message to any
556 update_network_size_estimate ()
558 struct GNUNET_NSE_ClientMessage em;
560 setup_estimate_message (&em);
561 GNUNET_SERVER_notification_context_broadcast (nc,
568 * Setup a flood message in our history array at the given
569 * slot offset for the given timestamp.
571 * @param slot index to use
572 * @param ts timestamp to use
575 setup_flood_message (unsigned int slot,
576 struct GNUNET_TIME_Absolute ts)
578 struct GNUNET_NSE_FloodMessage *fm;
579 uint32_t matching_bits;
581 matching_bits = get_matching_bits (ts, &my_identity);
582 fm = &size_estimate_messages[slot];
583 fm->header.size = htons (sizeof(struct GNUNET_NSE_FloodMessage));
584 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
585 fm->hop_count = htonl (0);
586 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
587 fm->purpose.size = htonl (sizeof(struct GNUNET_NSE_FloodMessage)
588 - sizeof (struct GNUNET_MessageHeader)
590 - sizeof (struct GNUNET_CRYPTO_RsaSignature));
591 fm->matching_bits = htonl (matching_bits);
592 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
593 fm->pkey = my_public_key;
594 fm->proof_of_work = my_proof;
595 GNUNET_CRYPTO_rsa_sign (my_private_key,
602 * Schedule transmission for the given peer for the current round based
603 * on what we know about the desired delay.
606 * @param key hash of peer identity
607 * @param value the 'struct NSEPeerEntry'
608 * @return GNUNET_OK (continue to iterate)
611 schedule_current_round (void *cls,
612 const GNUNET_HashCode *key,
615 struct NSEPeerEntry *peer_entry = value;
616 struct GNUNET_TIME_Relative delay;
618 if (peer_entry->th != NULL)
620 peer_entry->previous_round = GNUNET_NO;
623 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
625 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
626 peer_entry->previous_round = GNUNET_NO;
628 delay = get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
629 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
637 * Update our flood message to be sent (and our timestamps).
640 * @param tc context for this message
643 update_flood_message(void *cls,
644 const struct GNUNET_SCHEDULER_TaskContext *tc)
646 struct GNUNET_TIME_Relative offset;
649 flood_task = GNUNET_SCHEDULER_NO_TASK;
650 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
651 if (0 != offset.rel_value)
653 /* somehow run early, delay more */
655 = GNUNET_SCHEDULER_add_delayed (offset,
656 &update_flood_message,
660 current_timestamp = next_timestamp;
661 next_timestamp = GNUNET_TIME_absolute_add (current_timestamp,
662 GNUNET_NSE_INTERVAL);
663 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
664 if (estimate_count < HISTORY_SIZE)
666 if (next_timestamp.abs_value ==
667 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
669 /* we received a message for this round way early, use it! */
670 size_estimate_messages[estimate_index] = next_message;
671 size_estimate_messages[estimate_index].hop_count
672 = htonl (1 + ntohl (next_message.hop_count));
675 setup_flood_message (estimate_index, current_timestamp);
676 next_message.matching_bits = htonl (0); /* reset for 'next' round */
678 for (i=0;i<HISTORY_SIZE;i++)
679 hop_count_max = GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count),
681 GNUNET_CONTAINER_multihashmap_iterate (peers,
682 &schedule_current_round,
684 flood_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
685 &update_flood_message, NULL);
690 * Count the leading zeroes in hash.
693 * @return the number of leading zero bits.
696 count_leading_zeroes(const GNUNET_HashCode *hash)
698 unsigned int hash_count;
701 while ((0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count)))
708 * Check whether the given public key
709 * and integer are a valid proof of work.
711 * @param pkey the public key
712 * @param val the integer
714 * @return GNUNET_YES if valid, GNUNET_NO if not
717 check_proof_of_work(const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
720 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(val)];
721 GNUNET_HashCode result;
726 memcpy (&buf[sizeof(val)],
728 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
729 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
730 return (count_leading_zeroes (&result) >= NSE_WORK_REQUIRED) ? GNUNET_YES : GNUNET_NO;
735 * Write our current proof to disk.
743 GNUNET_CONFIGURATION_get_value_filename (cfg,
747 if (sizeof (my_proof) !=
748 GNUNET_DISK_fn_write (proof,
751 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE))
752 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
761 * Find our proof of work.
763 * @param cls closure (unused)
764 * @param tc task context
767 find_proof (void *cls,
768 const struct GNUNET_SCHEDULER_TaskContext *tc)
770 #define ROUND_SIZE 10
772 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(uint64_t)];
773 GNUNET_HashCode result;
776 proof_task = GNUNET_SCHEDULER_NO_TASK;
777 memcpy (&buf[sizeof(uint64_t)],
779 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
782 while ( (counter != UINT64_MAX) && (i < ROUND_SIZE) )
787 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
788 if (NSE_WORK_REQUIRED <= count_leading_zeroes(&result))
791 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
792 _("Proof of work found: %llu!\n"),
793 (unsigned long long) GNUNET_ntohll (counter));
794 for (i=0;i<HISTORY_SIZE;i++)
795 if (ntohl (size_estimate_messages[i].hop_count) == 0)
797 size_estimate_messages[i].proof_of_work = my_proof;
798 GNUNET_CRYPTO_rsa_sign (my_private_key,
799 &size_estimate_messages[i].purpose,
800 &size_estimate_messages[i].signature);
808 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
811 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
812 "Testing proofs currently at %llu\n",
813 (unsigned long long) counter);
815 /* remember progress every 100 rounds */
823 proof_task = GNUNET_SCHEDULER_add_delayed (PROOF_FIND_DELAY,
830 * An incoming flood message has been received which claims
831 * to have more bits matching than any we know in this time
832 * period. Verify the signature and/or proof of work.
834 * @param incoming_flood the message to verify
836 * @return GNUNET_YES if the message is verified
837 * GNUNET_NO if the key/signature don't verify
840 verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood)
843 check_proof_of_work (&incoming_flood->pkey,
844 incoming_flood->proof_of_work))
846 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
847 _("Proof of work invalid: %llu!\n"),
848 (unsigned long long) GNUNET_ntohll (incoming_flood->proof_of_work));
853 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
854 &incoming_flood->purpose,
855 &incoming_flood->signature,
856 &incoming_flood->pkey))
866 * Update transmissions for the given peer for the current round based
867 * on updated proximity information.
869 * @param cls peer entry to exclude from updates
870 * @param key hash of peer identity
871 * @param value the 'struct NSEPeerEntry'
872 * @return GNUNET_OK (continue to iterate)
875 update_flood_times (void *cls,
876 const GNUNET_HashCode *key,
879 struct NSEPeerEntry *exclude = cls;
880 struct NSEPeerEntry *peer_entry = value;
881 struct GNUNET_TIME_Relative delay;
883 if (peer_entry->th != NULL)
884 return GNUNET_OK; /* already active */
885 if (peer_entry == exclude)
886 return GNUNET_OK; /* trigger of the update */
887 if (peer_entry->previous_round == GNUNET_YES)
889 /* still stuck in previous round, no point to update, check that
890 we are active here though... */
891 GNUNET_break (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK);
894 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
896 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
897 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
899 delay = get_transmit_delay (0);
900 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
908 * Core handler for size estimate flooding messages.
910 * @param cls closure unused
911 * @param message message
912 * @param peer peer identity this message is from (ignored)
913 * @param atsi performance data (ignored)
917 handle_p2p_size_estimate(void *cls,
918 const struct GNUNET_PeerIdentity *peer,
919 const struct GNUNET_MessageHeader *message,
920 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
922 const struct GNUNET_NSE_FloodMessage *incoming_flood;
923 struct GNUNET_TIME_Absolute ts;
924 struct NSEPeerEntry *peer_entry;
925 uint32_t matching_bits;
928 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
929 GNUNET_STATISTICS_update (stats,
930 "# flood messages received",
933 matching_bits = ntohl (incoming_flood->matching_bits);
938 struct GNUNET_PeerIdentity os;
940 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
941 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
943 GNUNET_snprintf (origin, sizeof (origin),
946 GNUNET_snprintf (pred, sizeof (pred),
949 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
950 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
951 (unsigned long long) GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
954 GNUNET_i2s (&my_identity),
955 (unsigned int) matching_bits);
959 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
960 if (NULL == peer_entry)
965 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
966 if (ts.abs_value == current_timestamp.abs_value)
967 idx = estimate_index;
968 else if (ts.abs_value == current_timestamp.abs_value - GNUNET_NSE_INTERVAL.rel_value)
969 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
970 else if (ts.abs_value == next_timestamp.abs_value - GNUNET_NSE_INTERVAL.rel_value)
972 if (matching_bits <= ntohl (next_message.matching_bits))
973 return GNUNET_OK; /* ignore, simply too early */
975 verify_message_crypto (incoming_flood))
980 next_message = *incoming_flood;
985 GNUNET_STATISTICS_update (stats,
986 "# flood messages discarded (clock skew too large)",
992 if (0 == (memcmp (peer, &my_identity, sizeof(struct GNUNET_PeerIdentity))))
994 /* send to self, update our own estimate IF this also comes from us! */
995 if (0 == memcmp (&incoming_flood->pkey,
997 sizeof (my_public_key)))
998 update_network_size_estimate ();
1001 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1003 /* cancel transmission from us to this peer for this round */
1004 if (idx == estimate_index)
1006 if (peer_entry->previous_round == GNUNET_NO)
1008 /* cancel any activity for current round */
1009 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1011 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1012 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1013 peer_entry->previous_round = GNUNET_NO;
1015 if (peer_entry->th != NULL)
1017 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1018 peer_entry->th = NULL;
1024 /* cancel previous round only */
1025 peer_entry->previous_round = GNUNET_NO;
1029 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1031 /* Not closer than our most recent message, no need to do work here */
1032 GNUNET_STATISTICS_update (stats,
1033 "# flood messages ignored (had closer already)",
1039 verify_message_crypto (incoming_flood))
1041 GNUNET_break_op (0);
1044 size_estimate_messages[idx] = *incoming_flood;
1045 size_estimate_messages[idx].hop_count = htonl (ntohl (incoming_flood->hop_count) + 1);
1046 hop_count_max = GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
1049 /* have a new, better size estimate, inform clients */
1050 update_network_size_estimate ();
1053 GNUNET_CONTAINER_multihashmap_iterate (peers,
1054 &update_flood_times,
1062 * Method called whenever a peer connects.
1064 * @param cls closure
1065 * @param peer peer identity this notification is about
1066 * @param atsi performance data
1069 handle_core_connect(void *cls, const struct GNUNET_PeerIdentity *peer,
1070 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1072 struct NSEPeerEntry *peer_entry;
1075 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1076 "Peer `%s' connected to us\n",
1079 peer_entry = GNUNET_malloc(sizeof(struct NSEPeerEntry));
1080 peer_entry->id = *peer;
1081 GNUNET_CONTAINER_multihashmap_put (peers,
1084 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1085 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
1092 * Method called whenever a peer disconnects.
1094 * @param cls closure
1095 * @param peer peer identity this notification is about
1098 handle_core_disconnect(void *cls, const struct GNUNET_PeerIdentity *peer)
1100 struct NSEPeerEntry *pos;
1103 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1104 "Peer `%s' disconnected from us\n",
1107 pos = GNUNET_CONTAINER_multihashmap_get (peers,
1114 GNUNET_assert (GNUNET_YES ==
1115 GNUNET_CONTAINER_multihashmap_remove (peers,
1118 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1119 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1120 if (pos->th != NULL)
1121 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1127 * Task run during shutdown.
1133 shutdown_task(void *cls,
1134 const struct GNUNET_SCHEDULER_TaskContext *tc)
1136 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1138 GNUNET_SCHEDULER_cancel (flood_task);
1139 flood_task = GNUNET_SCHEDULER_NO_TASK;
1141 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1143 GNUNET_SCHEDULER_cancel (proof_task);
1144 proof_task = GNUNET_SCHEDULER_NO_TASK;
1145 write_proof (); /* remember progress */
1149 GNUNET_SERVER_notification_context_destroy (nc);
1152 if (coreAPI != NULL)
1154 GNUNET_CORE_disconnect (coreAPI);
1159 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1164 GNUNET_CONTAINER_multihashmap_destroy (peers);
1167 if (my_private_key != NULL)
1169 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1170 my_private_key = NULL;
1176 * Called on core init/fail.
1178 * @param cls service closure
1179 * @param server handle to the server for this service
1180 * @param identity the public identity of this peer
1181 * @param publicKey the public key of this peer
1184 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1185 const struct GNUNET_PeerIdentity *identity,
1186 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1188 struct GNUNET_TIME_Absolute now;
1189 struct GNUNET_TIME_Absolute prev_time;
1195 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1196 "Connection to core FAILED!\n");
1198 GNUNET_SCHEDULER_shutdown ();
1201 GNUNET_assert (0 == memcmp (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity)));
1202 now = GNUNET_TIME_absolute_get ();
1203 current_timestamp.abs_value = (now.abs_value / GNUNET_NSE_INTERVAL.rel_value) * GNUNET_NSE_INTERVAL.rel_value;
1204 next_timestamp.abs_value = current_timestamp.abs_value + GNUNET_NSE_INTERVAL.rel_value;
1206 for (i=0;i<HISTORY_SIZE;i++)
1208 prev_time.abs_value = current_timestamp.abs_value - (HISTORY_SIZE - i - 1) * GNUNET_NSE_INTERVAL.rel_value;
1209 setup_flood_message (i, prev_time);
1211 estimate_index = HISTORY_SIZE - 1;
1214 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
1215 &update_flood_message, NULL);
1220 * Handle network size estimate clients.
1222 * @param cls closure
1223 * @param server the initialized server
1224 * @param c configuration to use
1227 run(void *cls, struct GNUNET_SERVER_Handle *server,
1228 const struct GNUNET_CONFIGURATION_Handle *c)
1233 static const struct GNUNET_SERVER_MessageHandler handlers[] =
1235 { &handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START, sizeof (struct GNUNET_MessageHeader) },
1236 { NULL, NULL, 0, 0 }
1238 static const struct GNUNET_CORE_MessageHandler core_handlers[] =
1240 { &handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, sizeof (struct GNUNET_NSE_FloodMessage) },
1245 GNUNET_CONFIGURATION_get_value_filename (cfg,
1246 "GNUNETD", "HOSTKEY",
1249 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1250 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1251 GNUNET_SCHEDULER_shutdown ();
1254 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1255 GNUNET_free (keyfile);
1256 if (my_private_key == NULL)
1258 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1259 _("NSE service could not access hostkey. Exiting.\n"));
1260 GNUNET_SCHEDULER_shutdown ();
1263 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1264 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_identity.hashPubKey);
1266 GNUNET_CONFIGURATION_get_value_filename (cfg,
1270 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1271 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1272 if (my_private_key != NULL)
1274 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1275 my_private_key = NULL;
1277 GNUNET_SCHEDULER_shutdown ();
1280 if ( (GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1281 (sizeof (my_proof) !=
1282 GNUNET_DISK_fn_read (proof,
1284 sizeof (my_proof))) )
1286 GNUNET_free (proof);
1287 proof_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1291 peers = GNUNET_CONTAINER_multihashmap_create (128);
1292 GNUNET_SERVER_add_handlers (server, handlers);
1293 nc = GNUNET_SERVER_notification_context_create (server, 1);
1294 /* Connect to core service and register core handlers */
1295 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1296 CORE_QUEUE_SIZE, /* queue size */
1297 NULL, /* Closure passed to functions */
1298 &core_init, /* Call core_init once connected */
1299 &handle_core_connect, /* Handle connects */
1300 &handle_core_disconnect, /* Handle disconnects */
1301 NULL, /* Do we care about "status" updates? */
1302 NULL, /* Don't want notified about all incoming messages */
1303 GNUNET_NO, /* For header only inbound notification */
1304 NULL, /* Don't want notified about all outbound messages */
1305 GNUNET_NO, /* For header only outbound notification */
1306 core_handlers); /* Register these handlers */
1307 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1308 &shutdown_task, NULL);
1309 if (coreAPI == NULL)
1311 GNUNET_SCHEDULER_shutdown ();
1314 stats = GNUNET_STATISTICS_create ("nse", cfg);
1319 * The main function for the statistics service.
1321 * @param argc number of arguments from the command line
1322 * @param argv command line arguments
1323 * @return 0 ok, 1 on error
1326 main(int argc, char * const *argv)
1328 return (GNUNET_OK == GNUNET_SERVICE_run (argc, argv,
1330 GNUNET_SERVICE_OPTION_NONE, &run,
1334 /* end of gnunet-service-nse.c */