2 This file is part of GNUnet.
3 (C) 2009, 2010, 2011 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file nse/gnunet-service-nse.c
23 * @brief network size estimation service
24 * @author Nathan Evans
25 * @author Christian Grothoff
27 * The purpose of this service is to estimate the size of the network.
28 * Given a specified interval, each peer hashes the most recent
29 * timestamp which is evenly divisible by that interval. This hash is
30 * compared in distance to the peer identity to choose an offset. The
31 * closer the peer identity to the hashed timestamp, the earlier the
32 * peer sends out a "nearest peer" message. The closest peer's
33 * message should thus be received before any others, which stops
34 * those peer from sending their messages at a later duration. So
35 * every peer should receive the same nearest peer message, and from
36 * this can calculate the expected number of peers in the network.
39 #include "gnunet_util_lib.h"
40 #include "gnunet_constants.h"
41 #include "gnunet_protocols.h"
42 #include "gnunet_signatures.h"
43 #include "gnunet_statistics_service.h"
44 #include "gnunet_core_service.h"
45 #include "gnunet_nse_service.h"
49 * Should messages be delayed randomly? This option should be set to
50 * GNUNET_NO only for experiments, not in production. It should also
51 * be removed once the initial experiments have been completed.
53 #define USE_RANDOM_DELAYS GNUNET_YES
56 * Should we generate a histogram with the time stamps of when we received
57 * NSE messages to disk? (for performance evaluation only, not useful in
58 * production). The associated code should also probably be removed
59 * once we're done with experiments.
61 #define ENABLE_HISTOGRAM GNUNET_NO
64 * Over how many values do we calculate the weighted average?
66 #define HISTORY_SIZE 8
69 * Size of the queue to core.
71 #define CORE_QUEUE_SIZE 2
74 * Message priority to use.
76 #define NSE_PRIORITY 5
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.
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;
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;
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)
312 /* Weighted incremental algorithm for stddev according to West (1979) */
316 for (i = 0; i < estimate_count; i++)
318 val = htonl (size_estimate_messages[(estimate_index - i + HISTORY_SIZE)
319 % HISTORY_SIZE].matching_bits);
320 weight = 1; /* was: estimate_count + 1 - i; */
322 temp = weight + sumweight;
324 r = q * weight / temp;
325 sum += sumweight * q * r;
329 variance = sum / (sumweight - 1.0);
330 GNUNET_assert (variance >= 0);
331 std_dev = sqrt (variance);
332 current_std_dev = std_dev;
333 current_size_estimate = mean;
336 = htons (sizeof(struct GNUNET_NSE_ClientMessage));
338 = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
339 em->reserved = htonl (0);
340 em->timestamp = GNUNET_TIME_absolute_hton(GNUNET_TIME_absolute_get());
341 em->size_estimate = mean - 1.0/3.0;
342 em->std_deviation = std_dev;
343 GNUNET_STATISTICS_set (stats,
344 "# nodes in the network (estimate)",
345 (uint64_t) pow (2, mean - 1.0/3.0), GNUNET_NO);
350 * Handler for START message from client, triggers an
351 * immediate current network estimate notification.
352 * Also, we remember the client for updates upon future
353 * estimate measurements.
356 * @param client who sent the message
357 * @param message the message received
360 handle_start_message(void *cls, struct GNUNET_SERVER_Client *client,
361 const struct GNUNET_MessageHeader *message)
363 struct GNUNET_NSE_ClientMessage em;
366 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
367 "Received START message from client\n");
369 GNUNET_SERVER_notification_context_add (nc, client);
370 setup_estimate_message (&em);
371 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header, GNUNET_YES);
372 GNUNET_SERVER_receive_done (client, GNUNET_OK);
377 * How long should we delay a message to go the given number of
380 * @param matching_bits number of matching bits to consider
383 get_matching_bits_delay (uint32_t matching_bits)
385 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p'))*/
386 // S is next_timestamp (ignored in return value)
387 // f is frequency (gnunet_nse_interval)
388 // x is matching_bits
389 // p' is current_size_estimate
390 return ((double) gnunet_nse_interval.rel_value / (double) 2.0)
391 - ((gnunet_nse_interval.rel_value / M_PI) * atan (matching_bits - current_size_estimate));
396 * What delay randomization should we apply for a given number of matching bits?
398 * @param matching_bits number of matching bits
399 * @return random delay to apply
401 static struct GNUNET_TIME_Relative
402 get_delay_randomization (uint32_t matching_bits)
404 #if USE_RANDOM_DELAYS
405 struct GNUNET_TIME_Relative ret;
407 if (matching_bits == 0)
408 return GNUNET_TIME_UNIT_ZERO;
409 ret.rel_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
410 (uint32_t) (get_matching_bits_delay (matching_bits - 1) / (double) (hop_count_max + 1)));
413 return GNUNET_TIME_UNIT_ZERO;
419 * Get the number of matching bits that the given timestamp has to the given peer ID.
421 * @param timestamp time to generate key
422 * @param id peer identity to compare with
423 * @return number of matching bits
426 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
427 const struct GNUNET_PeerIdentity *id)
429 GNUNET_HashCode timestamp_hash;
431 GNUNET_CRYPTO_hash (×tamp.abs_value,
432 sizeof(timestamp.abs_value),
434 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash,
440 * Get the transmission delay that should be applied for a
443 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
444 * 0 for the current round (based on our proximity to time key)
445 * @return delay that should be applied
447 static struct GNUNET_TIME_Relative
448 get_transmit_delay (int round_offset)
450 struct GNUNET_TIME_Relative ret;
451 struct GNUNET_TIME_Absolute tgt;
453 uint32_t matching_bits;
455 switch (round_offset)
458 /* previous round is randomized between 0 and 50 ms */
459 #if USE_RANDOM_DELAYS
460 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
463 ret = GNUNET_TIME_UNIT_ZERO;
466 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
467 "Transmitting previous round behind schedule in %llu ms\n",
468 (unsigned long long) ret.rel_value);
472 /* current round is based on best-known matching_bits */
473 matching_bits = ntohl (size_estimate_messages[estimate_index].matching_bits);
474 dist_delay = get_matching_bits_delay (matching_bits);
475 dist_delay += get_delay_randomization (matching_bits).rel_value;
476 ret.rel_value = (uint64_t) dist_delay;
478 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
479 "For round %llu, delay for %u matching bits is %llu ms\n",
480 (unsigned long long) current_timestamp.abs_value,
481 (unsigned int) matching_bits,
482 (unsigned long long) ret.rel_value);
484 /* now consider round start time and add delay to it */
485 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
486 return GNUNET_TIME_absolute_get_remaining (tgt);
489 return GNUNET_TIME_UNIT_FOREVER_REL;
494 * Task that triggers a NSE P2P transmission.
496 * @param cls the 'struct NSEPeerEntry'
497 * @param tc scheduler context
500 transmit_task (void *cls,
501 const struct GNUNET_SCHEDULER_TaskContext *tc);
505 * Called when core is ready to send a message we asked for
506 * out to the destination.
508 * @param cls closure (NULL)
509 * @param size number of bytes available in buf
510 * @param buf where the callee should write the message
511 * @return number of bytes written to buf
514 transmit_ready (void *cls, size_t size, void *buf)
516 struct NSEPeerEntry *peer_entry = cls;
519 peer_entry->th = NULL;
522 /* client disconnected */
525 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
526 idx = estimate_index;
527 if (peer_entry->previous_round == GNUNET_NO)
529 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
530 peer_entry->previous_round = GNUNET_YES;
531 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0),
535 if ( (ntohl (size_estimate_messages[idx].hop_count) == 0) &&
536 (GNUNET_SCHEDULER_NO_TASK != proof_task) )
538 GNUNET_STATISTICS_update (stats,
539 "# flood messages not generated (no proof yet)",
545 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
546 "In round %llu, sending to `%s' estimate with %u bits\n",
547 (unsigned long long) GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].timestamp).abs_value,
548 GNUNET_i2s (&peer_entry->id),
549 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
551 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
552 GNUNET_STATISTICS_update (stats,
553 "# flood messages started",
556 GNUNET_STATISTICS_update (stats,
557 "# flood messages transmitted",
561 &size_estimate_messages[idx],
562 sizeof (struct GNUNET_NSE_FloodMessage));
563 GNUNET_STATISTICS_update (stats,
564 "# flood messages sent",
567 return sizeof (struct GNUNET_NSE_FloodMessage);
572 * Task that triggers a NSE P2P transmission.
574 * @param cls the 'struct NSEPeerEntry'
575 * @param tc scheduler context
578 transmit_task (void *cls,
579 const struct GNUNET_SCHEDULER_TaskContext *tc)
581 struct NSEPeerEntry *peer_entry = cls;
583 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
584 GNUNET_assert (NULL == peer_entry->th);
586 = GNUNET_CORE_notify_transmit_ready (coreAPI,
589 GNUNET_TIME_UNIT_FOREVER_REL,
591 sizeof (struct 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,
615 * Setup a flood message in our history array at the given
616 * slot offset for the given timestamp.
618 * @param slot index to use
619 * @param ts timestamp to use
622 setup_flood_message (unsigned int slot,
623 struct GNUNET_TIME_Absolute ts)
625 struct GNUNET_NSE_FloodMessage *fm;
626 uint32_t matching_bits;
628 matching_bits = get_matching_bits (ts, &my_identity);
629 fm = &size_estimate_messages[slot];
630 fm->header.size = htons (sizeof(struct GNUNET_NSE_FloodMessage));
631 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
632 fm->hop_count = htonl (0);
633 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
634 fm->purpose.size = htonl (sizeof(struct GNUNET_NSE_FloodMessage)
635 - sizeof (struct GNUNET_MessageHeader)
637 - sizeof (struct GNUNET_CRYPTO_RsaSignature));
638 fm->matching_bits = htonl (matching_bits);
639 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
640 fm->pkey = my_public_key;
641 fm->proof_of_work = my_proof;
642 GNUNET_CRYPTO_rsa_sign (my_private_key,
649 * Schedule transmission for the given peer for the current round based
650 * on what we know about the desired delay.
653 * @param key hash of peer identity
654 * @param value the 'struct NSEPeerEntry'
655 * @return GNUNET_OK (continue to iterate)
658 schedule_current_round (void *cls,
659 const GNUNET_HashCode *key,
662 struct NSEPeerEntry *peer_entry = value;
663 struct GNUNET_TIME_Relative delay;
665 if (peer_entry->th != NULL)
667 peer_entry->previous_round = GNUNET_NO;
670 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
672 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
673 peer_entry->previous_round = GNUNET_NO;
675 delay = get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
676 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
684 * Update our flood message to be sent (and our timestamps).
687 * @param tc context for this message
690 update_flood_message(void *cls,
691 const struct GNUNET_SCHEDULER_TaskContext *tc)
693 struct GNUNET_TIME_Relative offset;
696 flood_task = GNUNET_SCHEDULER_NO_TASK;
697 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
698 if (0 != offset.rel_value)
700 /* somehow run early, delay more */
702 = GNUNET_SCHEDULER_add_delayed (offset,
703 &update_flood_message,
707 current_timestamp = next_timestamp;
708 next_timestamp = GNUNET_TIME_absolute_add (current_timestamp,
709 gnunet_nse_interval);
710 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
711 if (estimate_count < HISTORY_SIZE)
713 if (next_timestamp.abs_value ==
714 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
716 /* we received a message for this round way early, use it! */
717 size_estimate_messages[estimate_index] = next_message;
718 size_estimate_messages[estimate_index].hop_count
719 = htonl (1 + ntohl (next_message.hop_count));
722 setup_flood_message (estimate_index, current_timestamp);
723 next_message.matching_bits = htonl (0); /* reset for 'next' round */
725 for (i = 0; i < HISTORY_SIZE; i++)
726 hop_count_max = GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count),
728 GNUNET_CONTAINER_multihashmap_iterate (peers,
729 &schedule_current_round,
731 flood_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
732 &update_flood_message, NULL);
737 * Count the leading zeroes in hash.
740 * @return the number of leading zero bits.
743 count_leading_zeroes(const GNUNET_HashCode *hash)
745 unsigned int hash_count;
748 while ((0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count)))
755 * Check whether the given public key
756 * and integer are a valid proof of work.
758 * @param pkey the public key
759 * @param val the integer
761 * @return GNUNET_YES if valid, GNUNET_NO if not
764 check_proof_of_work(const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
767 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(val)];
768 GNUNET_HashCode result;
773 memcpy (&buf[sizeof(val)],
775 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
776 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
777 return (count_leading_zeroes (&result) >= nse_work_required) ? GNUNET_YES : GNUNET_NO;
782 * Write our current proof to disk.
790 GNUNET_CONFIGURATION_get_value_filename (cfg,
794 if (sizeof (my_proof) !=
795 GNUNET_DISK_fn_write (proof,
798 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE))
799 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
808 * Find our proof of work.
810 * @param cls closure (unused)
811 * @param tc task context
814 find_proof (void *cls,
815 const struct GNUNET_SCHEDULER_TaskContext *tc)
817 #define ROUND_SIZE 10
819 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(uint64_t)];
820 GNUNET_HashCode result;
823 proof_task = GNUNET_SCHEDULER_NO_TASK;
824 memcpy (&buf[sizeof(uint64_t)],
826 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
829 while ( (counter != UINT64_MAX) && (i < ROUND_SIZE) )
834 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
835 if (nse_work_required <= count_leading_zeroes(&result))
839 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
840 "Proof of work found: %llu!\n",
841 (unsigned long long) GNUNET_ntohll (counter));
843 for (i=0;i<HISTORY_SIZE;i++)
844 if (ntohl (size_estimate_messages[i].hop_count) == 0)
846 size_estimate_messages[i].proof_of_work = my_proof;
847 GNUNET_CRYPTO_rsa_sign (my_private_key,
848 &size_estimate_messages[i].purpose,
849 &size_estimate_messages[i].signature);
857 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
860 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
861 "Testing proofs currently at %llu\n",
862 (unsigned long long) counter);
864 /* remember progress every 100 rounds */
872 proof_task = GNUNET_SCHEDULER_add_delayed (proof_find_delay,
879 * An incoming flood message has been received which claims
880 * to have more bits matching than any we know in this time
881 * period. Verify the signature and/or proof of work.
883 * @param incoming_flood the message to verify
885 * @return GNUNET_YES if the message is verified
886 * GNUNET_NO if the key/signature don't verify
889 verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood)
892 check_proof_of_work (&incoming_flood->pkey,
893 incoming_flood->proof_of_work))
895 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
896 _("Proof of work invalid: %llu!\n"),
897 (unsigned long long) GNUNET_ntohll (incoming_flood->proof_of_work));
902 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
903 &incoming_flood->purpose,
904 &incoming_flood->signature,
905 &incoming_flood->pkey))
915 * Update transmissions for the given peer for the current round based
916 * on updated proximity information.
918 * @param cls peer entry to exclude from updates
919 * @param key hash of peer identity
920 * @param value the 'struct NSEPeerEntry'
921 * @return GNUNET_OK (continue to iterate)
924 update_flood_times (void *cls,
925 const GNUNET_HashCode *key,
928 struct NSEPeerEntry *exclude = cls;
929 struct NSEPeerEntry *peer_entry = value;
930 struct GNUNET_TIME_Relative delay;
932 if (peer_entry->th != NULL)
933 return GNUNET_OK; /* already active */
934 if (peer_entry == exclude)
935 return GNUNET_OK; /* trigger of the update */
936 if (peer_entry->previous_round == GNUNET_NO)
938 /* still stuck in previous round, no point to update, check that
939 we are active here though... */
940 GNUNET_break ( (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
941 (peer_entry->th != NULL) );
944 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
946 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
947 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
949 delay = get_transmit_delay (0);
950 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
958 * Core handler for size estimate flooding messages.
960 * @param cls closure unused
961 * @param message message
962 * @param peer peer identity this message is from (ignored)
963 * @param atsi performance data (ignored)
967 handle_p2p_size_estimate(void *cls,
968 const struct GNUNET_PeerIdentity *peer,
969 const struct GNUNET_MessageHeader *message,
970 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
972 const struct GNUNET_NSE_FloodMessage *incoming_flood;
973 struct GNUNET_TIME_Absolute ts;
974 struct NSEPeerEntry *peer_entry;
975 uint32_t matching_bits;
980 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
982 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
983 GNUNET_STATISTICS_update (stats,
984 "# flood messages received",
987 matching_bits = ntohl (incoming_flood->matching_bits);
992 struct GNUNET_PeerIdentity os;
994 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
995 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
997 GNUNET_snprintf (origin, sizeof (origin),
1000 GNUNET_snprintf (pred, sizeof (pred),
1003 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1004 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
1005 (unsigned long long) GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1008 GNUNET_i2s (&my_identity),
1009 (unsigned int) matching_bits);
1013 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1014 if (NULL == peer_entry)
1020 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1022 if (ts.abs_value == current_timestamp.abs_value)
1023 idx = estimate_index;
1024 else if (ts.abs_value == current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1025 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1026 else if (ts.abs_value == next_timestamp.abs_value - gnunet_nse_interval.rel_value)
1028 if (matching_bits <= ntohl (next_message.matching_bits))
1029 return GNUNET_OK; /* ignore, simply too early/late */
1031 verify_message_crypto (incoming_flood))
1033 GNUNET_break_op (0);
1036 next_message = *incoming_flood;
1041 GNUNET_STATISTICS_update (stats,
1042 "# flood messages discarded (clock skew too large)",
1047 if (0 == (memcmp (peer, &my_identity, sizeof(struct GNUNET_PeerIdentity))))
1049 /* send to self, update our own estimate IF this also comes from us! */
1050 if (0 == memcmp (&incoming_flood->pkey,
1052 sizeof (my_public_key)))
1053 update_network_size_estimate ();
1056 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1058 /* cancel transmission from us to this peer for this round */
1059 if (idx == estimate_index)
1061 if (peer_entry->previous_round == GNUNET_YES)
1063 /* cancel any activity for current round */
1064 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1066 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1067 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1069 if (peer_entry->th != NULL)
1071 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1072 peer_entry->th = NULL;
1078 /* cancel previous round only */
1079 peer_entry->previous_round = GNUNET_YES;
1082 if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1084 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1086 if ( (idx < estimate_index) &&
1087 (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 = GNUNET_SCHEDULER_add_now (&transmit_task,
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)",
1105 verify_message_crypto (incoming_flood))
1107 GNUNET_break_op (0);
1110 size_estimate_messages[idx] = *incoming_flood;
1111 size_estimate_messages[idx].hop_count = htonl (ntohl (incoming_flood->hop_count) + 1);
1112 hop_count_max = GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
1115 /* have a new, better size estimate, inform clients */
1116 update_network_size_estimate ();
1119 GNUNET_CONTAINER_multihashmap_iterate (peers,
1120 &update_flood_times,
1128 * Method called whenever a peer connects.
1130 * @param cls closure
1131 * @param peer peer identity this notification is about
1132 * @param atsi performance data
1135 handle_core_connect(void *cls, const struct GNUNET_PeerIdentity *peer,
1136 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1138 struct NSEPeerEntry *peer_entry;
1141 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1142 "Peer `%s' connected to us\n",
1145 peer_entry = GNUNET_malloc(sizeof(struct NSEPeerEntry));
1146 peer_entry->id = *peer;
1147 GNUNET_CONTAINER_multihashmap_put (peers,
1150 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1151 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
1158 * Method called whenever a peer disconnects.
1160 * @param cls closure
1161 * @param peer peer identity this notification is about
1164 handle_core_disconnect(void *cls, const struct GNUNET_PeerIdentity *peer)
1166 struct NSEPeerEntry *pos;
1169 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1170 "Peer `%s' disconnected from us\n",
1173 pos = GNUNET_CONTAINER_multihashmap_get (peers,
1180 GNUNET_assert (GNUNET_YES ==
1181 GNUNET_CONTAINER_multihashmap_remove (peers,
1184 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1185 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1186 if (pos->th != NULL)
1188 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1196 * Task run during shutdown.
1202 shutdown_task(void *cls,
1203 const struct GNUNET_SCHEDULER_TaskContext *tc)
1205 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1207 GNUNET_SCHEDULER_cancel (flood_task);
1208 flood_task = GNUNET_SCHEDULER_NO_TASK;
1210 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1212 GNUNET_SCHEDULER_cancel (proof_task);
1213 proof_task = GNUNET_SCHEDULER_NO_TASK;
1214 write_proof (); /* remember progress */
1218 GNUNET_SERVER_notification_context_destroy (nc);
1221 if (coreAPI != NULL)
1223 GNUNET_CORE_disconnect (coreAPI);
1228 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1233 GNUNET_CONTAINER_multihashmap_destroy (peers);
1236 if (my_private_key != NULL)
1238 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1239 my_private_key = NULL;
1241 #if ENABLE_HISTOGRAM
1244 GNUNET_BIO_write_close (wh);
1252 * Called on core init/fail.
1254 * @param cls service closure
1255 * @param server handle to the server for this service
1256 * @param identity the public identity of this peer
1257 * @param publicKey the public key of this peer
1260 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1261 const struct GNUNET_PeerIdentity *identity,
1262 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1264 struct GNUNET_TIME_Absolute now;
1265 struct GNUNET_TIME_Absolute prev_time;
1271 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1272 "Connection to core FAILED!\n");
1274 GNUNET_SCHEDULER_shutdown ();
1277 GNUNET_assert (0 == memcmp (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity)));
1278 now = GNUNET_TIME_absolute_get ();
1279 current_timestamp.abs_value = (now.abs_value / gnunet_nse_interval.rel_value) * gnunet_nse_interval.rel_value;
1280 next_timestamp.abs_value = current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1282 for (i = 0; i < HISTORY_SIZE; i++)
1284 prev_time.abs_value = current_timestamp.abs_value - (HISTORY_SIZE - i - 1) * gnunet_nse_interval.rel_value;
1285 setup_flood_message (i, prev_time);
1287 estimate_index = HISTORY_SIZE - 1;
1290 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
1291 &update_flood_message, NULL);
1296 * Handle network size estimate clients.
1298 * @param cls closure
1299 * @param server the initialized server
1300 * @param c configuration to use
1303 run(void *cls, struct GNUNET_SERVER_Handle *server,
1304 const struct GNUNET_CONFIGURATION_Handle *c)
1309 static const struct GNUNET_SERVER_MessageHandler handlers[] =
1311 { &handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START, sizeof (struct GNUNET_MessageHeader) },
1312 { NULL, NULL, 0, 0 }
1314 static const struct GNUNET_CORE_MessageHandler core_handlers[] =
1316 { &handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, sizeof (struct GNUNET_NSE_FloodMessage) },
1322 GNUNET_CONFIGURATION_get_value_time (cfg,
1324 &gnunet_nse_interval)) ||
1326 GNUNET_CONFIGURATION_get_value_time (cfg,
1328 &proof_find_delay)) ||
1330 GNUNET_CONFIGURATION_get_value_number (cfg,
1332 &nse_work_required)) )
1334 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1335 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1336 GNUNET_SCHEDULER_shutdown ();
1339 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1341 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1342 _ ("Invalid work requirement for NSE service. Exiting.\n"));
1343 GNUNET_SCHEDULER_shutdown ();
1349 GNUNET_CONFIGURATION_get_value_filename (cfg,
1350 "GNUNETD", "HOSTKEY",
1353 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1354 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1355 GNUNET_SCHEDULER_shutdown ();
1358 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1359 GNUNET_free (keyfile);
1360 if (my_private_key == NULL)
1362 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1363 _("NSE service could not access hostkey. Exiting.\n"));
1364 GNUNET_SCHEDULER_shutdown ();
1367 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1368 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_identity.hashPubKey);
1370 GNUNET_CONFIGURATION_get_value_filename (cfg,
1374 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1375 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1376 if (my_private_key != NULL)
1378 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1379 my_private_key = NULL;
1381 GNUNET_SCHEDULER_shutdown ();
1384 if ( (GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1385 (sizeof (my_proof) !=
1386 GNUNET_DISK_fn_read (proof,
1388 sizeof (my_proof))) )
1390 GNUNET_free (proof);
1391 proof_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1395 peers = GNUNET_CONTAINER_multihashmap_create (128);
1396 GNUNET_SERVER_add_handlers (server, handlers);
1397 nc = GNUNET_SERVER_notification_context_create (server, 1);
1398 /* Connect to core service and register core handlers */
1399 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1400 CORE_QUEUE_SIZE, /* queue size */
1401 NULL, /* Closure passed to functions */
1402 &core_init, /* Call core_init once connected */
1403 &handle_core_connect, /* Handle connects */
1404 &handle_core_disconnect, /* Handle disconnects */
1405 NULL, /* Do we care about "status" updates? */
1406 NULL, /* Don't want notified about all incoming messages */
1407 GNUNET_NO, /* For header only inbound notification */
1408 NULL, /* Don't want notified about all outbound messages */
1409 GNUNET_NO, /* For header only outbound notification */
1410 core_handlers); /* Register these handlers */
1411 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1412 &shutdown_task, NULL);
1413 #if ENABLE_HISTOGRAM
1415 GNUNET_CONFIGURATION_get_value_filename (cfg,
1419 wh = GNUNET_BIO_write_open (proof);
1420 GNUNET_free (proof);
1423 if (coreAPI == NULL)
1425 GNUNET_SCHEDULER_shutdown ();
1428 stats = GNUNET_STATISTICS_create ("nse", cfg);
1433 * The main function for the statistics service.
1435 * @param argc number of arguments from the command line
1436 * @param argv command line arguments
1437 * @return 0 ok, 1 on error
1440 main(int argc, char * const *argv)
1442 return (GNUNET_OK == GNUNET_SERVICE_run (argc, argv,
1444 GNUNET_SERVICE_OPTION_NONE, &run,
1448 /* end of gnunet-service-nse.c */