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 * Pending message for this peer.
110 struct GNUNET_MessageHeader *pending_message;
113 * Core handle for sending messages to this peer.
115 struct GNUNET_CORE_TransmitHandle *th;
118 * What is the identity of the peer?
120 struct GNUNET_PeerIdentity id;
123 * Task scheduled to send message to this peer.
125 GNUNET_SCHEDULER_TaskIdentifier transmit_task;
128 * Did we receive or send a message about the previous round
129 * to this peer yet? GNUNET_YES if the previous round has
130 * been taken care of.
137 * Network size estimate reply; sent when "this"
138 * peer's timer has run out before receiving a
139 * valid reply from another peer.
141 struct GNUNET_NSE_FloodMessage
144 * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
146 struct GNUNET_MessageHeader header;
149 * Number of hops this message has taken so far.
151 uint32_t hop_count GNUNET_PACKED;
156 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
159 * The current timestamp value (which all
160 * peers should agree on).
162 struct GNUNET_TIME_AbsoluteNBO timestamp;
165 * Number of matching bits between the hash
166 * of timestamp and the initiator's public
169 uint32_t matching_bits GNUNET_PACKED;
172 * Public key of the originator.
174 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
177 * Proof of work, causing leading zeros when hashed with pkey.
179 uint64_t proof_of_work GNUNET_PACKED;
182 * Signature (over range specified in purpose).
184 struct GNUNET_CRYPTO_RsaSignature signature;
189 * Handle to our current configuration.
191 static const struct GNUNET_CONFIGURATION_Handle *cfg;
194 * Handle to the statistics service.
196 static struct GNUNET_STATISTICS_Handle *stats;
199 * Handle to the core service.
201 static struct GNUNET_CORE_Handle *coreAPI;
204 * Map of all connected peers.
206 static struct GNUNET_CONTAINER_MultiHashMap *peers;
209 * The current network size estimate. Number of bits matching on
212 static double current_size_estimate;
215 * The standard deviation of the last HISTORY_SIZE network
218 static double current_std_dev = NAN;
221 * Current hop counter estimate (estimate for network diameter).
223 static uint32_t hop_count_max;
226 * Message for the next round, if we got any.
228 static struct GNUNET_NSE_FloodMessage next_message;
231 * Array of recent size estimate messages.
233 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
236 * Index of most recent estimate.
238 static unsigned int estimate_index;
241 * Number of valid entries in the history.
243 static unsigned int estimate_count;
246 * Task scheduled to update our flood message for the next round.
248 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
251 * Task scheduled to compute our proof.
253 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
256 * Notification context, simplifies client broadcasts.
258 static struct GNUNET_SERVER_NotificationContext *nc;
261 * The next major time.
263 static struct GNUNET_TIME_Absolute next_timestamp;
266 * The current major time.
268 static struct GNUNET_TIME_Absolute current_timestamp;
271 * The public key of this peer.
273 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
276 * The private key of this peer.
278 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
281 * The peer identity of this peer.
283 static struct GNUNET_PeerIdentity my_identity;
286 * Proof of work for this peer.
288 static uint64_t my_proof;
292 * Initialize a message to clients with the current network
295 * @param em message to fill in
298 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
309 /* Weighted incremental algorithm for stddev according to West (1979) */
320 for (i = 0; i < estimate_count; i++)
322 j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
323 val = htonl (size_estimate_messages[j].matching_bits);
324 weight = 1.0; /* was: estimate_count + 1 - i; */
326 temp = weight + sumweight;
328 r = q * weight / temp;
330 sum += sumweight * q * r;
333 if (estimate_count > 0)
334 variance = (sum / sumweight) * estimate_count / (estimate_count - 1.0);
336 /* trivial version for debugging */
339 /* non-weighted trivial version */
345 for (i = 0; i < estimate_count; i++)
347 j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
348 val = htonl (size_estimate_messages[j].matching_bits);
352 if (0 != estimate_count)
354 mean = sum / estimate_count;
355 variance = (vsq - mean * sum) / (estimate_count - 1.0); // terrible for numerical stability...
356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
357 "(%f - %f) / %u = %f\n",
358 vsq, mean * sum, estimate_count - 1, variance);
362 GNUNET_assert (variance >= 0);
363 std_dev = sqrt (variance);
364 current_std_dev = std_dev;
365 current_size_estimate = mean;
367 em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage));
368 em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
369 em->reserved = htonl (0);
370 em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
371 em->size_estimate = mean - 0.332747;
372 nsize = log2 (GNUNET_CONTAINER_multihashmap_size (peers) + 1);
373 if (em->size_estimate < nsize)
374 em->size_estimate = nsize;
375 em->std_deviation = std_dev;
376 GNUNET_STATISTICS_set (stats, "# nodes in the network (estimate)",
377 (uint64_t) pow (2, mean - 1.0 / 3.0), GNUNET_NO);
382 * Handler for START message from client, triggers an
383 * immediate current network estimate notification.
384 * Also, we remember the client for updates upon future
385 * estimate measurements.
388 * @param client who sent the message
389 * @param message the message received
392 handle_start_message (void *cls, struct GNUNET_SERVER_Client *client,
393 const struct GNUNET_MessageHeader *message)
395 struct GNUNET_NSE_ClientMessage em;
398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n");
400 GNUNET_SERVER_notification_context_add (nc, client);
401 setup_estimate_message (&em);
402 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header,
404 GNUNET_SERVER_receive_done (client, GNUNET_OK);
409 * How long should we delay a message to go the given number of
412 * @param matching_bits number of matching bits to consider
415 get_matching_bits_delay (uint32_t matching_bits)
417 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */
418 // S is next_timestamp (ignored in return value)
419 // f is frequency (gnunet_nse_interval)
420 // x is matching_bits
421 // p' is current_size_estimate
422 return ((double) gnunet_nse_interval.rel_value / (double) 2.0) -
423 ((gnunet_nse_interval.rel_value / M_PI) *
424 atan (matching_bits - current_size_estimate));
429 * What delay randomization should we apply for a given number of matching bits?
431 * @param matching_bits number of matching bits
432 * @return random delay to apply
434 static struct GNUNET_TIME_Relative
435 get_delay_randomization (uint32_t matching_bits)
437 #if USE_RANDOM_DELAYS
438 struct GNUNET_TIME_Relative ret;
440 if (matching_bits == 0)
441 return GNUNET_TIME_UNIT_ZERO;
443 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
444 (uint32_t) (get_matching_bits_delay
446 1) / (double) (hop_count_max +
450 return GNUNET_TIME_UNIT_ZERO;
456 * Get the number of matching bits that the given timestamp has to the given peer ID.
458 * @param timestamp time to generate key
459 * @param id peer identity to compare with
460 * @return number of matching bits
463 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
464 const struct GNUNET_PeerIdentity *id)
466 GNUNET_HashCode timestamp_hash;
468 GNUNET_CRYPTO_hash (×tamp.abs_value, sizeof (timestamp.abs_value),
470 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash, &id->hashPubKey);
475 * Get the transmission delay that should be applied for a
478 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
479 * 0 for the current round (based on our proximity to time key)
480 * @return delay that should be applied
482 static struct GNUNET_TIME_Relative
483 get_transmit_delay (int round_offset)
485 struct GNUNET_TIME_Relative ret;
486 struct GNUNET_TIME_Absolute tgt;
488 uint32_t matching_bits;
490 switch (round_offset)
493 /* previous round is randomized between 0 and 50 ms */
494 #if USE_RANDOM_DELAYS
495 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
497 ret = GNUNET_TIME_UNIT_ZERO;
500 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
501 "Transmitting previous round behind schedule in %llu ms\n",
502 (unsigned long long) ret.rel_value);
506 /* current round is based on best-known matching_bits */
508 ntohl (size_estimate_messages[estimate_index].matching_bits);
509 dist_delay = get_matching_bits_delay (matching_bits);
510 dist_delay += get_delay_randomization (matching_bits).rel_value;
511 ret.rel_value = (uint64_t) dist_delay;
513 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
514 "For round %llu, delay for %u matching bits is %llu ms\n",
515 (unsigned long long) current_timestamp.abs_value,
516 (unsigned int) matching_bits,
517 (unsigned long long) ret.rel_value);
519 /* now consider round start time and add delay to it */
520 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
521 return GNUNET_TIME_absolute_get_remaining (tgt);
524 return GNUNET_TIME_UNIT_FOREVER_REL;
529 * Task that triggers a NSE P2P transmission.
531 * @param cls the 'struct NSEPeerEntry'
532 * @param tc scheduler context
535 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
539 * Called when core is ready to send a message we asked for
540 * out to the destination.
542 * @param cls closure (NULL)
543 * @param size number of bytes available in buf
544 * @param buf where the callee should write the message
545 * @return number of bytes written to buf
548 transmit_ready (void *cls, size_t size, void *buf)
550 struct NSEPeerEntry *peer_entry = cls;
553 peer_entry->th = NULL;
556 /* client disconnected */
559 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
560 idx = estimate_index;
561 if (peer_entry->previous_round == GNUNET_NO)
563 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
564 peer_entry->previous_round = GNUNET_YES;
565 peer_entry->transmit_task =
566 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), &transmit_task,
569 if ((ntohl (size_estimate_messages[idx].hop_count) == 0) &&
570 (GNUNET_SCHEDULER_NO_TASK != proof_task))
572 GNUNET_STATISTICS_update (stats,
573 "# flood messages not generated (no proof yet)",
578 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
579 "In round %llu, sending to `%s' estimate with %u bits\n",
581 GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].
582 timestamp).abs_value,
583 GNUNET_i2s (&peer_entry->id),
584 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
586 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
587 GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO);
588 GNUNET_STATISTICS_update (stats, "# flood messages transmitted", 1,
590 memcpy (buf, &size_estimate_messages[idx],
591 sizeof (struct GNUNET_NSE_FloodMessage));
592 GNUNET_STATISTICS_update (stats, "# flood messages sent", 1, GNUNET_NO);
593 return sizeof (struct GNUNET_NSE_FloodMessage);
598 * Task that triggers a NSE P2P transmission.
600 * @param cls the 'struct NSEPeerEntry'
601 * @param tc scheduler context
604 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
606 struct NSEPeerEntry *peer_entry = cls;
608 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
609 GNUNET_assert (NULL == peer_entry->th);
611 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO, NSE_PRIORITY,
612 GNUNET_TIME_UNIT_FOREVER_REL,
615 GNUNET_NSE_FloodMessage),
616 &transmit_ready, peer_entry);
621 * We've sent on our flood message or one that we received which was
622 * validated and closer than ours. Update the global list of recent
623 * messages and the average. Also re-broadcast the message to any
627 update_network_size_estimate ()
629 struct GNUNET_NSE_ClientMessage em;
631 setup_estimate_message (&em);
632 GNUNET_SERVER_notification_context_broadcast (nc, &em.header, GNUNET_YES);
637 * Setup a flood message in our history array at the given
638 * slot offset for the given timestamp.
640 * @param slot index to use
641 * @param ts timestamp to use
644 setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts)
646 struct GNUNET_NSE_FloodMessage *fm;
647 uint32_t matching_bits;
649 matching_bits = get_matching_bits (ts, &my_identity);
650 fm = &size_estimate_messages[slot];
651 fm->header.size = htons (sizeof (struct GNUNET_NSE_FloodMessage));
652 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
653 fm->hop_count = htonl (0);
654 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
656 htonl (sizeof (struct GNUNET_NSE_FloodMessage) -
657 sizeof (struct GNUNET_MessageHeader) - sizeof (uint32_t) -
658 sizeof (struct GNUNET_CRYPTO_RsaSignature));
659 fm->matching_bits = htonl (matching_bits);
660 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
661 fm->pkey = my_public_key;
662 fm->proof_of_work = my_proof;
663 GNUNET_assert (GNUNET_OK ==
664 GNUNET_CRYPTO_rsa_sign (my_private_key, &fm->purpose,
670 * Schedule transmission for the given peer for the current round based
671 * on what we know about the desired delay.
674 * @param key hash of peer identity
675 * @param value the 'struct NSEPeerEntry'
676 * @return GNUNET_OK (continue to iterate)
679 schedule_current_round (void *cls, const GNUNET_HashCode * key, void *value)
681 struct NSEPeerEntry *peer_entry = value;
682 struct GNUNET_TIME_Relative delay;
684 if (peer_entry->th != NULL)
686 peer_entry->previous_round = GNUNET_NO;
689 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
691 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
692 peer_entry->previous_round = GNUNET_NO;
695 get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
696 peer_entry->transmit_task =
697 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
703 * Update our flood message to be sent (and our timestamps).
706 * @param tc context for this message
709 update_flood_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
711 struct GNUNET_TIME_Relative offset;
714 flood_task = GNUNET_SCHEDULER_NO_TASK;
715 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
716 if (0 != offset.rel_value)
718 /* somehow run early, delay more */
720 GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL);
723 current_timestamp = next_timestamp;
725 GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
726 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
727 if (estimate_count < HISTORY_SIZE)
729 if (next_timestamp.abs_value ==
730 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
732 /* we received a message for this round way early, use it! */
733 size_estimate_messages[estimate_index] = next_message;
734 size_estimate_messages[estimate_index].hop_count =
735 htonl (1 + ntohl (next_message.hop_count));
738 setup_flood_message (estimate_index, current_timestamp);
739 next_message.matching_bits = htonl (0); /* reset for 'next' round */
741 for (i = 0; i < HISTORY_SIZE; i++)
743 GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max);
744 GNUNET_CONTAINER_multihashmap_iterate (peers, &schedule_current_round, NULL);
746 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
747 (next_timestamp), &update_flood_message,
753 * Count the leading zeroes in hash.
756 * @return the number of leading zero bits.
759 count_leading_zeroes (const GNUNET_HashCode * hash)
761 unsigned int hash_count;
764 while ((0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)))
771 * Check whether the given public key
772 * and integer are a valid proof of work.
774 * @param pkey the public key
775 * @param val the integer
777 * @return GNUNET_YES if valid, GNUNET_NO if not
780 check_proof_of_work (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
783 char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
785 GNUNET_HashCode result;
787 memcpy (buf, &val, sizeof (val));
788 memcpy (&buf[sizeof (val)], pkey,
789 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
790 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
791 return (count_leading_zeroes (&result) >=
792 nse_work_required) ? GNUNET_YES : GNUNET_NO;
797 * Write our current proof to disk.
805 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
807 if (sizeof (my_proof) !=
808 GNUNET_DISK_fn_write (proof, &my_proof, sizeof (my_proof),
809 GNUNET_DISK_PERM_USER_READ |
810 GNUNET_DISK_PERM_USER_WRITE))
811 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof);
818 * Find our proof of work.
820 * @param cls closure (unused)
821 * @param tc task context
824 find_proof (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
826 #define ROUND_SIZE 10
828 char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
830 GNUNET_HashCode result;
833 proof_task = GNUNET_SCHEDULER_NO_TASK;
834 memcpy (&buf[sizeof (uint64_t)], &my_public_key,
835 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
838 while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
840 memcpy (buf, &counter, sizeof (uint64_t));
841 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
842 if (nse_work_required <= count_leading_zeroes (&result))
846 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Proof of work found: %llu!\n",
847 (unsigned long long) GNUNET_ntohll (counter));
849 for (i = 0; i < HISTORY_SIZE; i++)
850 if (ntohl (size_estimate_messages[i].hop_count) == 0)
852 size_estimate_messages[i].proof_of_work = my_proof;
853 GNUNET_assert (GNUNET_OK ==
854 GNUNET_CRYPTO_rsa_sign (my_private_key,
855 &size_estimate_messages
857 &size_estimate_messages
866 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
869 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Testing proofs currently at %llu\n",
870 (unsigned long long) counter);
872 /* remember progress every 100 rounds */
881 GNUNET_SCHEDULER_add_delayed (proof_find_delay, &find_proof, NULL);
886 * An incoming flood message has been received which claims
887 * to have more bits matching than any we know in this time
888 * period. Verify the signature and/or proof of work.
890 * @param incoming_flood the message to verify
892 * @return GNUNET_YES if the message is verified
893 * GNUNET_NO if the key/signature don't verify
896 verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
899 check_proof_of_work (&incoming_flood->pkey,
900 incoming_flood->proof_of_work))
902 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Proof of work invalid: %llu!\n"),
904 GNUNET_ntohll (incoming_flood->proof_of_work));
909 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
910 &incoming_flood->purpose,
911 &incoming_flood->signature,
912 &incoming_flood->pkey))
922 * Update transmissions for the given peer for the current round based
923 * on updated proximity information.
925 * @param cls peer entry to exclude from updates
926 * @param key hash of peer identity
927 * @param value the 'struct NSEPeerEntry'
928 * @return GNUNET_OK (continue to iterate)
931 update_flood_times (void *cls, const GNUNET_HashCode * key, void *value)
933 struct NSEPeerEntry *exclude = cls;
934 struct NSEPeerEntry *peer_entry = value;
935 struct GNUNET_TIME_Relative delay;
937 if (peer_entry->th != NULL)
938 return GNUNET_OK; /* already active */
939 if (peer_entry == exclude)
940 return GNUNET_OK; /* trigger of the update */
941 if (peer_entry->previous_round == GNUNET_NO)
943 /* still stuck in previous round, no point to update, check that
944 * we are active here though... */
945 GNUNET_break ((peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
946 (peer_entry->th != NULL));
949 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
951 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
952 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
954 delay = get_transmit_delay (0);
955 peer_entry->transmit_task =
956 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
962 * Core handler for size estimate flooding messages.
964 * @param cls closure unused
965 * @param message message
966 * @param peer peer identity this message is from (ignored)
967 * @param atsi performance data (ignored)
968 * @param atsi_count number of records in 'atsi'
971 handle_p2p_size_estimate (void *cls, const struct GNUNET_PeerIdentity *peer,
972 const struct GNUNET_MessageHeader *message,
973 const struct GNUNET_ATS_Information *atsi,
974 unsigned int atsi_count)
976 const struct GNUNET_NSE_FloodMessage *incoming_flood;
977 struct GNUNET_TIME_Absolute ts;
978 struct NSEPeerEntry *peer_entry;
979 uint32_t matching_bits;
984 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
986 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
987 GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
988 matching_bits = ntohl (incoming_flood->matching_bits);
993 struct GNUNET_PeerIdentity os;
995 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
996 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
998 GNUNET_snprintf (origin, sizeof (origin), "%s", GNUNET_i2s (&os));
999 GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer));
1000 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1001 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
1002 (unsigned long long)
1003 GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1004 origin, pred, GNUNET_i2s (&my_identity),
1005 (unsigned int) matching_bits);
1009 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1010 if (NULL == peer_entry)
1016 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1018 if (ts.abs_value == current_timestamp.abs_value)
1019 idx = estimate_index;
1020 else if (ts.abs_value ==
1021 current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1022 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1023 else if (ts.abs_value ==
1024 next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1026 if (matching_bits <= ntohl (next_message.matching_bits))
1027 return GNUNET_OK; /* ignore, simply too early/late */
1028 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1030 GNUNET_break_op (0);
1033 next_message = *incoming_flood;
1038 GNUNET_STATISTICS_update (stats,
1039 "# flood messages discarded (clock skew too large)",
1043 if (0 == (memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity))))
1045 /* send to self, update our own estimate IF this also comes from us! */
1047 memcmp (&incoming_flood->pkey, &my_public_key, sizeof (my_public_key)))
1048 update_network_size_estimate ();
1051 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1053 /* cancel transmission from us to this peer for this round */
1054 if (idx == estimate_index)
1056 if (peer_entry->previous_round == GNUNET_YES)
1058 /* cancel any activity for current round */
1059 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1061 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1062 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1064 if (peer_entry->th != NULL)
1066 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1067 peer_entry->th = NULL;
1073 /* cancel previous round only */
1074 peer_entry->previous_round = GNUNET_YES;
1077 if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1079 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1081 if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
1082 peer_entry->previous_round = GNUNET_NO;
1083 /* push back our result now, that peer is spreading bad information... */
1084 if (NULL == peer_entry->th)
1086 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1087 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1088 peer_entry->transmit_task =
1089 GNUNET_SCHEDULER_add_now (&transmit_task, peer_entry);
1091 /* Not closer than our most recent message, no need to do work here */
1092 GNUNET_STATISTICS_update (stats,
1093 "# flood messages ignored (had closer already)",
1097 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1099 GNUNET_break_op (0);
1102 size_estimate_messages[idx] = *incoming_flood;
1103 size_estimate_messages[idx].hop_count =
1104 htonl (ntohl (incoming_flood->hop_count) + 1);
1106 GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
1108 /* have a new, better size estimate, inform clients */
1109 update_network_size_estimate ();
1112 GNUNET_CONTAINER_multihashmap_iterate (peers, &update_flood_times,
1120 * Method called whenever a peer connects.
1122 * @param cls closure
1123 * @param peer peer identity this notification is about
1124 * @param atsi performance data
1125 * @param atsi_count number of records in 'atsi'
1128 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
1129 const struct GNUNET_ATS_Information *atsi,
1130 unsigned int atsi_count)
1132 struct NSEPeerEntry *peer_entry;
1135 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' connected to us\n",
1138 peer_entry = GNUNET_malloc (sizeof (struct NSEPeerEntry));
1139 peer_entry->id = *peer;
1140 GNUNET_assert (GNUNET_OK ==
1141 GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_entry,
1142 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1143 peer_entry->transmit_task =
1144 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), &transmit_task,
1150 * Method called whenever a peer disconnects.
1152 * @param cls closure
1153 * @param peer peer identity this notification is about
1156 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1158 struct NSEPeerEntry *pos;
1161 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' disconnected from us\n",
1164 pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1170 GNUNET_assert (GNUNET_YES ==
1171 GNUNET_CONTAINER_multihashmap_remove (peers, &peer->hashPubKey,
1173 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1174 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1175 if (pos->th != NULL)
1177 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1185 * Task run during shutdown.
1191 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1193 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1195 GNUNET_SCHEDULER_cancel (flood_task);
1196 flood_task = GNUNET_SCHEDULER_NO_TASK;
1198 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1200 GNUNET_SCHEDULER_cancel (proof_task);
1201 proof_task = GNUNET_SCHEDULER_NO_TASK;
1202 write_proof (); /* remember progress */
1206 GNUNET_SERVER_notification_context_destroy (nc);
1209 if (coreAPI != NULL)
1211 GNUNET_CORE_disconnect (coreAPI);
1216 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1221 GNUNET_CONTAINER_multihashmap_destroy (peers);
1224 if (my_private_key != NULL)
1226 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1227 my_private_key = NULL;
1229 #if ENABLE_HISTOGRAM
1232 GNUNET_BIO_write_close (wh);
1240 * Called on core init/fail.
1242 * @param cls service closure
1243 * @param server handle to the server for this service
1244 * @param identity the public identity of this peer
1247 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1248 const struct GNUNET_PeerIdentity *identity)
1250 struct GNUNET_TIME_Absolute now;
1251 struct GNUNET_TIME_Absolute prev_time;
1257 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection to core FAILED!\n");
1259 GNUNET_SCHEDULER_shutdown ();
1263 memcmp (&my_identity, identity,
1264 sizeof (struct GNUNET_PeerIdentity)));
1265 now = GNUNET_TIME_absolute_get ();
1266 current_timestamp.abs_value =
1267 (now.abs_value / gnunet_nse_interval.rel_value) *
1268 gnunet_nse_interval.rel_value;
1269 next_timestamp.abs_value =
1270 current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1272 for (i = 0; i < HISTORY_SIZE; i++)
1274 prev_time.abs_value =
1275 current_timestamp.abs_value - (HISTORY_SIZE - i -
1276 1) * gnunet_nse_interval.rel_value;
1277 setup_flood_message (i, prev_time);
1279 estimate_index = HISTORY_SIZE - 1;
1282 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1283 (next_timestamp), &update_flood_message,
1289 * Handle network size estimate clients.
1291 * @param cls closure
1292 * @param server the initialized server
1293 * @param c configuration to use
1296 run (void *cls, struct GNUNET_SERVER_Handle *server,
1297 const struct GNUNET_CONFIGURATION_Handle *c)
1302 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1303 {&handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START,
1304 sizeof (struct GNUNET_MessageHeader)},
1307 static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
1308 {&handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD,
1309 sizeof (struct GNUNET_NSE_FloodMessage)},
1315 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "INTERVAL",
1316 &gnunet_nse_interval)) ||
1318 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "WORKDELAY",
1319 &proof_find_delay)) ||
1321 GNUNET_CONFIGURATION_get_value_number (cfg, "NSE", "WORKBITS",
1322 &nse_work_required)))
1324 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1326 ("NSE service is lacking key configuration settings. Exiting.\n"));
1327 GNUNET_SCHEDULER_shutdown ();
1330 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1332 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1333 _("Invalid work requirement for NSE service. Exiting.\n"));
1334 GNUNET_SCHEDULER_shutdown ();
1340 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
1343 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1345 ("NSE service is lacking key configuration settings. Exiting.\n"));
1346 GNUNET_SCHEDULER_shutdown ();
1349 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1350 GNUNET_free (keyfile);
1351 if (my_private_key == NULL)
1353 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1354 _("NSE service could not access hostkey. Exiting.\n"));
1355 GNUNET_SCHEDULER_shutdown ();
1358 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1359 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1360 &my_identity.hashPubKey);
1362 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
1364 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1366 ("NSE service is lacking key configuration settings. Exiting.\n"));
1367 if (my_private_key != NULL)
1369 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1370 my_private_key = NULL;
1372 GNUNET_SCHEDULER_shutdown ();
1375 if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1376 (sizeof (my_proof) !=
1377 GNUNET_DISK_fn_read (proof, &my_proof, sizeof (my_proof))))
1379 GNUNET_free (proof);
1381 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1384 peers = GNUNET_CONTAINER_multihashmap_create (128);
1385 GNUNET_SERVER_add_handlers (server, handlers);
1386 nc = GNUNET_SERVER_notification_context_create (server, 1);
1387 /* Connect to core service and register core handlers */
1388 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1390 NULL, /* Closure passed to functions */
1391 &core_init, /* Call core_init once connected */
1392 &handle_core_connect, /* Handle connects */
1393 &handle_core_disconnect, /* Handle disconnects */
1394 NULL, /* Don't want notified about all incoming messages */
1395 GNUNET_NO, /* For header only inbound notification */
1396 NULL, /* Don't want notified about all outbound messages */
1397 GNUNET_NO, /* For header only outbound notification */
1398 core_handlers); /* Register these handlers */
1399 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1401 #if ENABLE_HISTOGRAM
1403 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "HISTOGRAM", &proof))
1405 wh = GNUNET_BIO_write_open (proof);
1406 GNUNET_free (proof);
1409 if (coreAPI == NULL)
1411 GNUNET_SCHEDULER_shutdown ();
1414 stats = GNUNET_STATISTICS_create ("nse", cfg);
1419 * The main function for the statistics service.
1421 * @param argc number of arguments from the command line
1422 * @param argv command line arguments
1423 * @return 0 ok, 1 on error
1426 main (int argc, char *const *argv)
1428 return (GNUNET_OK ==
1429 GNUNET_SERVICE_run (argc, argv, "nse", GNUNET_SERVICE_OPTION_NONE,
1430 &run, NULL)) ? 0 : 1;
1433 /* end of gnunet-service-nse.c */