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.
40 #include "gnunet_util_lib.h"
41 #include "gnunet_constants.h"
42 #include "gnunet_protocols.h"
43 #include "gnunet_signatures.h"
44 #include "gnunet_statistics_service.h"
45 #include "gnunet_core_service.h"
46 #include "gnunet_nse_service.h"
50 * Should messages be delayed randomly? This option should be set to
51 * GNUNET_NO only for experiments, not in production. It should also
52 * be removed once the initial experiments have been completed.
54 #define USE_RANDOM_DELAYS GNUNET_YES
57 * Should we generate a histogram with the time stamps of when we received
58 * NSE messages to disk? (for performance evaluation only, not useful in
59 * production). The associated code should also probably be removed
60 * once we're done with experiments.
62 #define ENABLE_HISTOGRAM GNUNET_NO
65 * Over how many values do we calculate the weighted average?
67 #define HISTORY_SIZE 64
70 * Message priority to use.
72 #define NSE_PRIORITY 5
75 #define log2(a) (log(a)/log(2))
79 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
81 static unsigned long long nse_work_required;
84 * Interval for sending network size estimation flood requests.
86 static struct GNUNET_TIME_Relative gnunet_nse_interval;
89 * Interval between proof find runs.
91 static struct GNUNET_TIME_Relative proof_find_delay;
95 * Handle for writing when we received messages to disk.
97 static struct GNUNET_BIO_WriteHandle *wh;
102 * Per-peer information.
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.
146 uint32_t hop_count GNUNET_PACKED;
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 GNUNET_PACKED;
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 GNUNET_PACKED;
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)
305 /* Weighted incremental algorithm for stddev according to West (1979) */
317 for (i = 0; i < estimate_count; i++)
319 j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
320 val = htonl (size_estimate_messages[j].matching_bits);
321 weight = estimate_count + 1 - i;
323 temp = weight + sumweight;
325 r = q * weight / temp;
327 sum += sumweight * q * r;
330 if (estimate_count > 0)
331 variance = (sum / sumweight) * estimate_count / (estimate_count - 1.0);
333 /* trivial version for debugging */
336 /* non-weighted trivial version */
342 for (i = 0; i < estimate_count; i++)
344 j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
345 val = htonl (size_estimate_messages[j].matching_bits);
349 if (0 != estimate_count)
351 mean = sum / estimate_count;
352 variance = (vsq - mean * sum) / (estimate_count - 1.0); // terrible for numerical stability...
356 std_dev = sqrt (variance);
358 std_dev = variance; /* must be infinity due to estimate_count == 0 */
359 current_std_dev = std_dev;
360 current_size_estimate = mean;
362 em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage));
363 em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
364 em->reserved = htonl (0);
365 em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
366 em->size_estimate = mean - 0.332747;
367 nsize = log2 (GNUNET_CONTAINER_multihashmap_size (peers) + 1);
368 if (em->size_estimate < nsize)
369 em->size_estimate = nsize;
370 em->std_deviation = std_dev;
371 GNUNET_STATISTICS_set (stats, "# nodes in the network (estimate)",
372 (uint64_t) pow (2, mean - 1.0 / 3.0), GNUNET_NO);
377 * Handler for START message from client, triggers an
378 * immediate current network estimate notification.
379 * Also, we remember the client for updates upon future
380 * estimate measurements.
383 * @param client who sent the message
384 * @param message the message received
387 handle_start_message (void *cls, struct GNUNET_SERVER_Client *client,
388 const struct GNUNET_MessageHeader *message)
390 struct GNUNET_NSE_ClientMessage em;
393 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n");
395 GNUNET_SERVER_notification_context_add (nc, client);
396 setup_estimate_message (&em);
397 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header,
399 GNUNET_SERVER_receive_done (client, GNUNET_OK);
404 * How long should we delay a message to go the given number of
407 * @param matching_bits number of matching bits to consider
410 get_matching_bits_delay (uint32_t matching_bits)
412 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */
413 // S is next_timestamp (ignored in return value)
414 // f is frequency (gnunet_nse_interval)
415 // x is matching_bits
416 // p' is current_size_estimate
417 return ((double) gnunet_nse_interval.rel_value / (double) 2.0) -
418 ((gnunet_nse_interval.rel_value / M_PI) *
419 atan (matching_bits - current_size_estimate));
424 * What delay randomization should we apply for a given number of matching bits?
426 * @param matching_bits number of matching bits
427 * @return random delay to apply
429 static struct GNUNET_TIME_Relative
430 get_delay_randomization (uint32_t matching_bits)
432 #if USE_RANDOM_DELAYS
433 struct GNUNET_TIME_Relative ret;
437 if (matching_bits == 0)
438 return GNUNET_TIME_UNIT_ZERO;
439 d = get_matching_bits_delay (matching_bits - 1);
440 i = (uint32_t) (d / (double) (hop_count_max + 1));
441 ret.rel_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, i + 1);
444 return GNUNET_TIME_UNIT_ZERO;
450 * Get the number of matching bits that the given timestamp has to the given peer ID.
452 * @param timestamp time to generate key
453 * @param id peer identity to compare with
454 * @return number of matching bits
457 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
458 const struct GNUNET_PeerIdentity *id)
460 GNUNET_HashCode timestamp_hash;
462 GNUNET_CRYPTO_hash (×tamp.abs_value, sizeof (timestamp.abs_value),
464 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash, &id->hashPubKey);
469 * Get the transmission delay that should be applied for a
472 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
473 * 0 for the current round (based on our proximity to time key)
474 * @return delay that should be applied
476 static struct GNUNET_TIME_Relative
477 get_transmit_delay (int round_offset)
479 struct GNUNET_TIME_Relative ret;
480 struct GNUNET_TIME_Absolute tgt;
482 uint32_t matching_bits;
484 switch (round_offset)
487 /* previous round is randomized between 0 and 50 ms */
488 #if USE_RANDOM_DELAYS
489 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
491 ret = GNUNET_TIME_UNIT_ZERO;
494 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
495 "Transmitting previous round behind schedule in %llu ms\n",
496 (unsigned long long) ret.rel_value);
500 /* current round is based on best-known matching_bits */
502 ntohl (size_estimate_messages[estimate_index].matching_bits);
503 dist_delay = get_matching_bits_delay (matching_bits);
504 dist_delay += get_delay_randomization (matching_bits).rel_value;
505 ret.rel_value = (uint64_t) dist_delay;
507 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
508 "For round %llu, delay for %u matching bits is %llu ms\n",
509 (unsigned long long) current_timestamp.abs_value,
510 (unsigned int) matching_bits,
511 (unsigned long long) ret.rel_value);
513 /* now consider round start time and add delay to it */
514 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
515 return GNUNET_TIME_absolute_get_remaining (tgt);
518 return GNUNET_TIME_UNIT_FOREVER_REL;
523 * Task that triggers a NSE P2P transmission.
525 * @param cls the 'struct NSEPeerEntry'
526 * @param tc scheduler context
529 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
533 * Called when core is ready to send a message we asked for
534 * out to the destination.
536 * @param cls closure (NULL)
537 * @param size number of bytes available in buf
538 * @param buf where the callee should write the message
539 * @return number of bytes written to buf
542 transmit_ready (void *cls, size_t size, void *buf)
544 struct NSEPeerEntry *peer_entry = cls;
547 peer_entry->th = NULL;
550 /* client disconnected */
553 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
554 idx = estimate_index;
555 if (peer_entry->previous_round == GNUNET_NO)
557 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
558 peer_entry->previous_round = GNUNET_YES;
559 peer_entry->transmit_task =
560 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), &transmit_task,
563 if ((ntohl (size_estimate_messages[idx].hop_count) == 0) &&
564 (GNUNET_SCHEDULER_NO_TASK != proof_task))
566 GNUNET_STATISTICS_update (stats,
567 "# flood messages not generated (no proof yet)",
571 if (ntohs (size_estimate_messages[idx].header.size) == 0)
573 GNUNET_STATISTICS_update (stats,
574 "# flood messages not generated (lack of history)",
579 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
580 "In round %llu, sending to `%s' estimate with %u bits\n",
582 GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].
583 timestamp).abs_value,
584 GNUNET_i2s (&peer_entry->id),
585 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
587 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
588 GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO);
589 GNUNET_STATISTICS_update (stats, "# flood messages transmitted", 1,
591 memcpy (buf, &size_estimate_messages[idx],
592 sizeof (struct GNUNET_NSE_FloodMessage));
593 GNUNET_STATISTICS_update (stats, "# flood messages sent", 1, GNUNET_NO);
594 return sizeof (struct GNUNET_NSE_FloodMessage);
599 * Task that triggers a NSE P2P transmission.
601 * @param cls the 'struct NSEPeerEntry'
602 * @param tc scheduler context
605 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
607 struct NSEPeerEntry *peer_entry = cls;
609 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
610 GNUNET_assert (NULL == peer_entry->th);
612 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO, NSE_PRIORITY,
613 GNUNET_TIME_UNIT_FOREVER_REL,
616 GNUNET_NSE_FloodMessage),
617 &transmit_ready, peer_entry);
622 * We've sent on our flood message or one that we received which was
623 * validated and closer than ours. Update the global list of recent
624 * messages and the average. Also re-broadcast the message to any
628 update_network_size_estimate ()
630 struct GNUNET_NSE_ClientMessage em;
632 setup_estimate_message (&em);
633 GNUNET_SERVER_notification_context_broadcast (nc, &em.header, GNUNET_YES);
638 * Setup a flood message in our history array at the given
639 * slot offset for the given timestamp.
641 * @param slot index to use
642 * @param ts timestamp to use
645 setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts)
647 struct GNUNET_NSE_FloodMessage *fm;
648 uint32_t matching_bits;
650 matching_bits = get_matching_bits (ts, &my_identity);
651 fm = &size_estimate_messages[slot];
652 fm->header.size = htons (sizeof (struct GNUNET_NSE_FloodMessage));
653 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
654 fm->hop_count = htonl (0);
655 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
657 htonl (sizeof (struct GNUNET_NSE_FloodMessage) -
658 sizeof (struct GNUNET_MessageHeader) - sizeof (uint32_t) -
659 sizeof (struct GNUNET_CRYPTO_RsaSignature));
660 fm->matching_bits = htonl (matching_bits);
661 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
662 fm->pkey = my_public_key;
663 fm->proof_of_work = my_proof;
664 if (nse_work_required > 0)
665 GNUNET_assert (GNUNET_OK ==
666 GNUNET_CRYPTO_rsa_sign (my_private_key, &fm->purpose,
669 memset (&fm->signature, 0, sizeof (fm->signature));
674 * Schedule transmission for the given peer for the current round based
675 * on what we know about the desired delay.
678 * @param key hash of peer identity
679 * @param value the 'struct NSEPeerEntry'
680 * @return GNUNET_OK (continue to iterate)
683 schedule_current_round (void *cls, const GNUNET_HashCode * key, void *value)
685 struct NSEPeerEntry *peer_entry = value;
686 struct GNUNET_TIME_Relative delay;
688 if (peer_entry->th != NULL)
690 peer_entry->previous_round = GNUNET_NO;
693 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
695 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
696 peer_entry->previous_round = GNUNET_NO;
699 get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
700 peer_entry->transmit_task =
701 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
707 * Update our flood message to be sent (and our timestamps).
710 * @param tc context for this message
713 update_flood_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
715 struct GNUNET_TIME_Relative offset;
718 flood_task = GNUNET_SCHEDULER_NO_TASK;
719 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
721 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
722 if (0 != offset.rel_value)
724 /* somehow run early, delay more */
726 GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL);
729 current_timestamp = next_timestamp;
731 GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
732 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
733 if (estimate_count < HISTORY_SIZE)
735 if (next_timestamp.abs_value ==
736 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
738 /* we received a message for this round way early, use it! */
739 size_estimate_messages[estimate_index] = next_message;
740 size_estimate_messages[estimate_index].hop_count =
741 htonl (1 + ntohl (next_message.hop_count));
744 setup_flood_message (estimate_index, current_timestamp);
745 next_message.matching_bits = htonl (0); /* reset for 'next' round */
747 for (i = 0; i < HISTORY_SIZE; i++)
749 GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max);
750 GNUNET_CONTAINER_multihashmap_iterate (peers, &schedule_current_round, NULL);
752 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
753 (next_timestamp), &update_flood_message,
759 * Count the leading zeroes in hash.
762 * @return the number of leading zero bits.
765 count_leading_zeroes (const GNUNET_HashCode * hash)
767 unsigned int hash_count;
770 while ((0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)))
777 * Check whether the given public key
778 * and integer are a valid proof of work.
780 * @param pkey the public key
781 * @param val the integer
783 * @return GNUNET_YES if valid, GNUNET_NO if not
786 check_proof_of_work (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
789 char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
791 GNUNET_HashCode result;
793 memcpy (buf, &val, sizeof (val));
794 memcpy (&buf[sizeof (val)], pkey,
795 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
796 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
797 return (count_leading_zeroes (&result) >=
798 nse_work_required) ? GNUNET_YES : GNUNET_NO;
803 * Write our current proof to disk.
811 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
813 if (sizeof (my_proof) !=
814 GNUNET_DISK_fn_write (proof, &my_proof, sizeof (my_proof),
815 GNUNET_DISK_PERM_USER_READ |
816 GNUNET_DISK_PERM_USER_WRITE))
817 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof);
824 * Find our proof of work.
826 * @param cls closure (unused)
827 * @param tc task context
830 find_proof (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
832 #define ROUND_SIZE 10
834 char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
836 GNUNET_HashCode result;
839 proof_task = GNUNET_SCHEDULER_NO_TASK;
840 memcpy (&buf[sizeof (uint64_t)], &my_public_key,
841 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
844 while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
846 memcpy (buf, &counter, sizeof (uint64_t));
847 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
848 if (nse_work_required <= count_leading_zeroes (&result))
852 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Proof of work found: %llu!\n",
853 (unsigned long long) GNUNET_ntohll (counter));
856 setup_flood_message (estimate_index, current_timestamp);
862 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
865 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Testing proofs currently at %llu\n",
866 (unsigned long long) counter);
868 /* remember progress every 100 rounds */
877 GNUNET_SCHEDULER_add_delayed (proof_find_delay, &find_proof, NULL);
882 * An incoming flood message has been received which claims
883 * to have more bits matching than any we know in this time
884 * period. Verify the signature and/or proof of work.
886 * @param incoming_flood the message to verify
888 * @return GNUNET_YES if the message is verified
889 * GNUNET_NO if the key/signature don't verify
892 verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
895 check_proof_of_work (&incoming_flood->pkey,
896 incoming_flood->proof_of_work))
898 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Proof of work invalid: %llu!\n"),
900 GNUNET_ntohll (incoming_flood->proof_of_work));
904 if ((nse_work_required > 0) &&
906 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
907 &incoming_flood->purpose,
908 &incoming_flood->signature,
909 &incoming_flood->pkey)))
919 * Update transmissions for the given peer for the current round based
920 * on updated proximity information.
922 * @param cls peer entry to exclude from updates
923 * @param key hash of peer identity
924 * @param value the 'struct NSEPeerEntry'
925 * @return GNUNET_OK (continue to iterate)
928 update_flood_times (void *cls, const GNUNET_HashCode * key, void *value)
930 struct NSEPeerEntry *exclude = cls;
931 struct NSEPeerEntry *peer_entry = value;
932 struct GNUNET_TIME_Relative delay;
934 if (peer_entry->th != NULL)
935 return GNUNET_OK; /* already active */
936 if (peer_entry == exclude)
937 return GNUNET_OK; /* trigger of the update */
938 if (peer_entry->previous_round == GNUNET_NO)
940 /* still stuck in previous round, no point to update, check that
941 * we are active here though... */
942 GNUNET_break ((peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
943 (peer_entry->th != NULL));
946 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
948 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
949 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
951 delay = get_transmit_delay (0);
952 peer_entry->transmit_task =
953 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
959 * Core handler for size estimate flooding messages.
961 * @param cls closure unused
962 * @param message message
963 * @param peer peer identity this message is from (ignored)
964 * @param atsi performance data (ignored)
965 * @param atsi_count number of records in 'atsi'
968 handle_p2p_size_estimate (void *cls, const struct GNUNET_PeerIdentity *peer,
969 const struct GNUNET_MessageHeader *message,
970 const struct GNUNET_ATS_Information *atsi,
971 unsigned int atsi_count)
973 const struct GNUNET_NSE_FloodMessage *incoming_flood;
974 struct GNUNET_TIME_Absolute ts;
975 struct NSEPeerEntry *peer_entry;
976 uint32_t matching_bits;
981 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
983 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
984 GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
985 matching_bits = ntohl (incoming_flood->matching_bits);
990 struct GNUNET_PeerIdentity os;
992 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
993 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
995 GNUNET_snprintf (origin, sizeof (origin), "%s", GNUNET_i2s (&os));
996 GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer));
997 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
998 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
1000 GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1001 origin, pred, GNUNET_i2s (&my_identity),
1002 (unsigned int) matching_bits);
1006 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1007 if (NULL == peer_entry)
1013 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1015 if (ts.abs_value == current_timestamp.abs_value)
1016 idx = estimate_index;
1017 else if (ts.abs_value ==
1018 current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1019 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1020 else if (ts.abs_value ==
1021 next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1023 if (matching_bits <= ntohl (next_message.matching_bits))
1024 return GNUNET_OK; /* ignore, simply too early/late */
1025 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1027 GNUNET_break_op (0);
1030 next_message = *incoming_flood;
1035 GNUNET_STATISTICS_update (stats,
1036 "# flood messages discarded (clock skew too large)",
1040 if (0 == (memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity))))
1042 /* send to self, update our own estimate IF this also comes from us! */
1044 memcmp (&incoming_flood->pkey, &my_public_key, sizeof (my_public_key)))
1045 update_network_size_estimate ();
1048 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1050 /* cancel transmission from us to this peer for this round */
1051 if (idx == estimate_index)
1053 if (peer_entry->previous_round == GNUNET_YES)
1055 /* cancel any activity for current round */
1056 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1058 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1059 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1061 if (peer_entry->th != NULL)
1063 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1064 peer_entry->th = NULL;
1070 /* cancel previous round only */
1071 peer_entry->previous_round = GNUNET_YES;
1074 if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1076 /* cancel transmission in the other direction, as this peer clearly has
1077 up-to-date information already */
1078 if (idx != estimate_index)
1080 /* do not transmit information for the previous round to this peer
1081 anymore (but allow current round) */
1082 peer_entry->previous_round = GNUNET_YES;
1085 /* got up-to-date information for current round, cancel transmission altogether */
1086 if (GNUNET_SCHEDULER_NO_TASK != peer_entry->transmit_task)
1088 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1089 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1091 if (peer_entry->th != NULL)
1093 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1094 peer_entry->th = NULL;
1098 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1100 if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
1101 peer_entry->previous_round = GNUNET_NO;
1102 /* push back our result now, that peer is spreading bad information... */
1103 if (NULL == peer_entry->th)
1105 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1106 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1107 peer_entry->transmit_task =
1108 GNUNET_SCHEDULER_add_now (&transmit_task, peer_entry);
1110 /* Not closer than our most recent message, no need to do work here */
1111 GNUNET_STATISTICS_update (stats,
1112 "# flood messages ignored (had closer already)",
1116 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1118 GNUNET_break_op (0);
1121 size_estimate_messages[idx] = *incoming_flood;
1122 size_estimate_messages[idx].hop_count =
1123 htonl (ntohl (incoming_flood->hop_count) + 1);
1125 GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
1126 GNUNET_STATISTICS_set (stats,
1127 "# estimated network diameter",
1128 hop_count_max, GNUNET_NO);
1130 /* have a new, better size estimate, inform clients */
1131 update_network_size_estimate ();
1134 GNUNET_CONTAINER_multihashmap_iterate (peers, &update_flood_times,
1142 * Method called whenever a peer connects.
1144 * @param cls closure
1145 * @param peer peer identity this notification is about
1146 * @param atsi performance data
1147 * @param atsi_count number of records in 'atsi'
1150 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
1151 const struct GNUNET_ATS_Information *atsi,
1152 unsigned int atsi_count)
1154 struct NSEPeerEntry *peer_entry;
1157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' connected to us\n",
1160 peer_entry = GNUNET_malloc (sizeof (struct NSEPeerEntry));
1161 peer_entry->id = *peer;
1162 GNUNET_assert (GNUNET_OK ==
1163 GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey,
1165 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1166 peer_entry->transmit_task =
1167 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), &transmit_task,
1169 GNUNET_STATISTICS_update (stats, "# peers", 1, GNUNET_NO);
1174 * Method called whenever a peer disconnects.
1176 * @param cls closure
1177 * @param peer peer identity this notification is about
1180 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1182 struct NSEPeerEntry *pos;
1185 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' disconnected from us\n",
1188 pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1194 GNUNET_assert (GNUNET_YES ==
1195 GNUNET_CONTAINER_multihashmap_remove (peers, &peer->hashPubKey,
1197 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1198 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1199 if (pos->th != NULL)
1201 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1205 GNUNET_STATISTICS_update (stats, "# peers", -1, GNUNET_NO);
1210 * Task run during shutdown.
1216 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1218 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1220 GNUNET_SCHEDULER_cancel (flood_task);
1221 flood_task = GNUNET_SCHEDULER_NO_TASK;
1223 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1225 GNUNET_SCHEDULER_cancel (proof_task);
1226 proof_task = GNUNET_SCHEDULER_NO_TASK;
1227 write_proof (); /* remember progress */
1231 GNUNET_SERVER_notification_context_destroy (nc);
1234 if (coreAPI != NULL)
1236 GNUNET_CORE_disconnect (coreAPI);
1241 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1246 GNUNET_CONTAINER_multihashmap_destroy (peers);
1249 if (my_private_key != NULL)
1251 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1252 my_private_key = NULL;
1254 #if ENABLE_HISTOGRAM
1257 GNUNET_BIO_write_close (wh);
1265 * Called on core init/fail.
1267 * @param cls service closure
1268 * @param server handle to the server for this service
1269 * @param identity the public identity of this peer
1272 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1273 const struct GNUNET_PeerIdentity *identity)
1275 struct GNUNET_TIME_Absolute now;
1276 struct GNUNET_TIME_Absolute prev_time;
1281 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection to core FAILED!\n");
1283 GNUNET_SCHEDULER_shutdown ();
1287 memcmp (&my_identity, identity,
1288 sizeof (struct GNUNET_PeerIdentity)));
1289 now = GNUNET_TIME_absolute_get ();
1290 current_timestamp.abs_value =
1291 (now.abs_value / gnunet_nse_interval.rel_value) *
1292 gnunet_nse_interval.rel_value;
1293 next_timestamp.abs_value =
1294 current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1295 estimate_index = HISTORY_SIZE - 1;
1297 if (GNUNET_YES == check_proof_of_work (&my_public_key, my_proof))
1299 prev_time.abs_value =
1300 current_timestamp.abs_value - (estimate_index -
1301 1) * gnunet_nse_interval.rel_value;
1302 setup_flood_message (estimate_index, prev_time);
1306 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1307 (next_timestamp), &update_flood_message,
1313 * Handle network size estimate clients.
1315 * @param cls closure
1316 * @param server the initialized server
1317 * @param c configuration to use
1320 run (void *cls, struct GNUNET_SERVER_Handle *server,
1321 const struct GNUNET_CONFIGURATION_Handle *c)
1326 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1327 {&handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START,
1328 sizeof (struct GNUNET_MessageHeader)},
1331 static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
1332 {&handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD,
1333 sizeof (struct GNUNET_NSE_FloodMessage)},
1339 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "INTERVAL",
1340 &gnunet_nse_interval)) ||
1342 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "WORKDELAY",
1343 &proof_find_delay)) ||
1345 GNUNET_CONFIGURATION_get_value_number (cfg, "NSE", "WORKBITS",
1346 &nse_work_required)))
1348 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1350 ("NSE service is lacking key configuration settings. Exiting.\n"));
1351 GNUNET_SCHEDULER_shutdown ();
1354 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1356 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1357 _("Invalid work requirement for NSE service. Exiting.\n"));
1358 GNUNET_SCHEDULER_shutdown ();
1364 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
1367 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1369 ("NSE service is lacking key configuration settings. Exiting.\n"));
1370 GNUNET_SCHEDULER_shutdown ();
1373 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1374 GNUNET_free (keyfile);
1375 if (my_private_key == NULL)
1377 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1378 _("NSE service could not access hostkey. Exiting.\n"));
1379 GNUNET_SCHEDULER_shutdown ();
1382 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1383 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1384 &my_identity.hashPubKey);
1386 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
1388 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1390 ("NSE service is lacking key configuration settings. Exiting.\n"));
1391 if (my_private_key != NULL)
1393 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1394 my_private_key = NULL;
1396 GNUNET_SCHEDULER_shutdown ();
1399 if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1400 (sizeof (my_proof) !=
1401 GNUNET_DISK_fn_read (proof, &my_proof, sizeof (my_proof))))
1403 GNUNET_free (proof);
1405 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1408 peers = GNUNET_CONTAINER_multihashmap_create (128);
1409 GNUNET_SERVER_add_handlers (server, handlers);
1410 nc = GNUNET_SERVER_notification_context_create (server, 1);
1411 /* Connect to core service and register core handlers */
1412 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1413 1, NULL, /* Closure passed to functions */
1414 &core_init, /* Call core_init once connected */
1415 &handle_core_connect, /* Handle connects */
1416 &handle_core_disconnect, /* Handle disconnects */
1417 NULL, /* Don't want notified about all incoming messages */
1418 GNUNET_NO, /* For header only inbound notification */
1419 NULL, /* Don't want notified about all outbound messages */
1420 GNUNET_NO, /* For header only outbound notification */
1421 core_handlers); /* Register these handlers */
1422 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1424 #if ENABLE_HISTOGRAM
1426 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "HISTOGRAM", &proof))
1428 wh = GNUNET_BIO_write_open (proof);
1429 GNUNET_free (proof);
1432 if (coreAPI == NULL)
1434 GNUNET_SCHEDULER_shutdown ();
1437 stats = GNUNET_STATISTICS_create ("nse", cfg);
1442 * The main function for the statistics service.
1444 * @param argc number of arguments from the command line
1445 * @param argv command line arguments
1446 * @return 0 ok, 1 on error
1449 main (int argc, char *const *argv)
1451 return (GNUNET_OK ==
1452 GNUNET_SERVICE_run (argc, argv, "nse", GNUNET_SERVICE_OPTION_NONE,
1453 &run, NULL)) ? 0 : 1;
1456 /* end of gnunet-service-nse.c */