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 * Size of the queue to core.
72 #define CORE_QUEUE_SIZE 2
75 * Message priority to use.
77 #define NSE_PRIORITY 5
80 #define log2(a) (log(a)/log(2))
84 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
86 static unsigned long long nse_work_required;
89 * Interval for sending network size estimation flood requests.
91 static struct GNUNET_TIME_Relative gnunet_nse_interval;
94 * Interval between proof find runs.
96 static struct GNUNET_TIME_Relative proof_find_delay;
100 * Handle for writing when we received messages to disk.
102 static struct GNUNET_BIO_WriteHandle *wh;
107 * Per-peer information.
113 * Pending message for this peer.
115 struct GNUNET_MessageHeader *pending_message;
118 * Core handle for sending messages to this peer.
120 struct GNUNET_CORE_TransmitHandle *th;
123 * What is the identity of the peer?
125 struct GNUNET_PeerIdentity id;
128 * Task scheduled to send message to this peer.
130 GNUNET_SCHEDULER_TaskIdentifier transmit_task;
133 * Did we receive or send a message about the previous round
134 * to this peer yet? GNUNET_YES if the previous round has
135 * been taken care of.
142 * Network size estimate reply; sent when "this"
143 * peer's timer has run out before receiving a
144 * valid reply from another peer.
146 struct GNUNET_NSE_FloodMessage
149 * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
151 struct GNUNET_MessageHeader header;
154 * Number of hops this message has taken so far.
156 uint32_t hop_count GNUNET_PACKED;
161 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
164 * The current timestamp value (which all
165 * peers should agree on).
167 struct GNUNET_TIME_AbsoluteNBO timestamp;
170 * Number of matching bits between the hash
171 * of timestamp and the initiator's public
174 uint32_t matching_bits GNUNET_PACKED;
177 * Public key of the originator.
179 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
182 * Proof of work, causing leading zeros when hashed with pkey.
184 uint64_t proof_of_work GNUNET_PACKED;
187 * Signature (over range specified in purpose).
189 struct GNUNET_CRYPTO_RsaSignature signature;
194 * Handle to our current configuration.
196 static const struct GNUNET_CONFIGURATION_Handle *cfg;
199 * Handle to the statistics service.
201 static struct GNUNET_STATISTICS_Handle *stats;
204 * Handle to the core service.
206 static struct GNUNET_CORE_Handle *coreAPI;
209 * Map of all connected peers.
211 static struct GNUNET_CONTAINER_MultiHashMap *peers;
214 * The current network size estimate. Number of bits matching on
217 static double current_size_estimate;
220 * The standard deviation of the last HISTORY_SIZE network
223 static double current_std_dev = NAN;
226 * Current hop counter estimate (estimate for network diameter).
228 static uint32_t hop_count_max;
231 * Message for the next round, if we got any.
233 static struct GNUNET_NSE_FloodMessage next_message;
236 * Array of recent size estimate messages.
238 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
241 * Index of most recent estimate.
243 static unsigned int estimate_index;
246 * Number of valid entries in the history.
248 static unsigned int estimate_count;
251 * Task scheduled to update our flood message for the next round.
253 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
256 * Task scheduled to compute our proof.
258 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
261 * Notification context, simplifies client broadcasts.
263 static struct GNUNET_SERVER_NotificationContext *nc;
266 * The next major time.
268 static struct GNUNET_TIME_Absolute next_timestamp;
271 * The current major time.
273 static struct GNUNET_TIME_Absolute current_timestamp;
276 * The public key of this peer.
278 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
281 * The private key of this peer.
283 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
286 * The peer identity of this peer.
288 static struct GNUNET_PeerIdentity my_identity;
291 * Proof of work for this peer.
293 static uint64_t my_proof;
297 * Initialize a message to clients with the current network
300 * @param em message to fill in
303 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
313 /* Weighted incremental algorithm for stddev according to West (1979) */
324 for (i = 0; i < estimate_count; i++)
327 htonl (size_estimate_messages
328 [(estimate_index - i +
329 HISTORY_SIZE) % HISTORY_SIZE].matching_bits);
330 weight = 1; /* was: estimate_count + 1 - i; */
332 temp = weight + sumweight;
334 r = q * weight / temp;
335 sum += sumweight * q * r;
339 variance = sum / (sumweight - 1.0);
341 /* trivial version for debugging */
344 /* non-weighted trivial version */
350 for (i = 0; i < estimate_count; i++)
354 j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
355 val = htonl (size_estimate_messages[j].matching_bits);
359 if (0 != estimate_count)
361 mean = sum / estimate_count;
362 variance = (vsq - mean * sum) / estimate_count; // terrible for numerical stability...
363 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "(%f - %f) / %u = %f\n",
364 vsq, mean * sum, estimate_count, variance);
368 GNUNET_assert (variance >= 0);
369 std_dev = sqrt (variance);
370 current_std_dev = std_dev;
371 current_size_estimate = mean;
373 em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage));
374 em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
375 em->reserved = htonl (0);
376 em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
377 em->size_estimate = mean - 0.332747;
378 nsize = log2 (GNUNET_CONTAINER_multihashmap_size (peers) + 1);
379 if (em->size_estimate < nsize)
380 em->size_estimate = nsize;
381 em->std_deviation = std_dev;
382 GNUNET_STATISTICS_set (stats, "# nodes in the network (estimate)",
383 (uint64_t) pow (2, mean - 1.0 / 3.0), GNUNET_NO);
388 * Handler for START message from client, triggers an
389 * immediate current network estimate notification.
390 * Also, we remember the client for updates upon future
391 * estimate measurements.
394 * @param client who sent the message
395 * @param message the message received
398 handle_start_message (void *cls, struct GNUNET_SERVER_Client *client,
399 const struct GNUNET_MessageHeader *message)
401 struct GNUNET_NSE_ClientMessage em;
404 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n");
406 GNUNET_SERVER_notification_context_add (nc, client);
407 setup_estimate_message (&em);
408 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header,
410 GNUNET_SERVER_receive_done (client, GNUNET_OK);
415 * How long should we delay a message to go the given number of
418 * @param matching_bits number of matching bits to consider
421 get_matching_bits_delay (uint32_t matching_bits)
423 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */
424 // S is next_timestamp (ignored in return value)
425 // f is frequency (gnunet_nse_interval)
426 // x is matching_bits
427 // p' is current_size_estimate
428 return ((double) gnunet_nse_interval.rel_value / (double) 2.0) -
429 ((gnunet_nse_interval.rel_value / M_PI) *
430 atan (matching_bits - current_size_estimate));
435 * What delay randomization should we apply for a given number of matching bits?
437 * @param matching_bits number of matching bits
438 * @return random delay to apply
440 static struct GNUNET_TIME_Relative
441 get_delay_randomization (uint32_t matching_bits)
443 #if USE_RANDOM_DELAYS
444 struct GNUNET_TIME_Relative ret;
446 if (matching_bits == 0)
447 return GNUNET_TIME_UNIT_ZERO;
449 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
450 (uint32_t) (get_matching_bits_delay
452 1) / (double) (hop_count_max +
456 return GNUNET_TIME_UNIT_ZERO;
462 * Get the number of matching bits that the given timestamp has to the given peer ID.
464 * @param timestamp time to generate key
465 * @param id peer identity to compare with
466 * @return number of matching bits
469 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
470 const struct GNUNET_PeerIdentity *id)
472 GNUNET_HashCode timestamp_hash;
474 GNUNET_CRYPTO_hash (×tamp.abs_value, sizeof (timestamp.abs_value),
476 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash, &id->hashPubKey);
481 * Get the transmission delay that should be applied for a
484 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
485 * 0 for the current round (based on our proximity to time key)
486 * @return delay that should be applied
488 static struct GNUNET_TIME_Relative
489 get_transmit_delay (int round_offset)
491 struct GNUNET_TIME_Relative ret;
492 struct GNUNET_TIME_Absolute tgt;
494 uint32_t matching_bits;
496 switch (round_offset)
499 /* previous round is randomized between 0 and 50 ms */
500 #if USE_RANDOM_DELAYS
501 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
503 ret = GNUNET_TIME_UNIT_ZERO;
506 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
507 "Transmitting previous round behind schedule in %llu ms\n",
508 (unsigned long long) ret.rel_value);
512 /* current round is based on best-known matching_bits */
514 ntohl (size_estimate_messages[estimate_index].matching_bits);
515 dist_delay = get_matching_bits_delay (matching_bits);
516 dist_delay += get_delay_randomization (matching_bits).rel_value;
517 ret.rel_value = (uint64_t) dist_delay;
519 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
520 "For round %llu, delay for %u matching bits is %llu ms\n",
521 (unsigned long long) current_timestamp.abs_value,
522 (unsigned int) matching_bits,
523 (unsigned long long) ret.rel_value);
525 /* now consider round start time and add delay to it */
526 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
527 return GNUNET_TIME_absolute_get_remaining (tgt);
530 return GNUNET_TIME_UNIT_FOREVER_REL;
535 * Task that triggers a NSE P2P transmission.
537 * @param cls the 'struct NSEPeerEntry'
538 * @param tc scheduler context
541 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
545 * Called when core is ready to send a message we asked for
546 * out to the destination.
548 * @param cls closure (NULL)
549 * @param size number of bytes available in buf
550 * @param buf where the callee should write the message
551 * @return number of bytes written to buf
554 transmit_ready (void *cls, size_t size, void *buf)
556 struct NSEPeerEntry *peer_entry = cls;
559 peer_entry->th = NULL;
562 /* client disconnected */
565 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
566 idx = estimate_index;
567 if (peer_entry->previous_round == GNUNET_NO)
569 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
570 peer_entry->previous_round = GNUNET_YES;
571 peer_entry->transmit_task =
572 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), &transmit_task,
575 if ((ntohl (size_estimate_messages[idx].hop_count) == 0) &&
576 (GNUNET_SCHEDULER_NO_TASK != proof_task))
578 GNUNET_STATISTICS_update (stats,
579 "# flood messages not generated (no proof yet)",
584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
585 "In round %llu, sending to `%s' estimate with %u bits\n",
587 GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].
588 timestamp).abs_value,
589 GNUNET_i2s (&peer_entry->id),
590 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
592 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
593 GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO);
594 GNUNET_STATISTICS_update (stats, "# flood messages transmitted", 1,
596 memcpy (buf, &size_estimate_messages[idx],
597 sizeof (struct GNUNET_NSE_FloodMessage));
598 GNUNET_STATISTICS_update (stats, "# flood messages sent", 1, GNUNET_NO);
599 return sizeof (struct GNUNET_NSE_FloodMessage);
604 * Task that triggers a NSE P2P transmission.
606 * @param cls the 'struct NSEPeerEntry'
607 * @param tc scheduler context
610 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
612 struct NSEPeerEntry *peer_entry = cls;
614 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
615 GNUNET_assert (NULL == peer_entry->th);
617 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO, NSE_PRIORITY,
618 GNUNET_TIME_UNIT_FOREVER_REL,
621 GNUNET_NSE_FloodMessage),
622 &transmit_ready, peer_entry);
627 * We've sent on our flood message or one that we received which was
628 * validated and closer than ours. Update the global list of recent
629 * messages and the average. Also re-broadcast the message to any
633 update_network_size_estimate ()
635 struct GNUNET_NSE_ClientMessage em;
637 setup_estimate_message (&em);
638 GNUNET_SERVER_notification_context_broadcast (nc, &em.header, GNUNET_YES);
643 * Setup a flood message in our history array at the given
644 * slot offset for the given timestamp.
646 * @param slot index to use
647 * @param ts timestamp to use
650 setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts)
652 struct GNUNET_NSE_FloodMessage *fm;
653 uint32_t matching_bits;
655 matching_bits = get_matching_bits (ts, &my_identity);
656 fm = &size_estimate_messages[slot];
657 fm->header.size = htons (sizeof (struct GNUNET_NSE_FloodMessage));
658 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
659 fm->hop_count = htonl (0);
660 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
662 htonl (sizeof (struct GNUNET_NSE_FloodMessage) -
663 sizeof (struct GNUNET_MessageHeader) - sizeof (uint32_t) -
664 sizeof (struct GNUNET_CRYPTO_RsaSignature));
665 fm->matching_bits = htonl (matching_bits);
666 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
667 fm->pkey = my_public_key;
668 fm->proof_of_work = my_proof;
669 GNUNET_assert (GNUNET_OK ==
670 GNUNET_CRYPTO_rsa_sign (my_private_key, &fm->purpose,
676 * Schedule transmission for the given peer for the current round based
677 * on what we know about the desired delay.
680 * @param key hash of peer identity
681 * @param value the 'struct NSEPeerEntry'
682 * @return GNUNET_OK (continue to iterate)
685 schedule_current_round (void *cls, const GNUNET_HashCode * key, void *value)
687 struct NSEPeerEntry *peer_entry = value;
688 struct GNUNET_TIME_Relative delay;
690 if (peer_entry->th != NULL)
692 peer_entry->previous_round = GNUNET_NO;
695 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
697 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
698 peer_entry->previous_round = GNUNET_NO;
701 get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
702 peer_entry->transmit_task =
703 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
709 * Update our flood message to be sent (and our timestamps).
712 * @param tc context for this message
715 update_flood_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
717 struct GNUNET_TIME_Relative offset;
720 flood_task = GNUNET_SCHEDULER_NO_TASK;
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));
855 for (i = 0; i < HISTORY_SIZE; i++)
856 if (ntohl (size_estimate_messages[i].hop_count) == 0)
858 size_estimate_messages[i].proof_of_work = my_proof;
859 GNUNET_assert (GNUNET_OK ==
860 GNUNET_CRYPTO_rsa_sign (my_private_key,
861 &size_estimate_messages
863 &size_estimate_messages
872 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
875 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Testing proofs currently at %llu\n",
876 (unsigned long long) counter);
878 /* remember progress every 100 rounds */
887 GNUNET_SCHEDULER_add_delayed (proof_find_delay, &find_proof, NULL);
892 * An incoming flood message has been received which claims
893 * to have more bits matching than any we know in this time
894 * period. Verify the signature and/or proof of work.
896 * @param incoming_flood the message to verify
898 * @return GNUNET_YES if the message is verified
899 * GNUNET_NO if the key/signature don't verify
902 verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
905 check_proof_of_work (&incoming_flood->pkey,
906 incoming_flood->proof_of_work))
908 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Proof of work invalid: %llu!\n"),
910 GNUNET_ntohll (incoming_flood->proof_of_work));
915 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
916 &incoming_flood->purpose,
917 &incoming_flood->signature,
918 &incoming_flood->pkey))
928 * Update transmissions for the given peer for the current round based
929 * on updated proximity information.
931 * @param cls peer entry to exclude from updates
932 * @param key hash of peer identity
933 * @param value the 'struct NSEPeerEntry'
934 * @return GNUNET_OK (continue to iterate)
937 update_flood_times (void *cls, const GNUNET_HashCode * key, void *value)
939 struct NSEPeerEntry *exclude = cls;
940 struct NSEPeerEntry *peer_entry = value;
941 struct GNUNET_TIME_Relative delay;
943 if (peer_entry->th != NULL)
944 return GNUNET_OK; /* already active */
945 if (peer_entry == exclude)
946 return GNUNET_OK; /* trigger of the update */
947 if (peer_entry->previous_round == GNUNET_NO)
949 /* still stuck in previous round, no point to update, check that
950 * we are active here though... */
951 GNUNET_break ((peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
952 (peer_entry->th != NULL));
955 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
957 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
958 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
960 delay = get_transmit_delay (0);
961 peer_entry->transmit_task =
962 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
968 * Core handler for size estimate flooding messages.
970 * @param cls closure unused
971 * @param message message
972 * @param peer peer identity this message is from (ignored)
973 * @param atsi performance data (ignored)
974 * @param atsi_count number of records in 'atsi'
977 handle_p2p_size_estimate (void *cls, const struct GNUNET_PeerIdentity *peer,
978 const struct GNUNET_MessageHeader *message,
979 const struct GNUNET_ATS_Information *atsi,
980 unsigned int atsi_count)
982 const struct GNUNET_NSE_FloodMessage *incoming_flood;
983 struct GNUNET_TIME_Absolute ts;
984 struct NSEPeerEntry *peer_entry;
985 uint32_t matching_bits;
990 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
992 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
993 GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
994 matching_bits = ntohl (incoming_flood->matching_bits);
999 struct GNUNET_PeerIdentity os;
1001 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
1002 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1004 GNUNET_snprintf (origin, sizeof (origin), "%s", GNUNET_i2s (&os));
1005 GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer));
1006 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1007 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
1008 (unsigned long long)
1009 GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1010 origin, pred, GNUNET_i2s (&my_identity),
1011 (unsigned int) matching_bits);
1015 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1016 if (NULL == peer_entry)
1022 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1024 if (ts.abs_value == current_timestamp.abs_value)
1025 idx = estimate_index;
1026 else if (ts.abs_value ==
1027 current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1028 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1029 else if (ts.abs_value ==
1030 next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1032 if (matching_bits <= ntohl (next_message.matching_bits))
1033 return GNUNET_OK; /* ignore, simply too early/late */
1034 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1036 GNUNET_break_op (0);
1039 next_message = *incoming_flood;
1044 GNUNET_STATISTICS_update (stats,
1045 "# flood messages discarded (clock skew too large)",
1049 if (0 == (memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity))))
1051 /* send to self, update our own estimate IF this also comes from us! */
1053 memcmp (&incoming_flood->pkey, &my_public_key, sizeof (my_public_key)))
1054 update_network_size_estimate ();
1057 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1059 /* cancel transmission from us to this peer for this round */
1060 if (idx == estimate_index)
1062 if (peer_entry->previous_round == GNUNET_YES)
1064 /* cancel any activity for current round */
1065 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1067 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1068 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1070 if (peer_entry->th != NULL)
1072 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1073 peer_entry->th = NULL;
1079 /* cancel previous round only */
1080 peer_entry->previous_round = GNUNET_YES;
1083 if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1085 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1087 if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
1088 peer_entry->previous_round = GNUNET_NO;
1089 /* push back our result now, that peer is spreading bad information... */
1090 if (NULL == peer_entry->th)
1092 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1093 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1094 peer_entry->transmit_task =
1095 GNUNET_SCHEDULER_add_now (&transmit_task, peer_entry);
1097 /* Not closer than our most recent message, no need to do work here */
1098 GNUNET_STATISTICS_update (stats,
1099 "# flood messages ignored (had closer already)",
1103 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1105 GNUNET_break_op (0);
1108 size_estimate_messages[idx] = *incoming_flood;
1109 size_estimate_messages[idx].hop_count =
1110 htonl (ntohl (incoming_flood->hop_count) + 1);
1112 GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
1114 /* have a new, better size estimate, inform clients */
1115 update_network_size_estimate ();
1118 GNUNET_CONTAINER_multihashmap_iterate (peers, &update_flood_times,
1126 * Method called whenever a peer connects.
1128 * @param cls closure
1129 * @param peer peer identity this notification is about
1130 * @param atsi performance data
1131 * @param atsi_count number of records in 'atsi'
1134 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
1135 const struct GNUNET_ATS_Information *atsi,
1136 unsigned int atsi_count)
1138 struct NSEPeerEntry *peer_entry;
1141 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' connected to us\n",
1144 peer_entry = GNUNET_malloc (sizeof (struct NSEPeerEntry));
1145 peer_entry->id = *peer;
1146 GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_entry,
1147 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1148 peer_entry->transmit_task =
1149 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), &transmit_task,
1155 * Method called whenever a peer disconnects.
1157 * @param cls closure
1158 * @param peer peer identity this notification is about
1161 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1163 struct NSEPeerEntry *pos;
1166 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' disconnected from us\n",
1169 pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1175 GNUNET_assert (GNUNET_YES ==
1176 GNUNET_CONTAINER_multihashmap_remove (peers, &peer->hashPubKey,
1178 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1179 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1180 if (pos->th != NULL)
1182 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1190 * Task run during shutdown.
1196 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1198 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1200 GNUNET_SCHEDULER_cancel (flood_task);
1201 flood_task = GNUNET_SCHEDULER_NO_TASK;
1203 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1205 GNUNET_SCHEDULER_cancel (proof_task);
1206 proof_task = GNUNET_SCHEDULER_NO_TASK;
1207 write_proof (); /* remember progress */
1211 GNUNET_SERVER_notification_context_destroy (nc);
1214 if (coreAPI != NULL)
1216 GNUNET_CORE_disconnect (coreAPI);
1221 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1226 GNUNET_CONTAINER_multihashmap_destroy (peers);
1229 if (my_private_key != NULL)
1231 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1232 my_private_key = NULL;
1234 #if ENABLE_HISTOGRAM
1237 GNUNET_BIO_write_close (wh);
1245 * Called on core init/fail.
1247 * @param cls service closure
1248 * @param server handle to the server for this service
1249 * @param identity the public identity of this peer
1252 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1253 const struct GNUNET_PeerIdentity *identity)
1255 struct GNUNET_TIME_Absolute now;
1256 struct GNUNET_TIME_Absolute prev_time;
1262 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection to core FAILED!\n");
1264 GNUNET_SCHEDULER_shutdown ();
1268 memcmp (&my_identity, identity,
1269 sizeof (struct GNUNET_PeerIdentity)));
1270 now = GNUNET_TIME_absolute_get ();
1271 current_timestamp.abs_value =
1272 (now.abs_value / gnunet_nse_interval.rel_value) *
1273 gnunet_nse_interval.rel_value;
1274 next_timestamp.abs_value =
1275 current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1277 for (i = 0; i < HISTORY_SIZE; i++)
1279 prev_time.abs_value =
1280 current_timestamp.abs_value - (HISTORY_SIZE - i -
1281 1) * gnunet_nse_interval.rel_value;
1282 setup_flood_message (i, prev_time);
1284 estimate_index = HISTORY_SIZE - 1;
1287 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1288 (next_timestamp), &update_flood_message,
1294 * Handle network size estimate clients.
1296 * @param cls closure
1297 * @param server the initialized server
1298 * @param c configuration to use
1301 run (void *cls, struct GNUNET_SERVER_Handle *server,
1302 const struct GNUNET_CONFIGURATION_Handle *c)
1307 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1308 {&handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START,
1309 sizeof (struct GNUNET_MessageHeader)},
1312 static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
1313 {&handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD,
1314 sizeof (struct GNUNET_NSE_FloodMessage)},
1320 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "INTERVAL",
1321 &gnunet_nse_interval)) ||
1323 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "WORKDELAY",
1324 &proof_find_delay)) ||
1326 GNUNET_CONFIGURATION_get_value_number (cfg, "NSE", "WORKBITS",
1327 &nse_work_required)))
1329 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1331 ("NSE service is lacking key configuration settings. Exiting.\n"));
1332 GNUNET_SCHEDULER_shutdown ();
1335 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1337 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1338 _("Invalid work requirement for NSE service. Exiting.\n"));
1339 GNUNET_SCHEDULER_shutdown ();
1345 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
1348 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1350 ("NSE service is lacking key configuration settings. Exiting.\n"));
1351 GNUNET_SCHEDULER_shutdown ();
1354 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1355 GNUNET_free (keyfile);
1356 if (my_private_key == NULL)
1358 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1359 _("NSE service could not access hostkey. Exiting.\n"));
1360 GNUNET_SCHEDULER_shutdown ();
1363 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1364 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1365 &my_identity.hashPubKey);
1367 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
1369 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1371 ("NSE service is lacking key configuration settings. Exiting.\n"));
1372 if (my_private_key != NULL)
1374 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1375 my_private_key = NULL;
1377 GNUNET_SCHEDULER_shutdown ();
1380 if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1381 (sizeof (my_proof) !=
1382 GNUNET_DISK_fn_read (proof, &my_proof, sizeof (my_proof))))
1384 GNUNET_free (proof);
1386 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1389 peers = GNUNET_CONTAINER_multihashmap_create (128);
1390 GNUNET_SERVER_add_handlers (server, handlers);
1391 nc = GNUNET_SERVER_notification_context_create (server, 1);
1392 /* Connect to core service and register core handlers */
1393 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1394 CORE_QUEUE_SIZE, /* queue size */
1395 NULL, /* Closure passed to functions */
1396 &core_init, /* Call core_init once connected */
1397 &handle_core_connect, /* Handle connects */
1398 &handle_core_disconnect, /* Handle disconnects */
1399 NULL, /* Don't want notified about all incoming messages */
1400 GNUNET_NO, /* For header only inbound notification */
1401 NULL, /* Don't want notified about all outbound messages */
1402 GNUNET_NO, /* For header only outbound notification */
1403 core_handlers); /* Register these handlers */
1404 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1406 #if ENABLE_HISTOGRAM
1408 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "HISTOGRAM", &proof))
1410 wh = GNUNET_BIO_write_open (proof);
1411 GNUNET_free (proof);
1414 if (coreAPI == NULL)
1416 GNUNET_SCHEDULER_shutdown ();
1419 stats = GNUNET_STATISTICS_create ("nse", cfg);
1424 * The main function for the statistics service.
1426 * @param argc number of arguments from the command line
1427 * @param argv command line arguments
1428 * @return 0 ok, 1 on error
1431 main (int argc, char *const *argv)
1433 return (GNUNET_OK ==
1434 GNUNET_SERVICE_run (argc, argv, "nse", GNUNET_SERVICE_OPTION_NONE,
1435 &run, NULL)) ? 0 : 1;
1438 /* end of gnunet-service-nse.c */