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 * Send messages on connect.
51 #define SEND_ON_CONNECT GNUNET_YES
54 * Should we generate a histogram with the time stamps of when we received
55 * NSE messages to disk? (for performance evaluation only, not useful in
58 #define ENABLE_HISTOGRAM GNUNET_YES
61 * Over how many values do we calculate the weighted average?
63 #define HISTORY_SIZE 8
66 * Size of the queue to core.
68 #define CORE_QUEUE_SIZE 2
71 * Message priority to use.
73 #define NSE_PRIORITY 5
76 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
78 static unsigned long long nse_work_required;
81 * Interval for sending network size estimation flood requests.
83 static struct GNUNET_TIME_Relative gnunet_nse_interval;
86 * Interval between proof find runs.
88 static struct GNUNET_TIME_Relative proof_find_delay;
92 static struct GNUNET_BIO_WriteHandle *wh;
97 * Per-peer information.
103 * Pending message for this peer.
105 struct GNUNET_MessageHeader *pending_message;
108 * Core handle for sending messages to this peer.
110 struct GNUNET_CORE_TransmitHandle *th;
113 * What is the identity of the peer?
115 struct GNUNET_PeerIdentity id;
118 * Task scheduled to send message to this peer.
120 GNUNET_SCHEDULER_TaskIdentifier transmit_task;
123 * Did we receive or send a message about the previous round
124 * to this peer yet? GNUNET_YES if the previous round has
125 * been taken care of.
132 * Network size estimate reply; sent when "this"
133 * peer's timer has run out before receiving a
134 * valid reply from another peer.
136 struct GNUNET_NSE_FloodMessage
139 * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
141 struct GNUNET_MessageHeader header;
144 * Number of hops this message has taken so far.
151 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
154 * The current timestamp value (which all
155 * peers should agree on).
157 struct GNUNET_TIME_AbsoluteNBO timestamp;
160 * Number of matching bits between the hash
161 * of timestamp and the initiator's public
164 uint32_t matching_bits;
167 * Public key of the originator.
169 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
172 * Proof of work, causing leading zeros when hashed with pkey.
174 uint64_t proof_of_work;
177 * Signature (over range specified in purpose).
179 struct GNUNET_CRYPTO_RsaSignature signature;
184 * Handle to our current configuration.
186 static const struct GNUNET_CONFIGURATION_Handle *cfg;
189 * Handle to the statistics service.
191 static struct GNUNET_STATISTICS_Handle *stats;
194 * Handle to the core service.
196 static struct GNUNET_CORE_Handle *coreAPI;
199 * Map of all connected peers.
201 static struct GNUNET_CONTAINER_MultiHashMap *peers;
204 * The current network size estimate. Number of bits matching on
207 static double current_size_estimate;
210 * The standard deviation of the last HISTORY_SIZE network
213 static double current_std_dev = NAN;
216 * Current hop counter estimate (estimate for network diameter).
218 static uint32_t hop_count_max;
221 * Message for the next round, if we got any.
223 static struct GNUNET_NSE_FloodMessage next_message;
226 * Array of recent size estimate messages.
228 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
231 * Index of most recent estimate.
233 static unsigned int estimate_index;
236 * Number of valid entries in the history.
238 static unsigned int estimate_count;
241 * Task scheduled to update our flood message for the next round.
243 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
246 * Task scheduled to compute our proof.
248 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
251 * Notification context, simplifies client broadcasts.
253 static struct GNUNET_SERVER_NotificationContext *nc;
256 * The next major time.
258 static struct GNUNET_TIME_Absolute next_timestamp;
261 * The current major time.
263 static struct GNUNET_TIME_Absolute current_timestamp;
266 * The public key of this peer.
268 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
271 * The private key of this peer.
273 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
276 * The peer identity of this peer.
278 static struct GNUNET_PeerIdentity my_identity;
281 * Proof of work for this peer.
283 static uint64_t my_proof;
287 * Initialize a message to clients with the current network
290 * @param em message to fill in
293 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
307 /* Weighted incremental algorithm for stddev according to West (1979) */
311 for (i = 0; i < estimate_count; i++)
313 val = htonl (size_estimate_messages[(estimate_index - i + HISTORY_SIZE)
314 % HISTORY_SIZE].matching_bits);
315 weight = 1; /* was: estimate_count + 1 - i; */
317 temp = weight + sumweight;
319 r = q * weight / temp;
320 sum += sumweight * q * r;
324 variance = sum / (sumweight - 1.0);
325 GNUNET_assert (variance >= 0);
326 std_dev = sqrt (variance);
327 current_std_dev = std_dev;
328 current_size_estimate = mean;
331 = htons (sizeof(struct GNUNET_NSE_ClientMessage));
333 = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
334 em->reserved = htonl (0);
335 em->timestamp = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get());
336 em->size_estimate = mean - 1.0/3.0;
337 em->std_deviation = std_dev;
338 GNUNET_STATISTICS_set (stats,
339 "# nodes in the network (estimate)",
340 (uint64_t) pow (2, mean - 1.0/3.0), GNUNET_NO);
345 * Handler for START message from client, triggers an
346 * immediate current network estimate notification.
347 * Also, we remember the client for updates upon future
348 * estimate measurements.
351 * @param client who sent the message
352 * @param message the message received
355 handle_start_message(void *cls, struct GNUNET_SERVER_Client *client,
356 const struct GNUNET_MessageHeader *message)
358 struct GNUNET_NSE_ClientMessage em;
361 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
362 "Received START message from client\n");
364 GNUNET_SERVER_notification_context_add (nc, client);
365 setup_estimate_message (&em);
366 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header, GNUNET_YES);
367 GNUNET_SERVER_receive_done (client, GNUNET_OK);
372 * How long should we delay a message to go the given number of
375 * @param matching_bits number of matching bits to consider
378 get_matching_bits_delay (uint32_t matching_bits)
380 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p'))*/
381 // S is next_timestamp (ignored in return value)
382 // f is frequency (gnunet_nse_interval)
383 // x is matching_bits
384 // p' is current_size_estimate
385 return ((double) gnunet_nse_interval.rel_value / (double) 2.0)
386 - ((gnunet_nse_interval.rel_value / M_PI) * atan (matching_bits - current_size_estimate));
391 * What delay randomization should we apply for a given number of matching bits?
393 * @param matching_bits number of matching bits
394 * @return random delay to apply
396 static struct GNUNET_TIME_Relative
397 get_delay_randomization (uint32_t matching_bits)
399 struct GNUNET_TIME_Relative ret;
401 if (matching_bits == 0)
402 return GNUNET_TIME_UNIT_ZERO;
403 ret.rel_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
404 (uint32_t) (get_matching_bits_delay (matching_bits - 1) / (double) (hop_count_max + 1)));
410 * Get the number of matching bits that the given timestamp has to the given peer ID.
412 * @param timestamp time to generate key
413 * @param id peer identity to compare with
414 * @return number of matching bits
417 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
418 const struct GNUNET_PeerIdentity *id)
420 GNUNET_HashCode timestamp_hash;
422 GNUNET_CRYPTO_hash (×tamp.abs_value,
423 sizeof(timestamp.abs_value),
425 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash,
431 * Get the transmission delay that should be applied for a
434 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
435 * 0 for the current round (based on our proximity to time key)
436 * @return delay that should be applied
438 static struct GNUNET_TIME_Relative
439 get_transmit_delay (int round_offset)
441 struct GNUNET_TIME_Relative ret;
442 struct GNUNET_TIME_Absolute tgt;
444 uint32_t matching_bits;
446 switch (round_offset)
449 /* previous round is randomized between 0 and 50 ms */
450 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
453 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
454 "Transmitting previous round behind schedule in %llu ms\n",
455 (unsigned long long) ret.rel_value);
459 /* current round is based on best-known matching_bits */
460 matching_bits = ntohl (size_estimate_messages[estimate_index].matching_bits);
461 dist_delay = get_matching_bits_delay (matching_bits);
462 dist_delay += get_delay_randomization (matching_bits).rel_value;
463 ret.rel_value = (uint64_t) dist_delay;
465 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
466 "For round %llu, delay for %u matching bits is %llu ms\n",
467 (unsigned long long) current_timestamp.abs_value,
468 (unsigned int) matching_bits,
469 (unsigned long long) ret.rel_value);
471 /* now consider round start time and add delay to it */
472 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
473 return GNUNET_TIME_absolute_get_remaining (tgt);
476 return GNUNET_TIME_UNIT_FOREVER_REL;
481 * Task that triggers a NSE P2P transmission.
483 * @param cls the 'struct NSEPeerEntry'
484 * @param tc scheduler context
487 transmit_task (void *cls,
488 const struct GNUNET_SCHEDULER_TaskContext *tc);
492 * Called when core is ready to send a message we asked for
493 * out to the destination.
495 * @param cls closure (NULL)
496 * @param size number of bytes available in buf
497 * @param buf where the callee should write the message
498 * @return number of bytes written to buf
501 transmit_ready (void *cls, size_t size, void *buf)
503 struct NSEPeerEntry *peer_entry = cls;
506 peer_entry->th = NULL;
509 /* client disconnected */
512 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
513 idx = estimate_index;
514 if (peer_entry->previous_round == GNUNET_NO)
516 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
517 peer_entry->previous_round = GNUNET_YES;
518 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0),
522 if ( (ntohl (size_estimate_messages[idx].hop_count) == 0) &&
523 (GNUNET_SCHEDULER_NO_TASK != proof_task) )
525 GNUNET_STATISTICS_update (stats,
526 "# flood messages not generated (no proof yet)",
532 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
533 "In round %llu, sending to `%s' estimate with %u bits\n",
534 (unsigned long long) GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].timestamp).abs_value,
535 GNUNET_i2s (&peer_entry->id),
536 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
538 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
539 GNUNET_STATISTICS_update (stats,
540 "# flood messages started",
543 GNUNET_STATISTICS_update (stats,
544 "# flood messages transmitted",
548 &size_estimate_messages[idx],
549 sizeof (struct GNUNET_NSE_FloodMessage));
550 GNUNET_STATISTICS_update (stats,
551 "# flood messages sent",
554 return sizeof (struct GNUNET_NSE_FloodMessage);
559 * Task that triggers a NSE P2P transmission.
561 * @param cls the 'struct NSEPeerEntry'
562 * @param tc scheduler context
565 transmit_task (void *cls,
566 const struct GNUNET_SCHEDULER_TaskContext *tc)
568 struct NSEPeerEntry *peer_entry = cls;
570 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
572 = GNUNET_CORE_notify_transmit_ready (coreAPI,
575 GNUNET_TIME_UNIT_FOREVER_REL,
577 sizeof (struct GNUNET_NSE_FloodMessage),
578 &transmit_ready, peer_entry);
583 * We've sent on our flood message or one that we received which was
584 * validated and closer than ours. Update the global list of recent
585 * messages and the average. Also re-broadcast the message to any
589 update_network_size_estimate ()
591 struct GNUNET_NSE_ClientMessage em;
593 setup_estimate_message (&em);
594 GNUNET_SERVER_notification_context_broadcast (nc,
601 * Setup a flood message in our history array at the given
602 * slot offset for the given timestamp.
604 * @param slot index to use
605 * @param ts timestamp to use
608 setup_flood_message (unsigned int slot,
609 struct GNUNET_TIME_Absolute ts)
611 struct GNUNET_NSE_FloodMessage *fm;
612 uint32_t matching_bits;
614 matching_bits = get_matching_bits (ts, &my_identity);
615 fm = &size_estimate_messages[slot];
616 fm->header.size = htons (sizeof(struct GNUNET_NSE_FloodMessage));
617 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
618 fm->hop_count = htonl (0);
619 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
620 fm->purpose.size = htonl (sizeof(struct GNUNET_NSE_FloodMessage)
621 - sizeof (struct GNUNET_MessageHeader)
623 - sizeof (struct GNUNET_CRYPTO_RsaSignature));
624 fm->matching_bits = htonl (matching_bits);
625 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
626 fm->pkey = my_public_key;
627 fm->proof_of_work = my_proof;
628 GNUNET_CRYPTO_rsa_sign (my_private_key,
635 * Schedule transmission for the given peer for the current round based
636 * on what we know about the desired delay.
639 * @param key hash of peer identity
640 * @param value the 'struct NSEPeerEntry'
641 * @return GNUNET_OK (continue to iterate)
644 schedule_current_round (void *cls,
645 const GNUNET_HashCode *key,
648 struct NSEPeerEntry *peer_entry = value;
649 struct GNUNET_TIME_Relative delay;
651 if (peer_entry->th != NULL)
653 peer_entry->previous_round = GNUNET_NO;
656 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
658 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
659 peer_entry->previous_round = GNUNET_NO;
661 delay = get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
662 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
670 * Update our flood message to be sent (and our timestamps).
673 * @param tc context for this message
676 update_flood_message(void *cls,
677 const struct GNUNET_SCHEDULER_TaskContext *tc)
679 struct GNUNET_TIME_Relative offset;
682 flood_task = GNUNET_SCHEDULER_NO_TASK;
683 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
684 if (0 != offset.rel_value)
686 /* somehow run early, delay more */
688 = GNUNET_SCHEDULER_add_delayed (offset,
689 &update_flood_message,
693 current_timestamp = next_timestamp;
694 next_timestamp = GNUNET_TIME_absolute_add (current_timestamp,
695 gnunet_nse_interval);
696 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
697 if (estimate_count < HISTORY_SIZE)
699 if (next_timestamp.abs_value ==
700 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
702 /* we received a message for this round way early, use it! */
703 size_estimate_messages[estimate_index] = next_message;
704 size_estimate_messages[estimate_index].hop_count
705 = htonl (1 + ntohl (next_message.hop_count));
708 setup_flood_message (estimate_index, current_timestamp);
709 next_message.matching_bits = htonl (0); /* reset for 'next' round */
711 for (i = 0; i < HISTORY_SIZE; i++)
712 hop_count_max = GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count),
714 GNUNET_CONTAINER_multihashmap_iterate (peers,
715 &schedule_current_round,
717 flood_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
718 &update_flood_message, NULL);
723 * Count the leading zeroes in hash.
726 * @return the number of leading zero bits.
729 count_leading_zeroes(const GNUNET_HashCode *hash)
731 unsigned int hash_count;
734 while ((0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count)))
741 * Check whether the given public key
742 * and integer are a valid proof of work.
744 * @param pkey the public key
745 * @param val the integer
747 * @return GNUNET_YES if valid, GNUNET_NO if not
750 check_proof_of_work(const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
753 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(val)];
754 GNUNET_HashCode result;
759 memcpy (&buf[sizeof(val)],
761 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
762 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
763 return (count_leading_zeroes (&result) >= nse_work_required) ? GNUNET_YES : GNUNET_NO;
768 * Write our current proof to disk.
776 GNUNET_CONFIGURATION_get_value_filename (cfg,
780 if (sizeof (my_proof) !=
781 GNUNET_DISK_fn_write (proof,
784 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE))
785 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
794 * Find our proof of work.
796 * @param cls closure (unused)
797 * @param tc task context
800 find_proof (void *cls,
801 const struct GNUNET_SCHEDULER_TaskContext *tc)
803 #define ROUND_SIZE 10
805 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(uint64_t)];
806 GNUNET_HashCode result;
809 proof_task = GNUNET_SCHEDULER_NO_TASK;
810 memcpy (&buf[sizeof(uint64_t)],
812 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
815 while ( (counter != UINT64_MAX) && (i < ROUND_SIZE) )
820 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
821 if (nse_work_required <= count_leading_zeroes(&result))
825 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
826 "Proof of work found: %llu!\n",
827 (unsigned long long) GNUNET_ntohll (counter));
829 for (i=0;i<HISTORY_SIZE;i++)
830 if (ntohl (size_estimate_messages[i].hop_count) == 0)
832 size_estimate_messages[i].proof_of_work = my_proof;
833 GNUNET_CRYPTO_rsa_sign (my_private_key,
834 &size_estimate_messages[i].purpose,
835 &size_estimate_messages[i].signature);
843 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
847 "Testing proofs currently at %llu\n",
848 (unsigned long long) counter);
850 /* remember progress every 100 rounds */
858 proof_task = GNUNET_SCHEDULER_add_delayed (proof_find_delay,
865 * An incoming flood message has been received which claims
866 * to have more bits matching than any we know in this time
867 * period. Verify the signature and/or proof of work.
869 * @param incoming_flood the message to verify
871 * @return GNUNET_YES if the message is verified
872 * GNUNET_NO if the key/signature don't verify
875 verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood)
878 check_proof_of_work (&incoming_flood->pkey,
879 incoming_flood->proof_of_work))
881 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
882 _("Proof of work invalid: %llu!\n"),
883 (unsigned long long) GNUNET_ntohll (incoming_flood->proof_of_work));
888 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
889 &incoming_flood->purpose,
890 &incoming_flood->signature,
891 &incoming_flood->pkey))
901 * Update transmissions for the given peer for the current round based
902 * on updated proximity information.
904 * @param cls peer entry to exclude from updates
905 * @param key hash of peer identity
906 * @param value the 'struct NSEPeerEntry'
907 * @return GNUNET_OK (continue to iterate)
910 update_flood_times (void *cls,
911 const GNUNET_HashCode *key,
914 struct NSEPeerEntry *exclude = cls;
915 struct NSEPeerEntry *peer_entry = value;
916 struct GNUNET_TIME_Relative delay;
918 if (peer_entry->th != NULL)
919 return GNUNET_OK; /* already active */
920 if (peer_entry == exclude)
921 return GNUNET_OK; /* trigger of the update */
922 if (peer_entry->previous_round == GNUNET_NO)
924 /* still stuck in previous round, no point to update, check that
925 we are active here though... */
927 GNUNET_break (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK);
931 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
933 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
934 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
936 delay = get_transmit_delay (0);
937 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
945 * Core handler for size estimate flooding messages.
947 * @param cls closure unused
948 * @param message message
949 * @param peer peer identity this message is from (ignored)
950 * @param atsi performance data (ignored)
954 handle_p2p_size_estimate(void *cls,
955 const struct GNUNET_PeerIdentity *peer,
956 const struct GNUNET_MessageHeader *message,
957 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
959 const struct GNUNET_NSE_FloodMessage *incoming_flood;
960 struct GNUNET_TIME_Absolute ts;
961 struct NSEPeerEntry *peer_entry;
962 uint32_t matching_bits;
967 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
969 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
970 GNUNET_STATISTICS_update (stats,
971 "# flood messages received",
974 matching_bits = ntohl (incoming_flood->matching_bits);
979 struct GNUNET_PeerIdentity os;
981 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
982 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
984 GNUNET_snprintf (origin, sizeof (origin),
987 GNUNET_snprintf (pred, sizeof (pred),
990 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
991 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
992 (unsigned long long) GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
995 GNUNET_i2s (&my_identity),
996 (unsigned int) matching_bits);
1000 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1001 if (NULL == peer_entry)
1007 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1009 if (ts.abs_value == current_timestamp.abs_value)
1010 idx = estimate_index;
1011 else if (ts.abs_value == current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1012 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1013 else if (ts.abs_value == next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1015 if (matching_bits <= ntohl (next_message.matching_bits))
1016 return GNUNET_OK; /* ignore, simply too early/late */
1018 verify_message_crypto (incoming_flood))
1020 GNUNET_break_op (0);
1023 next_message = *incoming_flood;
1028 GNUNET_STATISTICS_update (stats,
1029 "# flood messages discarded (clock skew too large)",
1034 if (0 == (memcmp (peer, &my_identity, sizeof(struct GNUNET_PeerIdentity))))
1036 /* send to self, update our own estimate IF this also comes from us! */
1037 if (0 == memcmp (&incoming_flood->pkey,
1039 sizeof (my_public_key)))
1040 update_network_size_estimate ();
1043 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1045 /* cancel transmission from us to this peer for this round */
1046 if (idx == estimate_index)
1048 if (peer_entry->previous_round == GNUNET_YES)
1050 /* cancel any activity for current round */
1051 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1053 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1054 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1056 if (peer_entry->th != NULL)
1058 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1059 peer_entry->th = NULL;
1065 /* cancel previous round only */
1066 peer_entry->previous_round = GNUNET_YES;
1069 if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1071 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1073 if ( (idx < estimate_index) &&
1074 (peer_entry->previous_round == GNUNET_YES) )
1075 peer_entry->previous_round = GNUNET_NO;
1076 /* push back our result now, that peer is spreading bad information... */
1077 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1078 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1079 peer_entry->transmit_task = GNUNET_SCHEDULER_add_now (&transmit_task,
1081 /* Not closer than our most recent message, no need to do work here */
1082 GNUNET_STATISTICS_update (stats,
1083 "# flood messages ignored (had closer already)",
1089 verify_message_crypto (incoming_flood))
1091 GNUNET_break_op (0);
1094 size_estimate_messages[idx] = *incoming_flood;
1095 size_estimate_messages[idx].hop_count = htonl (ntohl (incoming_flood->hop_count) + 1);
1096 hop_count_max = GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
1099 /* have a new, better size estimate, inform clients */
1100 update_network_size_estimate ();
1103 GNUNET_CONTAINER_multihashmap_iterate (peers,
1104 &update_flood_times,
1112 * Method called whenever a peer connects.
1114 * @param cls closure
1115 * @param peer peer identity this notification is about
1116 * @param atsi performance data
1119 handle_core_connect(void *cls, const struct GNUNET_PeerIdentity *peer,
1120 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1122 struct NSEPeerEntry *peer_entry;
1125 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1126 "Peer `%s' connected to us\n",
1129 peer_entry = GNUNET_malloc(sizeof(struct NSEPeerEntry));
1130 peer_entry->id = *peer;
1131 GNUNET_CONTAINER_multihashmap_put (peers,
1134 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1136 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
1144 * Method called whenever a peer disconnects.
1146 * @param cls closure
1147 * @param peer peer identity this notification is about
1150 handle_core_disconnect(void *cls, const struct GNUNET_PeerIdentity *peer)
1152 struct NSEPeerEntry *pos;
1155 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1156 "Peer `%s' disconnected from us\n",
1159 pos = GNUNET_CONTAINER_multihashmap_get (peers,
1166 GNUNET_assert (GNUNET_YES ==
1167 GNUNET_CONTAINER_multihashmap_remove (peers,
1170 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1171 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1172 if (pos->th != NULL)
1173 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1179 * Task run during shutdown.
1185 shutdown_task(void *cls,
1186 const struct GNUNET_SCHEDULER_TaskContext *tc)
1188 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1190 GNUNET_SCHEDULER_cancel (flood_task);
1191 flood_task = GNUNET_SCHEDULER_NO_TASK;
1193 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1195 GNUNET_SCHEDULER_cancel (proof_task);
1196 proof_task = GNUNET_SCHEDULER_NO_TASK;
1197 write_proof (); /* remember progress */
1201 GNUNET_SERVER_notification_context_destroy (nc);
1204 if (coreAPI != NULL)
1206 GNUNET_CORE_disconnect (coreAPI);
1211 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1216 GNUNET_CONTAINER_multihashmap_destroy (peers);
1219 if (my_private_key != NULL)
1221 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1222 my_private_key = NULL;
1224 #if ENABLE_HISTOGRAM
1227 GNUNET_BIO_write_close (wh);
1235 * Called on core init/fail.
1237 * @param cls service closure
1238 * @param server handle to the server for this service
1239 * @param identity the public identity of this peer
1240 * @param publicKey the public key of this peer
1243 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1244 const struct GNUNET_PeerIdentity *identity,
1245 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1247 struct GNUNET_TIME_Absolute now;
1248 struct GNUNET_TIME_Absolute prev_time;
1254 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1255 "Connection to core FAILED!\n");
1257 GNUNET_SCHEDULER_shutdown ();
1260 GNUNET_assert (0 == memcmp (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity)));
1261 now = GNUNET_TIME_absolute_get ();
1262 current_timestamp.abs_value = (now.abs_value / gnunet_nse_interval.rel_value) * gnunet_nse_interval.rel_value;
1263 next_timestamp.abs_value = current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1265 for (i = 0; i < HISTORY_SIZE; i++)
1267 prev_time.abs_value = current_timestamp.abs_value - (HISTORY_SIZE - i - 1) * gnunet_nse_interval.rel_value;
1268 setup_flood_message (i, prev_time);
1270 estimate_index = HISTORY_SIZE - 1;
1273 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
1274 &update_flood_message, NULL);
1279 * Handle network size estimate clients.
1281 * @param cls closure
1282 * @param server the initialized server
1283 * @param c configuration to use
1286 run(void *cls, struct GNUNET_SERVER_Handle *server,
1287 const struct GNUNET_CONFIGURATION_Handle *c)
1292 static const struct GNUNET_SERVER_MessageHandler handlers[] =
1294 { &handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START, sizeof (struct GNUNET_MessageHeader) },
1295 { NULL, NULL, 0, 0 }
1297 static const struct GNUNET_CORE_MessageHandler core_handlers[] =
1299 { &handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, sizeof (struct GNUNET_NSE_FloodMessage) },
1305 GNUNET_CONFIGURATION_get_value_time (cfg,
1307 &gnunet_nse_interval)) ||
1309 GNUNET_CONFIGURATION_get_value_time (cfg,
1311 &proof_find_delay)) ||
1313 GNUNET_CONFIGURATION_get_value_number (cfg,
1315 &nse_work_required)) )
1317 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1318 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1319 GNUNET_SCHEDULER_shutdown ();
1322 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1324 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1325 _ ("Invalid work requirement for NSE service. Exiting.\n"));
1326 GNUNET_SCHEDULER_shutdown ();
1332 GNUNET_CONFIGURATION_get_value_filename (cfg,
1333 "GNUNETD", "HOSTKEY",
1336 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1337 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1338 GNUNET_SCHEDULER_shutdown ();
1341 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1342 GNUNET_free (keyfile);
1343 if (my_private_key == NULL)
1345 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1346 _("NSE service could not access hostkey. Exiting.\n"));
1347 GNUNET_SCHEDULER_shutdown ();
1350 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1351 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_identity.hashPubKey);
1353 GNUNET_CONFIGURATION_get_value_filename (cfg,
1357 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1358 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1359 if (my_private_key != NULL)
1361 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1362 my_private_key = NULL;
1364 GNUNET_SCHEDULER_shutdown ();
1367 if ( (GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1368 (sizeof (my_proof) !=
1369 GNUNET_DISK_fn_read (proof,
1371 sizeof (my_proof))) )
1373 GNUNET_free (proof);
1374 proof_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1378 peers = GNUNET_CONTAINER_multihashmap_create (128);
1379 GNUNET_SERVER_add_handlers (server, handlers);
1380 nc = GNUNET_SERVER_notification_context_create (server, 1);
1381 /* Connect to core service and register core handlers */
1382 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1383 CORE_QUEUE_SIZE, /* queue size */
1384 NULL, /* Closure passed to functions */
1385 &core_init, /* Call core_init once connected */
1386 &handle_core_connect, /* Handle connects */
1387 &handle_core_disconnect, /* Handle disconnects */
1388 NULL, /* Do we care about "status" updates? */
1389 NULL, /* Don't want notified about all incoming messages */
1390 GNUNET_NO, /* For header only inbound notification */
1391 NULL, /* Don't want notified about all outbound messages */
1392 GNUNET_NO, /* For header only outbound notification */
1393 core_handlers); /* Register these handlers */
1394 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1395 &shutdown_task, NULL);
1396 #if ENABLE_HISTOGRAM
1398 GNUNET_CONFIGURATION_get_value_filename (cfg,
1402 wh = GNUNET_BIO_write_open (proof);
1403 GNUNET_free (proof);
1406 if (coreAPI == NULL)
1408 GNUNET_SCHEDULER_shutdown ();
1411 stats = GNUNET_STATISTICS_create ("nse", cfg);
1416 * The main function for the statistics service.
1418 * @param argc number of arguments from the command line
1419 * @param argv command line arguments
1420 * @return 0 ok, 1 on error
1423 main(int argc, char * const *argv)
1425 return (GNUNET_OK == GNUNET_SERVICE_run (argc, argv,
1427 GNUNET_SERVICE_OPTION_NONE, &run,
1431 /* end of gnunet-service-nse.c */