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 NODELAYS GNUNET_YES
51 * Send messages on connect.
53 #define SEND_ON_CONNECT GNUNET_YES
56 * Should we generate a histogram with the time stamps of when we received
57 * NSE messages to disk? (for performance evaluation only, not useful in
60 #define ENABLE_HISTOGRAM GNUNET_YES
63 * Over how many values do we calculate the weighted average?
65 #define HISTORY_SIZE 8
68 * Size of the queue to core.
70 #define CORE_QUEUE_SIZE 2
73 * Message priority to use.
75 #define NSE_PRIORITY 5
78 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
80 static unsigned long long nse_work_required;
83 * Interval for sending network size estimation flood requests.
85 static struct GNUNET_TIME_Relative gnunet_nse_interval;
88 * Interval between proof find runs.
90 static struct GNUNET_TIME_Relative proof_find_delay;
94 static struct GNUNET_BIO_WriteHandle *wh;
99 * Per-peer information.
105 * Pending message for this peer.
107 struct GNUNET_MessageHeader *pending_message;
110 * Core handle for sending messages to this peer.
112 struct GNUNET_CORE_TransmitHandle *th;
115 * What is the identity of the peer?
117 struct GNUNET_PeerIdentity id;
120 * Task scheduled to send message to this peer.
122 GNUNET_SCHEDULER_TaskIdentifier transmit_task;
125 * Did we receive or send a message about the previous round
126 * to this peer yet? GNUNET_YES if the previous round has
127 * been taken care of.
134 * Network size estimate reply; sent when "this"
135 * peer's timer has run out before receiving a
136 * valid reply from another peer.
138 struct GNUNET_NSE_FloodMessage
141 * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
143 struct GNUNET_MessageHeader header;
146 * Number of hops this message has taken so far.
153 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
156 * The current timestamp value (which all
157 * peers should agree on).
159 struct GNUNET_TIME_AbsoluteNBO timestamp;
162 * Number of matching bits between the hash
163 * of timestamp and the initiator's public
166 uint32_t matching_bits;
169 * Public key of the originator.
171 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
174 * Proof of work, causing leading zeros when hashed with pkey.
176 uint64_t proof_of_work;
179 * Signature (over range specified in purpose).
181 struct GNUNET_CRYPTO_RsaSignature signature;
186 * Handle to our current configuration.
188 static const struct GNUNET_CONFIGURATION_Handle *cfg;
191 * Handle to the statistics service.
193 static struct GNUNET_STATISTICS_Handle *stats;
196 * Handle to the core service.
198 static struct GNUNET_CORE_Handle *coreAPI;
201 * Map of all connected peers.
203 static struct GNUNET_CONTAINER_MultiHashMap *peers;
206 * The current network size estimate. Number of bits matching on
209 static double current_size_estimate;
212 * The standard deviation of the last HISTORY_SIZE network
215 static double current_std_dev = NAN;
218 * Current hop counter estimate (estimate for network diameter).
220 static uint32_t hop_count_max;
223 * Message for the next round, if we got any.
225 static struct GNUNET_NSE_FloodMessage next_message;
228 * Array of recent size estimate messages.
230 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
233 * Index of most recent estimate.
235 static unsigned int estimate_index;
238 * Number of valid entries in the history.
240 static unsigned int estimate_count;
243 * Task scheduled to update our flood message for the next round.
245 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
248 * Task scheduled to compute our proof.
250 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
253 * Notification context, simplifies client broadcasts.
255 static struct GNUNET_SERVER_NotificationContext *nc;
258 * The next major time.
260 static struct GNUNET_TIME_Absolute next_timestamp;
263 * The current major time.
265 static struct GNUNET_TIME_Absolute current_timestamp;
268 * The public key of this peer.
270 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
273 * The private key of this peer.
275 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
278 * The peer identity of this peer.
280 static struct GNUNET_PeerIdentity my_identity;
283 * Proof of work for this peer.
285 static uint64_t my_proof;
289 * Initialize a message to clients with the current network
292 * @param em message to fill in
295 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
309 /* Weighted incremental algorithm for stddev according to West (1979) */
313 for (i = 0; i < estimate_count; i++)
315 val = htonl (size_estimate_messages[(estimate_index - i + HISTORY_SIZE)
316 % HISTORY_SIZE].matching_bits);
317 weight = 1; /* was: estimate_count + 1 - i; */
319 temp = weight + sumweight;
321 r = q * weight / temp;
322 sum += sumweight * q * r;
326 variance = sum / (sumweight - 1.0);
327 GNUNET_assert (variance >= 0);
328 std_dev = sqrt (variance);
329 current_std_dev = std_dev;
330 current_size_estimate = mean;
333 = htons (sizeof(struct GNUNET_NSE_ClientMessage));
335 = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
336 em->reserved = htonl (0);
337 em->timestamp = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get());
338 em->size_estimate = mean - 1.0/3.0;
339 em->std_deviation = std_dev;
340 GNUNET_STATISTICS_set (stats,
341 "# nodes in the network (estimate)",
342 (uint64_t) pow (2, mean - 1.0/3.0), GNUNET_NO);
347 * Handler for START message from client, triggers an
348 * immediate current network estimate notification.
349 * Also, we remember the client for updates upon future
350 * estimate measurements.
353 * @param client who sent the message
354 * @param message the message received
357 handle_start_message(void *cls, struct GNUNET_SERVER_Client *client,
358 const struct GNUNET_MessageHeader *message)
360 struct GNUNET_NSE_ClientMessage em;
363 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
364 "Received START message from client\n");
366 GNUNET_SERVER_notification_context_add (nc, client);
367 setup_estimate_message (&em);
368 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header, GNUNET_YES);
369 GNUNET_SERVER_receive_done (client, GNUNET_OK);
374 * How long should we delay a message to go the given number of
377 * @param matching_bits number of matching bits to consider
380 get_matching_bits_delay (uint32_t matching_bits)
382 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p'))*/
383 // S is next_timestamp (ignored in return value)
384 // f is frequency (gnunet_nse_interval)
385 // x is matching_bits
386 // p' is current_size_estimate
387 return ((double) gnunet_nse_interval.rel_value / (double) 2.0)
388 - ((gnunet_nse_interval.rel_value / M_PI) * atan (matching_bits - current_size_estimate));
393 * What delay randomization should we apply for a given number of matching bits?
395 * @param matching_bits number of matching bits
396 * @return random delay to apply
398 static struct GNUNET_TIME_Relative
399 get_delay_randomization (uint32_t matching_bits)
402 return GNUNET_TIME_UNIT_ZERO;
404 struct GNUNET_TIME_Relative ret;
406 if (matching_bits == 0)
407 return GNUNET_TIME_UNIT_ZERO;
408 ret.rel_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
409 (uint32_t) (get_matching_bits_delay (matching_bits - 1) / (double) (hop_count_max + 1)));
416 * Get the number of matching bits that the given timestamp has to the given peer ID.
418 * @param timestamp time to generate key
419 * @param id peer identity to compare with
420 * @return number of matching bits
423 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
424 const struct GNUNET_PeerIdentity *id)
426 GNUNET_HashCode timestamp_hash;
428 GNUNET_CRYPTO_hash (×tamp.abs_value,
429 sizeof(timestamp.abs_value),
431 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash,
437 * Get the transmission delay that should be applied for a
440 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
441 * 0 for the current round (based on our proximity to time key)
442 * @return delay that should be applied
444 static struct GNUNET_TIME_Relative
445 get_transmit_delay (int round_offset)
447 struct GNUNET_TIME_Relative ret;
448 struct GNUNET_TIME_Absolute tgt;
450 uint32_t matching_bits;
452 switch (round_offset)
455 /* previous round is randomized between 0 and 50 ms */
457 ret = GNUNET_TIME_UNIT_ZERO;
459 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
463 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
464 "Transmitting previous round behind schedule in %llu ms\n",
465 (unsigned long long) ret.rel_value);
469 /* current round is based on best-known matching_bits */
470 matching_bits = ntohl (size_estimate_messages[estimate_index].matching_bits);
471 dist_delay = get_matching_bits_delay (matching_bits);
472 dist_delay += get_delay_randomization (matching_bits).rel_value;
473 ret.rel_value = (uint64_t) dist_delay;
475 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
476 "For round %llu, delay for %u matching bits is %llu ms\n",
477 (unsigned long long) current_timestamp.abs_value,
478 (unsigned int) matching_bits,
479 (unsigned long long) ret.rel_value);
481 /* now consider round start time and add delay to it */
482 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
483 return GNUNET_TIME_absolute_get_remaining (tgt);
486 return GNUNET_TIME_UNIT_FOREVER_REL;
491 * Task that triggers a NSE P2P transmission.
493 * @param cls the 'struct NSEPeerEntry'
494 * @param tc scheduler context
497 transmit_task (void *cls,
498 const struct GNUNET_SCHEDULER_TaskContext *tc);
502 * Called when core is ready to send a message we asked for
503 * out to the destination.
505 * @param cls closure (NULL)
506 * @param size number of bytes available in buf
507 * @param buf where the callee should write the message
508 * @return number of bytes written to buf
511 transmit_ready (void *cls, size_t size, void *buf)
513 struct NSEPeerEntry *peer_entry = cls;
516 peer_entry->th = NULL;
519 /* client disconnected */
522 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
523 idx = estimate_index;
524 if (peer_entry->previous_round == GNUNET_NO)
526 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
527 peer_entry->previous_round = GNUNET_YES;
528 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0),
532 if ( (ntohl (size_estimate_messages[idx].hop_count) == 0) &&
533 (GNUNET_SCHEDULER_NO_TASK != proof_task) )
535 GNUNET_STATISTICS_update (stats,
536 "# flood messages not generated (no proof yet)",
542 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
543 "In round %llu, sending to `%s' estimate with %u bits\n",
544 (unsigned long long) GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].timestamp).abs_value,
545 GNUNET_i2s (&peer_entry->id),
546 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
548 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
549 GNUNET_STATISTICS_update (stats,
550 "# flood messages started",
553 GNUNET_STATISTICS_update (stats,
554 "# flood messages transmitted",
558 &size_estimate_messages[idx],
559 sizeof (struct GNUNET_NSE_FloodMessage));
560 GNUNET_STATISTICS_update (stats,
561 "# flood messages sent",
564 return sizeof (struct GNUNET_NSE_FloodMessage);
569 * Task that triggers a NSE P2P transmission.
571 * @param cls the 'struct NSEPeerEntry'
572 * @param tc scheduler context
575 transmit_task (void *cls,
576 const struct GNUNET_SCHEDULER_TaskContext *tc)
578 struct NSEPeerEntry *peer_entry = cls;
580 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
582 = GNUNET_CORE_notify_transmit_ready (coreAPI,
585 GNUNET_TIME_UNIT_FOREVER_REL,
587 sizeof (struct GNUNET_NSE_FloodMessage),
588 &transmit_ready, peer_entry);
593 * We've sent on our flood message or one that we received which was
594 * validated and closer than ours. Update the global list of recent
595 * messages and the average. Also re-broadcast the message to any
599 update_network_size_estimate ()
601 struct GNUNET_NSE_ClientMessage em;
603 setup_estimate_message (&em);
604 GNUNET_SERVER_notification_context_broadcast (nc,
611 * Setup a flood message in our history array at the given
612 * slot offset for the given timestamp.
614 * @param slot index to use
615 * @param ts timestamp to use
618 setup_flood_message (unsigned int slot,
619 struct GNUNET_TIME_Absolute ts)
621 struct GNUNET_NSE_FloodMessage *fm;
622 uint32_t matching_bits;
624 matching_bits = get_matching_bits (ts, &my_identity);
625 fm = &size_estimate_messages[slot];
626 fm->header.size = htons (sizeof(struct GNUNET_NSE_FloodMessage));
627 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
628 fm->hop_count = htonl (0);
629 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
630 fm->purpose.size = htonl (sizeof(struct GNUNET_NSE_FloodMessage)
631 - sizeof (struct GNUNET_MessageHeader)
633 - sizeof (struct GNUNET_CRYPTO_RsaSignature));
634 fm->matching_bits = htonl (matching_bits);
635 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
636 fm->pkey = my_public_key;
637 fm->proof_of_work = my_proof;
638 GNUNET_CRYPTO_rsa_sign (my_private_key,
645 * Schedule transmission for the given peer for the current round based
646 * on what we know about the desired delay.
649 * @param key hash of peer identity
650 * @param value the 'struct NSEPeerEntry'
651 * @return GNUNET_OK (continue to iterate)
654 schedule_current_round (void *cls,
655 const GNUNET_HashCode *key,
658 struct NSEPeerEntry *peer_entry = value;
659 struct GNUNET_TIME_Relative delay;
661 if (peer_entry->th != NULL)
663 peer_entry->previous_round = GNUNET_NO;
666 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
668 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
669 peer_entry->previous_round = GNUNET_NO;
671 delay = get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
672 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
680 * Update our flood message to be sent (and our timestamps).
683 * @param tc context for this message
686 update_flood_message(void *cls,
687 const struct GNUNET_SCHEDULER_TaskContext *tc)
689 struct GNUNET_TIME_Relative offset;
692 flood_task = GNUNET_SCHEDULER_NO_TASK;
693 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
694 if (0 != offset.rel_value)
696 /* somehow run early, delay more */
698 = GNUNET_SCHEDULER_add_delayed (offset,
699 &update_flood_message,
703 current_timestamp = next_timestamp;
704 next_timestamp = GNUNET_TIME_absolute_add (current_timestamp,
705 gnunet_nse_interval);
706 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
707 if (estimate_count < HISTORY_SIZE)
709 if (next_timestamp.abs_value ==
710 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
712 /* we received a message for this round way early, use it! */
713 size_estimate_messages[estimate_index] = next_message;
714 size_estimate_messages[estimate_index].hop_count
715 = htonl (1 + ntohl (next_message.hop_count));
718 setup_flood_message (estimate_index, current_timestamp);
719 next_message.matching_bits = htonl (0); /* reset for 'next' round */
721 for (i = 0; i < HISTORY_SIZE; i++)
722 hop_count_max = GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count),
724 GNUNET_CONTAINER_multihashmap_iterate (peers,
725 &schedule_current_round,
727 flood_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
728 &update_flood_message, NULL);
733 * Count the leading zeroes in hash.
736 * @return the number of leading zero bits.
739 count_leading_zeroes(const GNUNET_HashCode *hash)
741 unsigned int hash_count;
744 while ((0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count)))
751 * Check whether the given public key
752 * and integer are a valid proof of work.
754 * @param pkey the public key
755 * @param val the integer
757 * @return GNUNET_YES if valid, GNUNET_NO if not
760 check_proof_of_work(const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
763 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(val)];
764 GNUNET_HashCode result;
769 memcpy (&buf[sizeof(val)],
771 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
772 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
773 return (count_leading_zeroes (&result) >= nse_work_required) ? GNUNET_YES : GNUNET_NO;
778 * Write our current proof to disk.
786 GNUNET_CONFIGURATION_get_value_filename (cfg,
790 if (sizeof (my_proof) !=
791 GNUNET_DISK_fn_write (proof,
794 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE))
795 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
804 * Find our proof of work.
806 * @param cls closure (unused)
807 * @param tc task context
810 find_proof (void *cls,
811 const struct GNUNET_SCHEDULER_TaskContext *tc)
813 #define ROUND_SIZE 10
815 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(uint64_t)];
816 GNUNET_HashCode result;
819 proof_task = GNUNET_SCHEDULER_NO_TASK;
820 memcpy (&buf[sizeof(uint64_t)],
822 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
825 while ( (counter != UINT64_MAX) && (i < ROUND_SIZE) )
830 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
831 if (nse_work_required <= count_leading_zeroes(&result))
835 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
836 "Proof of work found: %llu!\n",
837 (unsigned long long) GNUNET_ntohll (counter));
839 for (i=0;i<HISTORY_SIZE;i++)
840 if (ntohl (size_estimate_messages[i].hop_count) == 0)
842 size_estimate_messages[i].proof_of_work = my_proof;
843 GNUNET_CRYPTO_rsa_sign (my_private_key,
844 &size_estimate_messages[i].purpose,
845 &size_estimate_messages[i].signature);
853 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
856 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
857 "Testing proofs currently at %llu\n",
858 (unsigned long long) counter);
860 /* remember progress every 100 rounds */
868 proof_task = GNUNET_SCHEDULER_add_delayed (proof_find_delay,
875 * An incoming flood message has been received which claims
876 * to have more bits matching than any we know in this time
877 * period. Verify the signature and/or proof of work.
879 * @param incoming_flood the message to verify
881 * @return GNUNET_YES if the message is verified
882 * GNUNET_NO if the key/signature don't verify
885 verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood)
888 check_proof_of_work (&incoming_flood->pkey,
889 incoming_flood->proof_of_work))
891 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
892 _("Proof of work invalid: %llu!\n"),
893 (unsigned long long) GNUNET_ntohll (incoming_flood->proof_of_work));
898 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
899 &incoming_flood->purpose,
900 &incoming_flood->signature,
901 &incoming_flood->pkey))
911 * Update transmissions for the given peer for the current round based
912 * on updated proximity information.
914 * @param cls peer entry to exclude from updates
915 * @param key hash of peer identity
916 * @param value the 'struct NSEPeerEntry'
917 * @return GNUNET_OK (continue to iterate)
920 update_flood_times (void *cls,
921 const GNUNET_HashCode *key,
924 struct NSEPeerEntry *exclude = cls;
925 struct NSEPeerEntry *peer_entry = value;
926 struct GNUNET_TIME_Relative delay;
928 if (peer_entry->th != NULL)
929 return GNUNET_OK; /* already active */
930 if (peer_entry == exclude)
931 return GNUNET_OK; /* trigger of the update */
932 if (peer_entry->previous_round == GNUNET_NO)
934 /* still stuck in previous round, no point to update, check that
935 we are active here though... */
936 GNUNET_break ( (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
937 (peer_entry->th != NULL) );
940 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
942 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
943 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
945 delay = get_transmit_delay (0);
946 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
954 * Core handler for size estimate flooding messages.
956 * @param cls closure unused
957 * @param message message
958 * @param peer peer identity this message is from (ignored)
959 * @param atsi performance data (ignored)
963 handle_p2p_size_estimate(void *cls,
964 const struct GNUNET_PeerIdentity *peer,
965 const struct GNUNET_MessageHeader *message,
966 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
968 const struct GNUNET_NSE_FloodMessage *incoming_flood;
969 struct GNUNET_TIME_Absolute ts;
970 struct NSEPeerEntry *peer_entry;
971 uint32_t matching_bits;
976 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
978 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
979 GNUNET_STATISTICS_update (stats,
980 "# flood messages received",
983 matching_bits = ntohl (incoming_flood->matching_bits);
988 struct GNUNET_PeerIdentity os;
990 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
991 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
993 GNUNET_snprintf (origin, sizeof (origin),
996 GNUNET_snprintf (pred, sizeof (pred),
999 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1000 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
1001 (unsigned long long) GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1004 GNUNET_i2s (&my_identity),
1005 (unsigned int) matching_bits);
1009 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1010 if (NULL == peer_entry)
1016 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1018 if (ts.abs_value == current_timestamp.abs_value)
1019 idx = estimate_index;
1020 else if (ts.abs_value == current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1021 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1022 else if (ts.abs_value == next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1024 if (matching_bits <= ntohl (next_message.matching_bits))
1025 return GNUNET_OK; /* ignore, simply too early/late */
1027 verify_message_crypto (incoming_flood))
1029 GNUNET_break_op (0);
1032 next_message = *incoming_flood;
1037 GNUNET_STATISTICS_update (stats,
1038 "# flood messages discarded (clock skew too large)",
1043 if (0 == (memcmp (peer, &my_identity, sizeof(struct GNUNET_PeerIdentity))))
1045 /* send to self, update our own estimate IF this also comes from us! */
1046 if (0 == memcmp (&incoming_flood->pkey,
1048 sizeof (my_public_key)))
1049 update_network_size_estimate ();
1052 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1054 /* cancel transmission from us to this peer for this round */
1055 if (idx == estimate_index)
1057 if (peer_entry->previous_round == GNUNET_YES)
1059 /* cancel any activity for current round */
1060 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1062 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1063 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1065 if (peer_entry->th != NULL)
1067 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1068 peer_entry->th = NULL;
1074 /* cancel previous round only */
1075 peer_entry->previous_round = GNUNET_YES;
1078 if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1080 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1082 if ( (idx < estimate_index) &&
1083 (peer_entry->previous_round == GNUNET_YES) )
1084 peer_entry->previous_round = GNUNET_NO;
1085 /* push back our result now, that peer is spreading bad information... */
1086 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1087 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1088 peer_entry->transmit_task = GNUNET_SCHEDULER_add_now (&transmit_task,
1090 /* Not closer than our most recent message, no need to do work here */
1091 GNUNET_STATISTICS_update (stats,
1092 "# flood messages ignored (had closer already)",
1098 verify_message_crypto (incoming_flood))
1100 GNUNET_break_op (0);
1103 size_estimate_messages[idx] = *incoming_flood;
1104 size_estimate_messages[idx].hop_count = htonl (ntohl (incoming_flood->hop_count) + 1);
1105 hop_count_max = GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
1108 /* have a new, better size estimate, inform clients */
1109 update_network_size_estimate ();
1112 GNUNET_CONTAINER_multihashmap_iterate (peers,
1113 &update_flood_times,
1121 * Method called whenever a peer connects.
1123 * @param cls closure
1124 * @param peer peer identity this notification is about
1125 * @param atsi performance data
1128 handle_core_connect(void *cls, const struct GNUNET_PeerIdentity *peer,
1129 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1131 struct NSEPeerEntry *peer_entry;
1134 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1135 "Peer `%s' connected to us\n",
1138 peer_entry = GNUNET_malloc(sizeof(struct NSEPeerEntry));
1139 peer_entry->id = *peer;
1140 GNUNET_CONTAINER_multihashmap_put (peers,
1143 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1145 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
1153 * Method called whenever a peer disconnects.
1155 * @param cls closure
1156 * @param peer peer identity this notification is about
1159 handle_core_disconnect(void *cls, const struct GNUNET_PeerIdentity *peer)
1161 struct NSEPeerEntry *pos;
1164 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1165 "Peer `%s' disconnected from us\n",
1168 pos = GNUNET_CONTAINER_multihashmap_get (peers,
1175 GNUNET_assert (GNUNET_YES ==
1176 GNUNET_CONTAINER_multihashmap_remove (peers,
1179 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1180 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1181 if (pos->th != NULL)
1182 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1188 * Task run during shutdown.
1194 shutdown_task(void *cls,
1195 const struct GNUNET_SCHEDULER_TaskContext *tc)
1197 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1199 GNUNET_SCHEDULER_cancel (flood_task);
1200 flood_task = GNUNET_SCHEDULER_NO_TASK;
1202 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1204 GNUNET_SCHEDULER_cancel (proof_task);
1205 proof_task = GNUNET_SCHEDULER_NO_TASK;
1206 write_proof (); /* remember progress */
1210 GNUNET_SERVER_notification_context_destroy (nc);
1213 if (coreAPI != NULL)
1215 GNUNET_CORE_disconnect (coreAPI);
1220 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1225 GNUNET_CONTAINER_multihashmap_destroy (peers);
1228 if (my_private_key != NULL)
1230 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1231 my_private_key = NULL;
1233 #if ENABLE_HISTOGRAM
1236 GNUNET_BIO_write_close (wh);
1244 * Called on core init/fail.
1246 * @param cls service closure
1247 * @param server handle to the server for this service
1248 * @param identity the public identity of this peer
1249 * @param publicKey the public key of this peer
1252 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1253 const struct GNUNET_PeerIdentity *identity,
1254 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1256 struct GNUNET_TIME_Absolute now;
1257 struct GNUNET_TIME_Absolute prev_time;
1263 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1264 "Connection to core FAILED!\n");
1266 GNUNET_SCHEDULER_shutdown ();
1269 GNUNET_assert (0 == memcmp (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity)));
1270 now = GNUNET_TIME_absolute_get ();
1271 current_timestamp.abs_value = (now.abs_value / gnunet_nse_interval.rel_value) * gnunet_nse_interval.rel_value;
1272 next_timestamp.abs_value = current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1274 for (i = 0; i < HISTORY_SIZE; i++)
1276 prev_time.abs_value = current_timestamp.abs_value - (HISTORY_SIZE - i - 1) * gnunet_nse_interval.rel_value;
1277 setup_flood_message (i, prev_time);
1279 estimate_index = HISTORY_SIZE - 1;
1282 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
1283 &update_flood_message, NULL);
1288 * Handle network size estimate clients.
1290 * @param cls closure
1291 * @param server the initialized server
1292 * @param c configuration to use
1295 run(void *cls, struct GNUNET_SERVER_Handle *server,
1296 const struct GNUNET_CONFIGURATION_Handle *c)
1301 static const struct GNUNET_SERVER_MessageHandler handlers[] =
1303 { &handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START, sizeof (struct GNUNET_MessageHeader) },
1304 { NULL, NULL, 0, 0 }
1306 static const struct GNUNET_CORE_MessageHandler core_handlers[] =
1308 { &handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, sizeof (struct GNUNET_NSE_FloodMessage) },
1314 GNUNET_CONFIGURATION_get_value_time (cfg,
1316 &gnunet_nse_interval)) ||
1318 GNUNET_CONFIGURATION_get_value_time (cfg,
1320 &proof_find_delay)) ||
1322 GNUNET_CONFIGURATION_get_value_number (cfg,
1324 &nse_work_required)) )
1326 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1327 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1328 GNUNET_SCHEDULER_shutdown ();
1331 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1333 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1334 _ ("Invalid work requirement for NSE service. Exiting.\n"));
1335 GNUNET_SCHEDULER_shutdown ();
1341 GNUNET_CONFIGURATION_get_value_filename (cfg,
1342 "GNUNETD", "HOSTKEY",
1345 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1346 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1347 GNUNET_SCHEDULER_shutdown ();
1350 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1351 GNUNET_free (keyfile);
1352 if (my_private_key == NULL)
1354 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1355 _("NSE service could not access hostkey. Exiting.\n"));
1356 GNUNET_SCHEDULER_shutdown ();
1359 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1360 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_identity.hashPubKey);
1362 GNUNET_CONFIGURATION_get_value_filename (cfg,
1366 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1367 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1368 if (my_private_key != NULL)
1370 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1371 my_private_key = NULL;
1373 GNUNET_SCHEDULER_shutdown ();
1376 if ( (GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1377 (sizeof (my_proof) !=
1378 GNUNET_DISK_fn_read (proof,
1380 sizeof (my_proof))) )
1382 GNUNET_free (proof);
1383 proof_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1387 peers = GNUNET_CONTAINER_multihashmap_create (128);
1388 GNUNET_SERVER_add_handlers (server, handlers);
1389 nc = GNUNET_SERVER_notification_context_create (server, 1);
1390 /* Connect to core service and register core handlers */
1391 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1392 CORE_QUEUE_SIZE, /* queue size */
1393 NULL, /* Closure passed to functions */
1394 &core_init, /* Call core_init once connected */
1395 &handle_core_connect, /* Handle connects */
1396 &handle_core_disconnect, /* Handle disconnects */
1397 NULL, /* Do we care about "status" updates? */
1398 NULL, /* Don't want notified about all incoming messages */
1399 GNUNET_NO, /* For header only inbound notification */
1400 NULL, /* Don't want notified about all outbound messages */
1401 GNUNET_NO, /* For header only outbound notification */
1402 core_handlers); /* Register these handlers */
1403 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1404 &shutdown_task, NULL);
1405 #if ENABLE_HISTOGRAM
1407 GNUNET_CONFIGURATION_get_value_filename (cfg,
1411 wh = GNUNET_BIO_write_open (proof);
1412 GNUNET_free (proof);
1415 if (coreAPI == NULL)
1417 GNUNET_SCHEDULER_shutdown ();
1420 stats = GNUNET_STATISTICS_create ("nse", cfg);
1425 * The main function for the statistics service.
1427 * @param argc number of arguments from the command line
1428 * @param argv command line arguments
1429 * @return 0 ok, 1 on error
1432 main(int argc, char * const *argv)
1434 return (GNUNET_OK == GNUNET_SERVICE_run (argc, argv,
1436 GNUNET_SERVICE_OPTION_NONE, &run,
1440 /* end of gnunet-service-nse.c */