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 * Should we generate a histogram with the time stamps of when we received
50 * NSE messages to disk? (for performance evaluation only, not useful in
53 #define ENABLE_HISTOGRAM GNUNET_YES
56 * Over how many values do we calculate the weighted average?
58 #define HISTORY_SIZE 8
61 * Size of the queue to core.
63 #define CORE_QUEUE_SIZE 2
66 * Message priority to use.
68 #define NSE_PRIORITY 5
71 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
73 static unsigned long long nse_work_required;
76 * Interval for sending network size estimation flood requests.
78 static struct GNUNET_TIME_Relative gnunet_nse_interval;
81 * Interval between proof find runs.
83 static struct GNUNET_TIME_Relative proof_find_delay;
87 static struct GNUNET_BIO_WriteHandle *wh;
92 * Per-peer information.
98 * Pending message for this peer.
100 struct GNUNET_MessageHeader *pending_message;
103 * Core handle for sending messages to this peer.
105 struct GNUNET_CORE_TransmitHandle *th;
108 * What is the identity of the peer?
110 struct GNUNET_PeerIdentity id;
113 * Task scheduled to send message to this peer.
115 GNUNET_SCHEDULER_TaskIdentifier transmit_task;
118 * Did we receive or send a message about the previous round
119 * to this peer yet? GNUNET_YES if the previous round has
120 * been taken care of.
127 * Network size estimate reply; sent when "this"
128 * peer's timer has run out before receiving a
129 * valid reply from another peer.
131 struct GNUNET_NSE_FloodMessage
134 * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
136 struct GNUNET_MessageHeader header;
139 * Number of hops this message has taken so far.
146 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
149 * The current timestamp value (which all
150 * peers should agree on).
152 struct GNUNET_TIME_AbsoluteNBO timestamp;
155 * Number of matching bits between the hash
156 * of timestamp and the initiator's public
159 uint32_t matching_bits;
162 * Public key of the originator.
164 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
167 * Proof of work, causing leading zeros when hashed with pkey.
169 uint64_t proof_of_work;
172 * Signature (over range specified in purpose).
174 struct GNUNET_CRYPTO_RsaSignature signature;
179 * Handle to our current configuration.
181 static const struct GNUNET_CONFIGURATION_Handle *cfg;
184 * Handle to the statistics service.
186 static struct GNUNET_STATISTICS_Handle *stats;
189 * Handle to the core service.
191 static struct GNUNET_CORE_Handle *coreAPI;
194 * Map of all connected peers.
196 static struct GNUNET_CONTAINER_MultiHashMap *peers;
199 * The current network size estimate. Number of bits matching on
202 static double current_size_estimate;
205 * The standard deviation of the last HISTORY_SIZE network
208 static double current_std_dev = NAN;
211 * Current hop counter estimate (estimate for network diameter).
213 static uint32_t hop_count_max;
216 * Message for the next round, if we got any.
218 static struct GNUNET_NSE_FloodMessage next_message;
221 * Array of recent size estimate messages.
223 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
226 * Index of most recent estimate.
228 static unsigned int estimate_index;
231 * Number of valid entries in the history.
233 static unsigned int estimate_count;
236 * Task scheduled to update our flood message for the next round.
238 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
241 * Task scheduled to compute our proof.
243 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
246 * Notification context, simplifies client broadcasts.
248 static struct GNUNET_SERVER_NotificationContext *nc;
251 * The next major time.
253 static struct GNUNET_TIME_Absolute next_timestamp;
256 * The current major time.
258 static struct GNUNET_TIME_Absolute current_timestamp;
261 * The public key of this peer.
263 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
266 * The private key of this peer.
268 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
271 * The peer identity of this peer.
273 static struct GNUNET_PeerIdentity my_identity;
276 * Proof of work for this peer.
278 static uint64_t my_proof;
282 * Initialize a message to clients with the current network
285 * @param em message to fill in
288 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
302 /* Weighted incremental algorithm for stddev according to West (1979) */
306 for (i=0;i<estimate_count; i++)
308 val = htonl (size_estimate_messages[(estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE].matching_bits);
309 weight = estimate_count + 1 - i;
311 temp = weight + sumweight;
313 r = q * weight / temp;
314 sum += sumweight * q * r;
318 variance = sum / (sumweight - 1.0);
319 GNUNET_assert (variance >= 0);
320 std_dev = sqrt (variance);
321 current_std_dev = std_dev;
322 current_size_estimate = mean;
325 = htons (sizeof(struct GNUNET_NSE_ClientMessage));
327 = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
328 em->reserved = htonl (0);
329 em->size_estimate = mean - 0.5;
330 em->std_deviation = std_dev;
331 GNUNET_STATISTICS_set (stats,
332 "# nodes in the network (estimate)",
333 (uint64_t) pow (2, mean - 0.5), GNUNET_NO);
338 * Handler for START message from client, triggers an
339 * immediate current network estimate notification.
340 * Also, we remember the client for updates upon future
341 * estimate measurements.
344 * @param client who sent the message
345 * @param message the message received
348 handle_start_message(void *cls, struct GNUNET_SERVER_Client *client,
349 const struct GNUNET_MessageHeader *message)
351 struct GNUNET_NSE_ClientMessage em;
354 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
355 "Received START message from client\n");
357 GNUNET_SERVER_notification_context_add (nc, client);
358 setup_estimate_message (&em);
359 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header, GNUNET_YES);
360 GNUNET_SERVER_receive_done (client, GNUNET_OK);
365 * How long should we delay a message to go the given number of
368 * @param matching_bits number of matching bits to consider
371 get_matching_bits_delay (uint32_t matching_bits)
373 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p'))*/
374 // S is next_timestamp (ignored in return value)
375 // f is frequency (gnunet_nse_interval)
376 // x is matching_bits
377 // p' is current_size_estimate
378 return ((double) gnunet_nse_interval.rel_value / (double) 2.0)
379 - ((gnunet_nse_interval.rel_value / M_PI) * atan (matching_bits - current_size_estimate));
384 * What delay randomization should we apply for a given number of matching bits?
386 * @param matching_bits number of matching bits
387 * @return random delay to apply
389 static struct GNUNET_TIME_Relative
390 get_delay_randomization (uint32_t matching_bits)
392 struct GNUNET_TIME_Relative ret;
394 if (matching_bits == 0)
395 return GNUNET_TIME_UNIT_ZERO;
396 ret.rel_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
397 (uint32_t) (get_matching_bits_delay (matching_bits - 1) / (double) (hop_count_max + 1)));
403 * Get the number of matching bits that the given timestamp has to the given peer ID.
405 * @param timestamp time to generate key
406 * @param id peer identity to compare with
407 * @return number of matching bits
410 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
411 const struct GNUNET_PeerIdentity *id)
413 GNUNET_HashCode timestamp_hash;
415 GNUNET_CRYPTO_hash (×tamp.abs_value,
416 sizeof(timestamp.abs_value),
418 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash,
424 * Get the transmission delay that should be applied for a
427 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
428 * 0 for the current round (based on our proximity to time key)
429 * @return delay that should be applied
431 static struct GNUNET_TIME_Relative
432 get_transmit_delay (int round_offset)
434 struct GNUNET_TIME_Relative ret;
435 struct GNUNET_TIME_Absolute tgt;
437 uint32_t matching_bits;
439 switch (round_offset)
442 /* previous round is randomized between 0 and 50 ms */
443 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
446 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
447 "Transmitting previous round behind schedule in %llu ms\n",
448 (unsigned long long) ret.rel_value);
452 /* current round is based on best-known matching_bits */
453 matching_bits = ntohl (size_estimate_messages[estimate_index].matching_bits);
454 dist_delay = get_matching_bits_delay (matching_bits);
455 dist_delay += get_delay_randomization (matching_bits).rel_value;
456 ret.rel_value = (uint64_t) dist_delay;
458 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
459 "For round %llu, delay for %u matching bits is %llu ms\n",
460 (unsigned long long) current_timestamp.abs_value,
461 (unsigned int) matching_bits,
462 (unsigned long long) ret.rel_value);
464 /* now consider round start time and add delay to it */
465 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
466 return GNUNET_TIME_absolute_get_remaining (tgt);
469 return GNUNET_TIME_UNIT_FOREVER_REL;
474 * Task that triggers a NSE P2P transmission.
476 * @param cls the 'struct NSEPeerEntry'
477 * @param tc scheduler context
480 transmit_task (void *cls,
481 const struct GNUNET_SCHEDULER_TaskContext *tc);
485 * Called when core is ready to send a message we asked for
486 * out to the destination.
488 * @param cls closure (NULL)
489 * @param size number of bytes available in buf
490 * @param buf where the callee should write the message
491 * @return number of bytes written to buf
494 transmit_ready (void *cls, size_t size, void *buf)
496 struct NSEPeerEntry *peer_entry = cls;
499 peer_entry->th = NULL;
502 /* client disconnected */
505 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
506 idx = estimate_index;
507 if (peer_entry->previous_round == GNUNET_NO)
509 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
510 peer_entry->previous_round = GNUNET_YES;
511 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0),
515 if ( (ntohl (size_estimate_messages[idx].hop_count) == 0) &&
516 (GNUNET_SCHEDULER_NO_TASK != proof_task) )
518 GNUNET_STATISTICS_update (stats,
519 "# flood messages not generated (no proof yet)",
525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
526 "In round %llu, sending to `%s' estimate with %u bits\n",
527 (unsigned long long) GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].timestamp).abs_value,
528 GNUNET_i2s (&peer_entry->id),
529 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
531 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
532 GNUNET_STATISTICS_update (stats,
533 "# flood messages started",
536 GNUNET_STATISTICS_update (stats,
537 "# flood messages transmitted",
541 &size_estimate_messages[idx],
542 sizeof (struct GNUNET_NSE_FloodMessage));
543 GNUNET_STATISTICS_update (stats,
544 "# flood messages sent",
547 return sizeof (struct GNUNET_NSE_FloodMessage);
552 * Task that triggers a NSE P2P transmission.
554 * @param cls the 'struct NSEPeerEntry'
555 * @param tc scheduler context
558 transmit_task (void *cls,
559 const struct GNUNET_SCHEDULER_TaskContext *tc)
561 struct NSEPeerEntry *peer_entry = cls;
563 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
565 = GNUNET_CORE_notify_transmit_ready (coreAPI,
568 GNUNET_TIME_UNIT_FOREVER_REL,
570 sizeof (struct GNUNET_NSE_FloodMessage),
571 &transmit_ready, peer_entry);
576 * We've sent on our flood message or one that we received which was
577 * validated and closer than ours. Update the global list of recent
578 * messages and the average. Also re-broadcast the message to any
582 update_network_size_estimate ()
584 struct GNUNET_NSE_ClientMessage em;
586 setup_estimate_message (&em);
587 GNUNET_SERVER_notification_context_broadcast (nc,
594 * Setup a flood message in our history array at the given
595 * slot offset for the given timestamp.
597 * @param slot index to use
598 * @param ts timestamp to use
601 setup_flood_message (unsigned int slot,
602 struct GNUNET_TIME_Absolute ts)
604 struct GNUNET_NSE_FloodMessage *fm;
605 uint32_t matching_bits;
607 matching_bits = get_matching_bits (ts, &my_identity);
608 fm = &size_estimate_messages[slot];
609 fm->header.size = htons (sizeof(struct GNUNET_NSE_FloodMessage));
610 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
611 fm->hop_count = htonl (0);
612 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
613 fm->purpose.size = htonl (sizeof(struct GNUNET_NSE_FloodMessage)
614 - sizeof (struct GNUNET_MessageHeader)
616 - sizeof (struct GNUNET_CRYPTO_RsaSignature));
617 fm->matching_bits = htonl (matching_bits);
618 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
619 fm->pkey = my_public_key;
620 fm->proof_of_work = my_proof;
621 GNUNET_CRYPTO_rsa_sign (my_private_key,
628 * Schedule transmission for the given peer for the current round based
629 * on what we know about the desired delay.
632 * @param key hash of peer identity
633 * @param value the 'struct NSEPeerEntry'
634 * @return GNUNET_OK (continue to iterate)
637 schedule_current_round (void *cls,
638 const GNUNET_HashCode *key,
641 struct NSEPeerEntry *peer_entry = value;
642 struct GNUNET_TIME_Relative delay;
644 if (peer_entry->th != NULL)
646 peer_entry->previous_round = GNUNET_NO;
649 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
651 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
652 peer_entry->previous_round = GNUNET_NO;
654 delay = get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
655 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
663 * Update our flood message to be sent (and our timestamps).
666 * @param tc context for this message
669 update_flood_message(void *cls,
670 const struct GNUNET_SCHEDULER_TaskContext *tc)
672 struct GNUNET_TIME_Relative offset;
675 flood_task = GNUNET_SCHEDULER_NO_TASK;
676 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
677 if (0 != offset.rel_value)
679 /* somehow run early, delay more */
681 = GNUNET_SCHEDULER_add_delayed (offset,
682 &update_flood_message,
686 current_timestamp = next_timestamp;
687 next_timestamp = GNUNET_TIME_absolute_add (current_timestamp,
688 gnunet_nse_interval);
689 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
690 if (estimate_count < HISTORY_SIZE)
692 if (next_timestamp.abs_value ==
693 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
695 /* we received a message for this round way early, use it! */
696 size_estimate_messages[estimate_index] = next_message;
697 size_estimate_messages[estimate_index].hop_count
698 = htonl (1 + ntohl (next_message.hop_count));
701 setup_flood_message (estimate_index, current_timestamp);
702 next_message.matching_bits = htonl (0); /* reset for 'next' round */
704 for (i=0;i<HISTORY_SIZE;i++)
705 hop_count_max = GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count),
707 GNUNET_CONTAINER_multihashmap_iterate (peers,
708 &schedule_current_round,
710 flood_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
711 &update_flood_message, NULL);
716 * Count the leading zeroes in hash.
719 * @return the number of leading zero bits.
722 count_leading_zeroes(const GNUNET_HashCode *hash)
724 unsigned int hash_count;
727 while ((0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count)))
734 * Check whether the given public key
735 * and integer are a valid proof of work.
737 * @param pkey the public key
738 * @param val the integer
740 * @return GNUNET_YES if valid, GNUNET_NO if not
743 check_proof_of_work(const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
746 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(val)];
747 GNUNET_HashCode result;
752 memcpy (&buf[sizeof(val)],
754 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
755 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
756 return (count_leading_zeroes (&result) >= nse_work_required) ? GNUNET_YES : GNUNET_NO;
761 * Write our current proof to disk.
769 GNUNET_CONFIGURATION_get_value_filename (cfg,
773 if (sizeof (my_proof) !=
774 GNUNET_DISK_fn_write (proof,
777 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE))
778 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
787 * Find our proof of work.
789 * @param cls closure (unused)
790 * @param tc task context
793 find_proof (void *cls,
794 const struct GNUNET_SCHEDULER_TaskContext *tc)
796 #define ROUND_SIZE 10
798 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(uint64_t)];
799 GNUNET_HashCode result;
802 proof_task = GNUNET_SCHEDULER_NO_TASK;
803 memcpy (&buf[sizeof(uint64_t)],
805 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
808 while ( (counter != UINT64_MAX) && (i < ROUND_SIZE) )
813 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
814 if (nse_work_required <= count_leading_zeroes(&result))
818 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
819 "Proof of work found: %llu!\n",
820 (unsigned long long) GNUNET_ntohll (counter));
822 for (i=0;i<HISTORY_SIZE;i++)
823 if (ntohl (size_estimate_messages[i].hop_count) == 0)
825 size_estimate_messages[i].proof_of_work = my_proof;
826 GNUNET_CRYPTO_rsa_sign (my_private_key,
827 &size_estimate_messages[i].purpose,
828 &size_estimate_messages[i].signature);
836 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
840 "Testing proofs currently at %llu\n",
841 (unsigned long long) counter);
843 /* remember progress every 100 rounds */
851 proof_task = GNUNET_SCHEDULER_add_delayed (proof_find_delay,
858 * An incoming flood message has been received which claims
859 * to have more bits matching than any we know in this time
860 * period. Verify the signature and/or proof of work.
862 * @param incoming_flood the message to verify
864 * @return GNUNET_YES if the message is verified
865 * GNUNET_NO if the key/signature don't verify
868 verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood)
871 check_proof_of_work (&incoming_flood->pkey,
872 incoming_flood->proof_of_work))
874 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
875 _("Proof of work invalid: %llu!\n"),
876 (unsigned long long) GNUNET_ntohll (incoming_flood->proof_of_work));
881 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
882 &incoming_flood->purpose,
883 &incoming_flood->signature,
884 &incoming_flood->pkey))
894 * Update transmissions for the given peer for the current round based
895 * on updated proximity information.
897 * @param cls peer entry to exclude from updates
898 * @param key hash of peer identity
899 * @param value the 'struct NSEPeerEntry'
900 * @return GNUNET_OK (continue to iterate)
903 update_flood_times (void *cls,
904 const GNUNET_HashCode *key,
907 struct NSEPeerEntry *exclude = cls;
908 struct NSEPeerEntry *peer_entry = value;
909 struct GNUNET_TIME_Relative delay;
911 if (peer_entry->th != NULL)
912 return GNUNET_OK; /* already active */
913 if (peer_entry == exclude)
914 return GNUNET_OK; /* trigger of the update */
915 if (peer_entry->previous_round == GNUNET_NO)
917 /* still stuck in previous round, no point to update, check that
918 we are active here though... */
919 GNUNET_break (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK);
922 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
924 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
925 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
927 delay = get_transmit_delay (0);
928 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
936 * Core handler for size estimate flooding messages.
938 * @param cls closure unused
939 * @param message message
940 * @param peer peer identity this message is from (ignored)
941 * @param atsi performance data (ignored)
945 handle_p2p_size_estimate(void *cls,
946 const struct GNUNET_PeerIdentity *peer,
947 const struct GNUNET_MessageHeader *message,
948 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
950 const struct GNUNET_NSE_FloodMessage *incoming_flood;
951 struct GNUNET_TIME_Absolute ts;
952 struct NSEPeerEntry *peer_entry;
953 uint32_t matching_bits;
958 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
960 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
961 GNUNET_STATISTICS_update (stats,
962 "# flood messages received",
965 matching_bits = ntohl (incoming_flood->matching_bits);
970 struct GNUNET_PeerIdentity os;
972 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
973 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
975 GNUNET_snprintf (origin, sizeof (origin),
978 GNUNET_snprintf (pred, sizeof (pred),
981 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
982 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
983 (unsigned long long) GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
986 GNUNET_i2s (&my_identity),
987 (unsigned int) matching_bits);
991 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
992 if (NULL == peer_entry)
997 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
998 if (ts.abs_value == current_timestamp.abs_value)
999 idx = estimate_index;
1000 else if (ts.abs_value == current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1001 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1002 else if (ts.abs_value == next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1004 if (matching_bits <= ntohl (next_message.matching_bits))
1005 return GNUNET_OK; /* ignore, simply too early/late */
1007 verify_message_crypto (incoming_flood))
1009 GNUNET_break_op (0);
1012 next_message = *incoming_flood;
1017 GNUNET_STATISTICS_update (stats,
1018 "# flood messages discarded (clock skew too large)",
1023 if (0 == (memcmp (peer, &my_identity, sizeof(struct GNUNET_PeerIdentity))))
1025 /* send to self, update our own estimate IF this also comes from us! */
1026 if (0 == memcmp (&incoming_flood->pkey,
1028 sizeof (my_public_key)))
1029 update_network_size_estimate ();
1032 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1034 /* cancel transmission from us to this peer for this round */
1035 if (idx == estimate_index)
1037 if (peer_entry->previous_round == GNUNET_YES)
1039 /* cancel any activity for current round */
1040 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1042 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1043 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1045 if (peer_entry->th != NULL)
1047 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1048 peer_entry->th = NULL;
1054 /* cancel previous round only */
1055 peer_entry->previous_round = GNUNET_YES;
1058 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1060 /* Not closer than our most recent message, no need to do work here */
1061 GNUNET_STATISTICS_update (stats,
1062 "# flood messages ignored (had closer already)",
1068 verify_message_crypto (incoming_flood))
1070 GNUNET_break_op (0);
1073 size_estimate_messages[idx] = *incoming_flood;
1074 size_estimate_messages[idx].hop_count = htonl (ntohl (incoming_flood->hop_count) + 1);
1075 hop_count_max = GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
1078 /* have a new, better size estimate, inform clients */
1079 update_network_size_estimate ();
1082 GNUNET_CONTAINER_multihashmap_iterate (peers,
1083 &update_flood_times,
1091 * Method called whenever a peer connects.
1093 * @param cls closure
1094 * @param peer peer identity this notification is about
1095 * @param atsi performance data
1098 handle_core_connect(void *cls, const struct GNUNET_PeerIdentity *peer,
1099 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1101 struct NSEPeerEntry *peer_entry;
1104 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1105 "Peer `%s' connected to us\n",
1108 peer_entry = GNUNET_malloc(sizeof(struct NSEPeerEntry));
1109 peer_entry->id = *peer;
1110 GNUNET_CONTAINER_multihashmap_put (peers,
1113 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1114 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
1121 * Method called whenever a peer disconnects.
1123 * @param cls closure
1124 * @param peer peer identity this notification is about
1127 handle_core_disconnect(void *cls, const struct GNUNET_PeerIdentity *peer)
1129 struct NSEPeerEntry *pos;
1132 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1133 "Peer `%s' disconnected from us\n",
1136 pos = GNUNET_CONTAINER_multihashmap_get (peers,
1143 GNUNET_assert (GNUNET_YES ==
1144 GNUNET_CONTAINER_multihashmap_remove (peers,
1147 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1148 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1149 if (pos->th != NULL)
1150 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1156 * Task run during shutdown.
1162 shutdown_task(void *cls,
1163 const struct GNUNET_SCHEDULER_TaskContext *tc)
1165 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1167 GNUNET_SCHEDULER_cancel (flood_task);
1168 flood_task = GNUNET_SCHEDULER_NO_TASK;
1170 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1172 GNUNET_SCHEDULER_cancel (proof_task);
1173 proof_task = GNUNET_SCHEDULER_NO_TASK;
1174 write_proof (); /* remember progress */
1178 GNUNET_SERVER_notification_context_destroy (nc);
1181 if (coreAPI != NULL)
1183 GNUNET_CORE_disconnect (coreAPI);
1188 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1193 GNUNET_CONTAINER_multihashmap_destroy (peers);
1196 if (my_private_key != NULL)
1198 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1199 my_private_key = NULL;
1201 #if ENABLE_HISTOGRAM
1204 GNUNET_BIO_write_close (wh);
1212 * Called on core init/fail.
1214 * @param cls service closure
1215 * @param server handle to the server for this service
1216 * @param identity the public identity of this peer
1217 * @param publicKey the public key of this peer
1220 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1221 const struct GNUNET_PeerIdentity *identity,
1222 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1224 struct GNUNET_TIME_Absolute now;
1225 struct GNUNET_TIME_Absolute prev_time;
1231 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1232 "Connection to core FAILED!\n");
1234 GNUNET_SCHEDULER_shutdown ();
1237 GNUNET_assert (0 == memcmp (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity)));
1238 now = GNUNET_TIME_absolute_get ();
1239 current_timestamp.abs_value = (now.abs_value / gnunet_nse_interval.rel_value) * gnunet_nse_interval.rel_value;
1240 next_timestamp.abs_value = current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1242 for (i=0;i<HISTORY_SIZE;i++)
1244 prev_time.abs_value = current_timestamp.abs_value - (HISTORY_SIZE - i - 1) * gnunet_nse_interval.rel_value;
1245 setup_flood_message (i, prev_time);
1247 estimate_index = HISTORY_SIZE - 1;
1250 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
1251 &update_flood_message, NULL);
1256 * Handle network size estimate clients.
1258 * @param cls closure
1259 * @param server the initialized server
1260 * @param c configuration to use
1263 run(void *cls, struct GNUNET_SERVER_Handle *server,
1264 const struct GNUNET_CONFIGURATION_Handle *c)
1269 static const struct GNUNET_SERVER_MessageHandler handlers[] =
1271 { &handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START, sizeof (struct GNUNET_MessageHeader) },
1272 { NULL, NULL, 0, 0 }
1274 static const struct GNUNET_CORE_MessageHandler core_handlers[] =
1276 { &handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, sizeof (struct GNUNET_NSE_FloodMessage) },
1282 GNUNET_CONFIGURATION_get_value_time (cfg,
1284 &gnunet_nse_interval)) ||
1286 GNUNET_CONFIGURATION_get_value_time (cfg,
1288 &proof_find_delay)) ||
1290 GNUNET_CONFIGURATION_get_value_number (cfg,
1292 &nse_work_required)) )
1294 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1295 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1296 GNUNET_SCHEDULER_shutdown ();
1299 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1301 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1302 _ ("Invalid work requirement for NSE service. Exiting.\n"));
1303 GNUNET_SCHEDULER_shutdown ();
1309 GNUNET_CONFIGURATION_get_value_filename (cfg,
1310 "GNUNETD", "HOSTKEY",
1313 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1314 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1315 GNUNET_SCHEDULER_shutdown ();
1318 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1319 GNUNET_free (keyfile);
1320 if (my_private_key == NULL)
1322 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1323 _("NSE service could not access hostkey. Exiting.\n"));
1324 GNUNET_SCHEDULER_shutdown ();
1327 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1328 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_identity.hashPubKey);
1330 GNUNET_CONFIGURATION_get_value_filename (cfg,
1334 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1335 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1336 if (my_private_key != NULL)
1338 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1339 my_private_key = NULL;
1341 GNUNET_SCHEDULER_shutdown ();
1344 if ( (GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1345 (sizeof (my_proof) !=
1346 GNUNET_DISK_fn_read (proof,
1348 sizeof (my_proof))) )
1350 GNUNET_free (proof);
1351 proof_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1355 peers = GNUNET_CONTAINER_multihashmap_create (128);
1356 GNUNET_SERVER_add_handlers (server, handlers);
1357 nc = GNUNET_SERVER_notification_context_create (server, 1);
1358 /* Connect to core service and register core handlers */
1359 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1360 CORE_QUEUE_SIZE, /* queue size */
1361 NULL, /* Closure passed to functions */
1362 &core_init, /* Call core_init once connected */
1363 &handle_core_connect, /* Handle connects */
1364 &handle_core_disconnect, /* Handle disconnects */
1365 NULL, /* Do we care about "status" updates? */
1366 NULL, /* Don't want notified about all incoming messages */
1367 GNUNET_NO, /* For header only inbound notification */
1368 NULL, /* Don't want notified about all outbound messages */
1369 GNUNET_NO, /* For header only outbound notification */
1370 core_handlers); /* Register these handlers */
1371 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1372 &shutdown_task, NULL);
1373 #if ENABLE_HISTOGRAM
1375 GNUNET_CONFIGURATION_get_value_filename (cfg,
1379 wh = GNUNET_BIO_write_open (proof);
1380 GNUNET_free (proof);
1383 if (coreAPI == NULL)
1385 GNUNET_SCHEDULER_shutdown ();
1388 stats = GNUNET_STATISTICS_create ("nse", cfg);
1393 * The main function for the statistics service.
1395 * @param argc number of arguments from the command line
1396 * @param argv command line arguments
1397 * @return 0 ok, 1 on error
1400 main(int argc, char * const *argv)
1402 return (GNUNET_OK == GNUNET_SERVICE_run (argc, argv,
1404 GNUNET_SERVICE_OPTION_NONE, &run,
1408 /* end of gnunet-service-nse.c */