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 8
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)
318 /* Weighted incremental algorithm for stddev according to West (1979) */
322 for (i = 0; i < estimate_count; i++)
325 htonl (size_estimate_messages
326 [(estimate_index - i +
327 HISTORY_SIZE) % HISTORY_SIZE].matching_bits);
328 weight = 1; /* was: estimate_count + 1 - i; */
330 temp = weight + sumweight;
332 r = q * weight / temp;
333 sum += sumweight * q * r;
337 variance = sum / (sumweight - 1.0);
338 GNUNET_assert (variance >= 0);
339 std_dev = sqrt (variance);
340 current_std_dev = std_dev;
341 current_size_estimate = mean;
343 em->header.size = htons (sizeof (struct GNUNET_NSE_ClientMessage));
344 em->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
345 em->reserved = htonl (0);
346 em->timestamp = GNUNET_TIME_absolute_hton (GNUNET_TIME_absolute_get ());
347 em->size_estimate = mean - 0.332747;
348 nsize = log2 (GNUNET_CONTAINER_multihashmap_size (peers) + 1);
349 if (em->size_estimate < nsize)
350 em->size_estimate = nsize;
351 em->std_deviation = std_dev;
352 GNUNET_STATISTICS_set (stats, "# nodes in the network (estimate)",
353 (uint64_t) pow (2, mean - 1.0 / 3.0), GNUNET_NO);
358 * Handler for START message from client, triggers an
359 * immediate current network estimate notification.
360 * Also, we remember the client for updates upon future
361 * estimate measurements.
364 * @param client who sent the message
365 * @param message the message received
368 handle_start_message (void *cls, struct GNUNET_SERVER_Client *client,
369 const struct GNUNET_MessageHeader *message)
371 struct GNUNET_NSE_ClientMessage em;
374 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Received START message from client\n");
376 GNUNET_SERVER_notification_context_add (nc, client);
377 setup_estimate_message (&em);
378 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header,
380 GNUNET_SERVER_receive_done (client, GNUNET_OK);
385 * How long should we delay a message to go the given number of
388 * @param matching_bits number of matching bits to consider
391 get_matching_bits_delay (uint32_t matching_bits)
393 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p')) */
394 // S is next_timestamp (ignored in return value)
395 // f is frequency (gnunet_nse_interval)
396 // x is matching_bits
397 // p' is current_size_estimate
398 return ((double) gnunet_nse_interval.rel_value / (double) 2.0) -
399 ((gnunet_nse_interval.rel_value / M_PI) *
400 atan (matching_bits - current_size_estimate));
405 * What delay randomization should we apply for a given number of matching bits?
407 * @param matching_bits number of matching bits
408 * @return random delay to apply
410 static struct GNUNET_TIME_Relative
411 get_delay_randomization (uint32_t matching_bits)
413 #if USE_RANDOM_DELAYS
414 struct GNUNET_TIME_Relative ret;
416 if (matching_bits == 0)
417 return GNUNET_TIME_UNIT_ZERO;
419 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
420 (uint32_t) (get_matching_bits_delay
422 1) / (double) (hop_count_max +
426 return GNUNET_TIME_UNIT_ZERO;
432 * Get the number of matching bits that the given timestamp has to the given peer ID.
434 * @param timestamp time to generate key
435 * @param id peer identity to compare with
436 * @return number of matching bits
439 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
440 const struct GNUNET_PeerIdentity *id)
442 GNUNET_HashCode timestamp_hash;
444 GNUNET_CRYPTO_hash (×tamp.abs_value, sizeof (timestamp.abs_value),
446 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash, &id->hashPubKey);
451 * Get the transmission delay that should be applied for a
454 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
455 * 0 for the current round (based on our proximity to time key)
456 * @return delay that should be applied
458 static struct GNUNET_TIME_Relative
459 get_transmit_delay (int round_offset)
461 struct GNUNET_TIME_Relative ret;
462 struct GNUNET_TIME_Absolute tgt;
464 uint32_t matching_bits;
466 switch (round_offset)
469 /* previous round is randomized between 0 and 50 ms */
470 #if USE_RANDOM_DELAYS
471 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
473 ret = GNUNET_TIME_UNIT_ZERO;
476 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
477 "Transmitting previous round behind schedule in %llu ms\n",
478 (unsigned long long) ret.rel_value);
482 /* current round is based on best-known matching_bits */
484 ntohl (size_estimate_messages[estimate_index].matching_bits);
485 dist_delay = get_matching_bits_delay (matching_bits);
486 dist_delay += get_delay_randomization (matching_bits).rel_value;
487 ret.rel_value = (uint64_t) dist_delay;
489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
490 "For round %llu, delay for %u matching bits is %llu ms\n",
491 (unsigned long long) current_timestamp.abs_value,
492 (unsigned int) matching_bits,
493 (unsigned long long) ret.rel_value);
495 /* now consider round start time and add delay to it */
496 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
497 return GNUNET_TIME_absolute_get_remaining (tgt);
500 return GNUNET_TIME_UNIT_FOREVER_REL;
505 * Task that triggers a NSE P2P transmission.
507 * @param cls the 'struct NSEPeerEntry'
508 * @param tc scheduler context
511 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
515 * Called when core is ready to send a message we asked for
516 * out to the destination.
518 * @param cls closure (NULL)
519 * @param size number of bytes available in buf
520 * @param buf where the callee should write the message
521 * @return number of bytes written to buf
524 transmit_ready (void *cls, size_t size, void *buf)
526 struct NSEPeerEntry *peer_entry = cls;
529 peer_entry->th = NULL;
532 /* client disconnected */
535 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
536 idx = estimate_index;
537 if (peer_entry->previous_round == GNUNET_NO)
539 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
540 peer_entry->previous_round = GNUNET_YES;
541 peer_entry->transmit_task =
542 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), &transmit_task,
545 if ((ntohl (size_estimate_messages[idx].hop_count) == 0) &&
546 (GNUNET_SCHEDULER_NO_TASK != proof_task))
548 GNUNET_STATISTICS_update (stats,
549 "# flood messages not generated (no proof yet)",
554 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
555 "In round %llu, sending to `%s' estimate with %u bits\n",
557 GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].
558 timestamp).abs_value,
559 GNUNET_i2s (&peer_entry->id),
560 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
562 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
563 GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO);
564 GNUNET_STATISTICS_update (stats, "# flood messages transmitted", 1,
566 memcpy (buf, &size_estimate_messages[idx],
567 sizeof (struct GNUNET_NSE_FloodMessage));
568 GNUNET_STATISTICS_update (stats, "# flood messages sent", 1, GNUNET_NO);
569 return sizeof (struct GNUNET_NSE_FloodMessage);
574 * Task that triggers a NSE P2P transmission.
576 * @param cls the 'struct NSEPeerEntry'
577 * @param tc scheduler context
580 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
582 struct NSEPeerEntry *peer_entry = cls;
584 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
585 GNUNET_assert (NULL == peer_entry->th);
587 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO, NSE_PRIORITY,
588 GNUNET_TIME_UNIT_FOREVER_REL,
591 GNUNET_NSE_FloodMessage),
592 &transmit_ready, peer_entry);
597 * We've sent on our flood message or one that we received which was
598 * validated and closer than ours. Update the global list of recent
599 * messages and the average. Also re-broadcast the message to any
603 update_network_size_estimate ()
605 struct GNUNET_NSE_ClientMessage em;
607 setup_estimate_message (&em);
608 GNUNET_SERVER_notification_context_broadcast (nc, &em.header, GNUNET_YES);
613 * Setup a flood message in our history array at the given
614 * slot offset for the given timestamp.
616 * @param slot index to use
617 * @param ts timestamp to use
620 setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts)
622 struct GNUNET_NSE_FloodMessage *fm;
623 uint32_t matching_bits;
625 matching_bits = get_matching_bits (ts, &my_identity);
626 fm = &size_estimate_messages[slot];
627 fm->header.size = htons (sizeof (struct GNUNET_NSE_FloodMessage));
628 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
629 fm->hop_count = htonl (0);
630 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
632 htonl (sizeof (struct GNUNET_NSE_FloodMessage) -
633 sizeof (struct GNUNET_MessageHeader) - sizeof (uint32_t) -
634 sizeof (struct GNUNET_CRYPTO_RsaSignature));
635 fm->matching_bits = htonl (matching_bits);
636 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
637 fm->pkey = my_public_key;
638 fm->proof_of_work = my_proof;
639 GNUNET_assert (GNUNET_OK ==
640 GNUNET_CRYPTO_rsa_sign (my_private_key, &fm->purpose,
646 * Schedule transmission for the given peer for the current round based
647 * on what we know about the desired delay.
650 * @param key hash of peer identity
651 * @param value the 'struct NSEPeerEntry'
652 * @return GNUNET_OK (continue to iterate)
655 schedule_current_round (void *cls, const GNUNET_HashCode * key, void *value)
657 struct NSEPeerEntry *peer_entry = value;
658 struct GNUNET_TIME_Relative delay;
660 if (peer_entry->th != NULL)
662 peer_entry->previous_round = GNUNET_NO;
665 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
667 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
668 peer_entry->previous_round = GNUNET_NO;
671 get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
672 peer_entry->transmit_task =
673 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
679 * Update our flood message to be sent (and our timestamps).
682 * @param tc context for this message
685 update_flood_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
687 struct GNUNET_TIME_Relative offset;
690 flood_task = GNUNET_SCHEDULER_NO_TASK;
691 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
692 if (0 != offset.rel_value)
694 /* somehow run early, delay more */
696 GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL);
699 current_timestamp = next_timestamp;
701 GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
702 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
703 if (estimate_count < HISTORY_SIZE)
705 if (next_timestamp.abs_value ==
706 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
708 /* we received a message for this round way early, use it! */
709 size_estimate_messages[estimate_index] = next_message;
710 size_estimate_messages[estimate_index].hop_count =
711 htonl (1 + ntohl (next_message.hop_count));
714 setup_flood_message (estimate_index, current_timestamp);
715 next_message.matching_bits = htonl (0); /* reset for 'next' round */
717 for (i = 0; i < HISTORY_SIZE; i++)
719 GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max);
720 GNUNET_CONTAINER_multihashmap_iterate (peers, &schedule_current_round, NULL);
722 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
723 (next_timestamp), &update_flood_message,
729 * Count the leading zeroes in hash.
732 * @return the number of leading zero bits.
735 count_leading_zeroes (const GNUNET_HashCode * hash)
737 unsigned int hash_count;
740 while ((0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)))
747 * Check whether the given public key
748 * and integer are a valid proof of work.
750 * @param pkey the public key
751 * @param val the integer
753 * @return GNUNET_YES if valid, GNUNET_NO if not
756 check_proof_of_work (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
759 char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
761 GNUNET_HashCode result;
763 memcpy (buf, &val, sizeof (val));
764 memcpy (&buf[sizeof (val)], pkey,
765 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
766 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
767 return (count_leading_zeroes (&result) >=
768 nse_work_required) ? GNUNET_YES : GNUNET_NO;
773 * Write our current proof to disk.
781 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
783 if (sizeof (my_proof) !=
784 GNUNET_DISK_fn_write (proof, &my_proof, sizeof (my_proof),
785 GNUNET_DISK_PERM_USER_READ |
786 GNUNET_DISK_PERM_USER_WRITE))
787 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof);
794 * Find our proof of work.
796 * @param cls closure (unused)
797 * @param tc task context
800 find_proof (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
802 #define ROUND_SIZE 10
804 char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
806 GNUNET_HashCode result;
809 proof_task = GNUNET_SCHEDULER_NO_TASK;
810 memcpy (&buf[sizeof (uint64_t)], &my_public_key,
811 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
814 while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
816 memcpy (buf, &counter, sizeof (uint64_t));
817 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
818 if (nse_work_required <= count_leading_zeroes (&result))
822 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Proof of work found: %llu!\n",
823 (unsigned long long) GNUNET_ntohll (counter));
825 for (i = 0; i < HISTORY_SIZE; i++)
826 if (ntohl (size_estimate_messages[i].hop_count) == 0)
828 size_estimate_messages[i].proof_of_work = my_proof;
829 GNUNET_assert (GNUNET_OK ==
830 GNUNET_CRYPTO_rsa_sign (my_private_key,
831 &size_estimate_messages
833 &size_estimate_messages
842 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
845 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Testing proofs currently at %llu\n",
846 (unsigned long long) counter);
848 /* remember progress every 100 rounds */
857 GNUNET_SCHEDULER_add_delayed (proof_find_delay, &find_proof, NULL);
862 * An incoming flood message has been received which claims
863 * to have more bits matching than any we know in this time
864 * period. Verify the signature and/or proof of work.
866 * @param incoming_flood the message to verify
868 * @return GNUNET_YES if the message is verified
869 * GNUNET_NO if the key/signature don't verify
872 verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
875 check_proof_of_work (&incoming_flood->pkey,
876 incoming_flood->proof_of_work))
878 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Proof of work invalid: %llu!\n"),
880 GNUNET_ntohll (incoming_flood->proof_of_work));
885 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
886 &incoming_flood->purpose,
887 &incoming_flood->signature,
888 &incoming_flood->pkey))
898 * Update transmissions for the given peer for the current round based
899 * on updated proximity information.
901 * @param cls peer entry to exclude from updates
902 * @param key hash of peer identity
903 * @param value the 'struct NSEPeerEntry'
904 * @return GNUNET_OK (continue to iterate)
907 update_flood_times (void *cls, const GNUNET_HashCode * key, void *value)
909 struct NSEPeerEntry *exclude = cls;
910 struct NSEPeerEntry *peer_entry = value;
911 struct GNUNET_TIME_Relative delay;
913 if (peer_entry->th != NULL)
914 return GNUNET_OK; /* already active */
915 if (peer_entry == exclude)
916 return GNUNET_OK; /* trigger of the update */
917 if (peer_entry->previous_round == GNUNET_NO)
919 /* still stuck in previous round, no point to update, check that
920 * we are active here though... */
921 GNUNET_break ((peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
922 (peer_entry->th != NULL));
925 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
927 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
928 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
930 delay = get_transmit_delay (0);
931 peer_entry->transmit_task =
932 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
938 * Core handler for size estimate flooding messages.
940 * @param cls closure unused
941 * @param message message
942 * @param peer peer identity this message is from (ignored)
943 * @param atsi performance data (ignored)
944 * @param atsi_count number of records in 'atsi'
947 handle_p2p_size_estimate (void *cls, const struct GNUNET_PeerIdentity *peer,
948 const struct GNUNET_MessageHeader *message,
949 const struct GNUNET_ATS_Information *atsi,
950 unsigned int atsi_count)
952 const struct GNUNET_NSE_FloodMessage *incoming_flood;
953 struct GNUNET_TIME_Absolute ts;
954 struct NSEPeerEntry *peer_entry;
955 uint32_t matching_bits;
960 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
962 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
963 GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
964 matching_bits = ntohl (incoming_flood->matching_bits);
969 struct GNUNET_PeerIdentity os;
971 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
972 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
974 GNUNET_snprintf (origin, sizeof (origin), "%s", GNUNET_i2s (&os));
975 GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer));
976 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
977 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
979 GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
980 origin, pred, GNUNET_i2s (&my_identity),
981 (unsigned int) matching_bits);
985 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
986 if (NULL == peer_entry)
992 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
994 if (ts.abs_value == current_timestamp.abs_value)
995 idx = estimate_index;
996 else if (ts.abs_value ==
997 current_timestamp.abs_value - gnunet_nse_interval.rel_value)
998 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
999 else if (ts.abs_value ==
1000 next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1002 if (matching_bits <= ntohl (next_message.matching_bits))
1003 return GNUNET_OK; /* ignore, simply too early/late */
1004 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1006 GNUNET_break_op (0);
1009 next_message = *incoming_flood;
1014 GNUNET_STATISTICS_update (stats,
1015 "# flood messages discarded (clock skew too large)",
1019 if (0 == (memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity))))
1021 /* send to self, update our own estimate IF this also comes from us! */
1023 memcmp (&incoming_flood->pkey, &my_public_key, sizeof (my_public_key)))
1024 update_network_size_estimate ();
1027 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1029 /* cancel transmission from us to this peer for this round */
1030 if (idx == estimate_index)
1032 if (peer_entry->previous_round == GNUNET_YES)
1034 /* cancel any activity for current round */
1035 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1037 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1038 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1040 if (peer_entry->th != NULL)
1042 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1043 peer_entry->th = NULL;
1049 /* cancel previous round only */
1050 peer_entry->previous_round = GNUNET_YES;
1053 if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1055 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1057 if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
1058 peer_entry->previous_round = GNUNET_NO;
1059 /* push back our result now, that peer is spreading bad information... */
1060 if (NULL == peer_entry->th)
1062 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1063 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1064 peer_entry->transmit_task =
1065 GNUNET_SCHEDULER_add_now (&transmit_task, peer_entry);
1067 /* Not closer than our most recent message, no need to do work here */
1068 GNUNET_STATISTICS_update (stats,
1069 "# flood messages ignored (had closer already)",
1073 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1075 GNUNET_break_op (0);
1078 size_estimate_messages[idx] = *incoming_flood;
1079 size_estimate_messages[idx].hop_count =
1080 htonl (ntohl (incoming_flood->hop_count) + 1);
1082 GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
1084 /* have a new, better size estimate, inform clients */
1085 update_network_size_estimate ();
1088 GNUNET_CONTAINER_multihashmap_iterate (peers, &update_flood_times,
1096 * Method called whenever a peer connects.
1098 * @param cls closure
1099 * @param peer peer identity this notification is about
1100 * @param atsi performance data
1101 * @param atsi_count number of records in 'atsi'
1104 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
1105 const struct GNUNET_ATS_Information *atsi,
1106 unsigned int atsi_count)
1108 struct NSEPeerEntry *peer_entry;
1111 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' connected to us\n",
1114 peer_entry = GNUNET_malloc (sizeof (struct NSEPeerEntry));
1115 peer_entry->id = *peer;
1116 GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey, peer_entry,
1117 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1118 peer_entry->transmit_task =
1119 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), &transmit_task,
1125 * Method called whenever a peer disconnects.
1127 * @param cls closure
1128 * @param peer peer identity this notification is about
1131 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1133 struct NSEPeerEntry *pos;
1136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' disconnected from us\n",
1139 pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1145 GNUNET_assert (GNUNET_YES ==
1146 GNUNET_CONTAINER_multihashmap_remove (peers, &peer->hashPubKey,
1148 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1149 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1150 if (pos->th != NULL)
1152 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1160 * Task run during shutdown.
1166 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1168 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1170 GNUNET_SCHEDULER_cancel (flood_task);
1171 flood_task = GNUNET_SCHEDULER_NO_TASK;
1173 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1175 GNUNET_SCHEDULER_cancel (proof_task);
1176 proof_task = GNUNET_SCHEDULER_NO_TASK;
1177 write_proof (); /* remember progress */
1181 GNUNET_SERVER_notification_context_destroy (nc);
1184 if (coreAPI != NULL)
1186 GNUNET_CORE_disconnect (coreAPI);
1191 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1196 GNUNET_CONTAINER_multihashmap_destroy (peers);
1199 if (my_private_key != NULL)
1201 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1202 my_private_key = NULL;
1204 #if ENABLE_HISTOGRAM
1207 GNUNET_BIO_write_close (wh);
1215 * Called on core init/fail.
1217 * @param cls service closure
1218 * @param server handle to the server for this service
1219 * @param identity the public identity of this peer
1222 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1223 const struct GNUNET_PeerIdentity *identity)
1225 struct GNUNET_TIME_Absolute now;
1226 struct GNUNET_TIME_Absolute prev_time;
1232 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection to core FAILED!\n");
1234 GNUNET_SCHEDULER_shutdown ();
1238 memcmp (&my_identity, identity,
1239 sizeof (struct GNUNET_PeerIdentity)));
1240 now = GNUNET_TIME_absolute_get ();
1241 current_timestamp.abs_value =
1242 (now.abs_value / gnunet_nse_interval.rel_value) *
1243 gnunet_nse_interval.rel_value;
1244 next_timestamp.abs_value =
1245 current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1247 for (i = 0; i < HISTORY_SIZE; i++)
1249 prev_time.abs_value =
1250 current_timestamp.abs_value - (HISTORY_SIZE - i -
1251 1) * gnunet_nse_interval.rel_value;
1252 setup_flood_message (i, prev_time);
1254 estimate_index = HISTORY_SIZE - 1;
1257 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1258 (next_timestamp), &update_flood_message,
1264 * Handle network size estimate clients.
1266 * @param cls closure
1267 * @param server the initialized server
1268 * @param c configuration to use
1271 run (void *cls, struct GNUNET_SERVER_Handle *server,
1272 const struct GNUNET_CONFIGURATION_Handle *c)
1277 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1278 {&handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START,
1279 sizeof (struct GNUNET_MessageHeader)},
1282 static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
1283 {&handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD,
1284 sizeof (struct GNUNET_NSE_FloodMessage)},
1290 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "INTERVAL",
1291 &gnunet_nse_interval)) ||
1293 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "WORKDELAY",
1294 &proof_find_delay)) ||
1296 GNUNET_CONFIGURATION_get_value_number (cfg, "NSE", "WORKBITS",
1297 &nse_work_required)))
1299 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1301 ("NSE service is lacking key configuration settings. Exiting.\n"));
1302 GNUNET_SCHEDULER_shutdown ();
1305 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1307 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1308 _("Invalid work requirement for NSE service. Exiting.\n"));
1309 GNUNET_SCHEDULER_shutdown ();
1315 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
1318 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1320 ("NSE service is lacking key configuration settings. Exiting.\n"));
1321 GNUNET_SCHEDULER_shutdown ();
1324 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1325 GNUNET_free (keyfile);
1326 if (my_private_key == NULL)
1328 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1329 _("NSE service could not access hostkey. Exiting.\n"));
1330 GNUNET_SCHEDULER_shutdown ();
1333 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1334 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1335 &my_identity.hashPubKey);
1337 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
1339 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1341 ("NSE service is lacking key configuration settings. Exiting.\n"));
1342 if (my_private_key != NULL)
1344 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1345 my_private_key = NULL;
1347 GNUNET_SCHEDULER_shutdown ();
1350 if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1351 (sizeof (my_proof) !=
1352 GNUNET_DISK_fn_read (proof, &my_proof, sizeof (my_proof))))
1354 GNUNET_free (proof);
1356 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1359 peers = GNUNET_CONTAINER_multihashmap_create (128);
1360 GNUNET_SERVER_add_handlers (server, handlers);
1361 nc = GNUNET_SERVER_notification_context_create (server, 1);
1362 /* Connect to core service and register core handlers */
1363 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1364 CORE_QUEUE_SIZE, /* queue size */
1365 NULL, /* Closure passed to functions */
1366 &core_init, /* Call core_init once connected */
1367 &handle_core_connect, /* Handle connects */
1368 &handle_core_disconnect, /* Handle disconnects */
1369 NULL, /* Don't want notified about all incoming messages */
1370 GNUNET_NO, /* For header only inbound notification */
1371 NULL, /* Don't want notified about all outbound messages */
1372 GNUNET_NO, /* For header only outbound notification */
1373 core_handlers); /* Register these handlers */
1374 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1376 #if ENABLE_HISTOGRAM
1378 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "HISTOGRAM", &proof))
1380 wh = GNUNET_BIO_write_open (proof);
1381 GNUNET_free (proof);
1384 if (coreAPI == NULL)
1386 GNUNET_SCHEDULER_shutdown ();
1389 stats = GNUNET_STATISTICS_create ("nse", cfg);
1394 * The main function for the statistics service.
1396 * @param argc number of arguments from the command line
1397 * @param argv command line arguments
1398 * @return 0 ok, 1 on error
1401 main (int argc, char *const *argv)
1403 return (GNUNET_OK ==
1404 GNUNET_SERVICE_run (argc, argv, "nse", GNUNET_SERVICE_OPTION_NONE,
1405 &run, NULL)) ? 0 : 1;
1408 /* end of gnunet-service-nse.c */