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)
310 /* Weighted incremental algorithm for stddev according to West (1979) */
322 for (i = 0; i < estimate_count; i++)
324 j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
325 val = htonl (size_estimate_messages[j].matching_bits);
326 weight = estimate_count + 1 - i;
328 temp = weight + sumweight;
330 r = q * weight / temp;
332 sum += sumweight * q * r;
335 if (estimate_count > 0)
336 variance = (sum / sumweight) * estimate_count / (estimate_count - 1.0);
338 /* trivial version for debugging */
341 /* non-weighted trivial version */
347 for (i = 0; i < estimate_count; i++)
349 j = (estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE;
350 val = htonl (size_estimate_messages[j].matching_bits);
354 if (0 != estimate_count)
356 mean = sum / estimate_count;
357 variance = (vsq - mean * sum) / (estimate_count - 1.0); // terrible for numerical stability...
361 std_dev = sqrt (variance);
363 std_dev = variance; /* must be infinity due to estimate_count == 0 */
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;
442 if (matching_bits == 0)
443 return GNUNET_TIME_UNIT_ZERO;
444 d = get_matching_bits_delay (matching_bits - 1);
445 i = (uint32_t) (d / (double) (hop_count_max + 1));
446 ret.rel_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, i + 1);
449 return GNUNET_TIME_UNIT_ZERO;
455 * Get the number of matching bits that the given timestamp has to the given peer ID.
457 * @param timestamp time to generate key
458 * @param id peer identity to compare with
459 * @return number of matching bits
462 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
463 const struct GNUNET_PeerIdentity *id)
465 GNUNET_HashCode timestamp_hash;
467 GNUNET_CRYPTO_hash (×tamp.abs_value, sizeof (timestamp.abs_value),
469 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash, &id->hashPubKey);
474 * Get the transmission delay that should be applied for a
477 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
478 * 0 for the current round (based on our proximity to time key)
479 * @return delay that should be applied
481 static struct GNUNET_TIME_Relative
482 get_transmit_delay (int round_offset)
484 struct GNUNET_TIME_Relative ret;
485 struct GNUNET_TIME_Absolute tgt;
487 uint32_t matching_bits;
489 switch (round_offset)
492 /* previous round is randomized between 0 and 50 ms */
493 #if USE_RANDOM_DELAYS
494 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK, 50);
496 ret = GNUNET_TIME_UNIT_ZERO;
499 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
500 "Transmitting previous round behind schedule in %llu ms\n",
501 (unsigned long long) ret.rel_value);
505 /* current round is based on best-known matching_bits */
507 ntohl (size_estimate_messages[estimate_index].matching_bits);
508 dist_delay = get_matching_bits_delay (matching_bits);
509 dist_delay += get_delay_randomization (matching_bits).rel_value;
510 ret.rel_value = (uint64_t) dist_delay;
512 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
513 "For round %llu, delay for %u matching bits is %llu ms\n",
514 (unsigned long long) current_timestamp.abs_value,
515 (unsigned int) matching_bits,
516 (unsigned long long) ret.rel_value);
518 /* now consider round start time and add delay to it */
519 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
520 return GNUNET_TIME_absolute_get_remaining (tgt);
523 return GNUNET_TIME_UNIT_FOREVER_REL;
528 * Task that triggers a NSE P2P transmission.
530 * @param cls the 'struct NSEPeerEntry'
531 * @param tc scheduler context
534 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
538 * Called when core is ready to send a message we asked for
539 * out to the destination.
541 * @param cls closure (NULL)
542 * @param size number of bytes available in buf
543 * @param buf where the callee should write the message
544 * @return number of bytes written to buf
547 transmit_ready (void *cls, size_t size, void *buf)
549 struct NSEPeerEntry *peer_entry = cls;
552 peer_entry->th = NULL;
555 /* client disconnected */
558 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
559 idx = estimate_index;
560 if (peer_entry->previous_round == GNUNET_NO)
562 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
563 peer_entry->previous_round = GNUNET_YES;
564 peer_entry->transmit_task =
565 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0), &transmit_task,
568 if ((ntohl (size_estimate_messages[idx].hop_count) == 0) &&
569 (GNUNET_SCHEDULER_NO_TASK != proof_task))
571 GNUNET_STATISTICS_update (stats,
572 "# flood messages not generated (no proof yet)",
576 if (ntohs (size_estimate_messages[idx].header.size) == 0)
578 GNUNET_STATISTICS_update (stats,
579 "# flood messages not generated (lack of history)",
584 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
585 "In round %llu, sending to `%s' estimate with %u bits\n",
587 GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].
588 timestamp).abs_value,
589 GNUNET_i2s (&peer_entry->id),
590 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
592 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
593 GNUNET_STATISTICS_update (stats, "# flood messages started", 1, GNUNET_NO);
594 GNUNET_STATISTICS_update (stats, "# flood messages transmitted", 1,
596 memcpy (buf, &size_estimate_messages[idx],
597 sizeof (struct GNUNET_NSE_FloodMessage));
598 GNUNET_STATISTICS_update (stats, "# flood messages sent", 1, GNUNET_NO);
599 return sizeof (struct GNUNET_NSE_FloodMessage);
604 * Task that triggers a NSE P2P transmission.
606 * @param cls the 'struct NSEPeerEntry'
607 * @param tc scheduler context
610 transmit_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
612 struct NSEPeerEntry *peer_entry = cls;
614 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
615 GNUNET_assert (NULL == peer_entry->th);
617 GNUNET_CORE_notify_transmit_ready (coreAPI, GNUNET_NO, NSE_PRIORITY,
618 GNUNET_TIME_UNIT_FOREVER_REL,
621 GNUNET_NSE_FloodMessage),
622 &transmit_ready, peer_entry);
627 * We've sent on our flood message or one that we received which was
628 * validated and closer than ours. Update the global list of recent
629 * messages and the average. Also re-broadcast the message to any
633 update_network_size_estimate ()
635 struct GNUNET_NSE_ClientMessage em;
637 setup_estimate_message (&em);
638 GNUNET_SERVER_notification_context_broadcast (nc, &em.header, GNUNET_YES);
643 * Setup a flood message in our history array at the given
644 * slot offset for the given timestamp.
646 * @param slot index to use
647 * @param ts timestamp to use
650 setup_flood_message (unsigned int slot, struct GNUNET_TIME_Absolute ts)
652 struct GNUNET_NSE_FloodMessage *fm;
653 uint32_t matching_bits;
655 matching_bits = get_matching_bits (ts, &my_identity);
656 fm = &size_estimate_messages[slot];
657 fm->header.size = htons (sizeof (struct GNUNET_NSE_FloodMessage));
658 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
659 fm->hop_count = htonl (0);
660 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
662 htonl (sizeof (struct GNUNET_NSE_FloodMessage) -
663 sizeof (struct GNUNET_MessageHeader) - sizeof (uint32_t) -
664 sizeof (struct GNUNET_CRYPTO_RsaSignature));
665 fm->matching_bits = htonl (matching_bits);
666 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
667 fm->pkey = my_public_key;
668 fm->proof_of_work = my_proof;
669 if (nse_work_required > 0)
670 GNUNET_assert (GNUNET_OK ==
671 GNUNET_CRYPTO_rsa_sign (my_private_key, &fm->purpose,
674 memset (&fm->signature, 0, sizeof (fm->signature));
679 * Schedule transmission for the given peer for the current round based
680 * on what we know about the desired delay.
683 * @param key hash of peer identity
684 * @param value the 'struct NSEPeerEntry'
685 * @return GNUNET_OK (continue to iterate)
688 schedule_current_round (void *cls, const GNUNET_HashCode * key, void *value)
690 struct NSEPeerEntry *peer_entry = value;
691 struct GNUNET_TIME_Relative delay;
693 if (peer_entry->th != NULL)
695 peer_entry->previous_round = GNUNET_NO;
698 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
700 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
701 peer_entry->previous_round = GNUNET_NO;
704 get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
705 peer_entry->transmit_task =
706 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
712 * Update our flood message to be sent (and our timestamps).
715 * @param tc context for this message
718 update_flood_message (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
720 struct GNUNET_TIME_Relative offset;
723 flood_task = GNUNET_SCHEDULER_NO_TASK;
724 if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
726 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
727 if (0 != offset.rel_value)
729 /* somehow run early, delay more */
731 GNUNET_SCHEDULER_add_delayed (offset, &update_flood_message, NULL);
734 current_timestamp = next_timestamp;
736 GNUNET_TIME_absolute_add (current_timestamp, gnunet_nse_interval);
737 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
738 if (estimate_count < HISTORY_SIZE)
740 if (next_timestamp.abs_value ==
741 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
743 /* we received a message for this round way early, use it! */
744 size_estimate_messages[estimate_index] = next_message;
745 size_estimate_messages[estimate_index].hop_count =
746 htonl (1 + ntohl (next_message.hop_count));
749 setup_flood_message (estimate_index, current_timestamp);
750 next_message.matching_bits = htonl (0); /* reset for 'next' round */
752 for (i = 0; i < HISTORY_SIZE; i++)
754 GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count), hop_count_max);
755 GNUNET_CONTAINER_multihashmap_iterate (peers, &schedule_current_round, NULL);
757 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
758 (next_timestamp), &update_flood_message,
764 * Count the leading zeroes in hash.
767 * @return the number of leading zero bits.
770 count_leading_zeroes (const GNUNET_HashCode * hash)
772 unsigned int hash_count;
775 while ((0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)))
782 * Check whether the given public key
783 * and integer are a valid proof of work.
785 * @param pkey the public key
786 * @param val the integer
788 * @return GNUNET_YES if valid, GNUNET_NO if not
791 check_proof_of_work (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
794 char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
796 GNUNET_HashCode result;
798 memcpy (buf, &val, sizeof (val));
799 memcpy (&buf[sizeof (val)], pkey,
800 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
801 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
802 return (count_leading_zeroes (&result) >=
803 nse_work_required) ? GNUNET_YES : GNUNET_NO;
808 * Write our current proof to disk.
816 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
818 if (sizeof (my_proof) !=
819 GNUNET_DISK_fn_write (proof, &my_proof, sizeof (my_proof),
820 GNUNET_DISK_PERM_USER_READ |
821 GNUNET_DISK_PERM_USER_WRITE))
822 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", proof);
829 * Find our proof of work.
831 * @param cls closure (unused)
832 * @param tc task context
835 find_proof (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
837 #define ROUND_SIZE 10
839 char buf[sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) +
841 GNUNET_HashCode result;
844 proof_task = GNUNET_SCHEDULER_NO_TASK;
845 memcpy (&buf[sizeof (uint64_t)], &my_public_key,
846 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
849 while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
851 memcpy (buf, &counter, sizeof (uint64_t));
852 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
853 if (nse_work_required <= count_leading_zeroes (&result))
857 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Proof of work found: %llu!\n",
858 (unsigned long long) GNUNET_ntohll (counter));
861 setup_flood_message (estimate_index, current_timestamp);
867 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Testing proofs currently at %llu\n",
871 (unsigned long long) counter);
873 /* remember progress every 100 rounds */
882 GNUNET_SCHEDULER_add_delayed (proof_find_delay, &find_proof, NULL);
887 * An incoming flood message has been received which claims
888 * to have more bits matching than any we know in this time
889 * period. Verify the signature and/or proof of work.
891 * @param incoming_flood the message to verify
893 * @return GNUNET_YES if the message is verified
894 * GNUNET_NO if the key/signature don't verify
897 verify_message_crypto (const struct GNUNET_NSE_FloodMessage *incoming_flood)
900 check_proof_of_work (&incoming_flood->pkey,
901 incoming_flood->proof_of_work))
903 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Proof of work invalid: %llu!\n"),
905 GNUNET_ntohll (incoming_flood->proof_of_work));
909 if ((nse_work_required > 0) &&
911 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
912 &incoming_flood->purpose,
913 &incoming_flood->signature,
914 &incoming_flood->pkey)))
924 * Update transmissions for the given peer for the current round based
925 * on updated proximity information.
927 * @param cls peer entry to exclude from updates
928 * @param key hash of peer identity
929 * @param value the 'struct NSEPeerEntry'
930 * @return GNUNET_OK (continue to iterate)
933 update_flood_times (void *cls, const GNUNET_HashCode * key, void *value)
935 struct NSEPeerEntry *exclude = cls;
936 struct NSEPeerEntry *peer_entry = value;
937 struct GNUNET_TIME_Relative delay;
939 if (peer_entry->th != NULL)
940 return GNUNET_OK; /* already active */
941 if (peer_entry == exclude)
942 return GNUNET_OK; /* trigger of the update */
943 if (peer_entry->previous_round == GNUNET_NO)
945 /* still stuck in previous round, no point to update, check that
946 * we are active here though... */
947 GNUNET_break ((peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK) ||
948 (peer_entry->th != NULL));
951 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
953 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
954 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
956 delay = get_transmit_delay (0);
957 peer_entry->transmit_task =
958 GNUNET_SCHEDULER_add_delayed (delay, &transmit_task, peer_entry);
964 * Core handler for size estimate flooding messages.
966 * @param cls closure unused
967 * @param message message
968 * @param peer peer identity this message is from (ignored)
969 * @param atsi performance data (ignored)
970 * @param atsi_count number of records in 'atsi'
973 handle_p2p_size_estimate (void *cls, const struct GNUNET_PeerIdentity *peer,
974 const struct GNUNET_MessageHeader *message,
975 const struct GNUNET_ATS_Information *atsi,
976 unsigned int atsi_count)
978 const struct GNUNET_NSE_FloodMessage *incoming_flood;
979 struct GNUNET_TIME_Absolute ts;
980 struct NSEPeerEntry *peer_entry;
981 uint32_t matching_bits;
986 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
988 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
989 GNUNET_STATISTICS_update (stats, "# flood messages received", 1, GNUNET_NO);
990 matching_bits = ntohl (incoming_flood->matching_bits);
995 struct GNUNET_PeerIdentity os;
997 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
998 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
1000 GNUNET_snprintf (origin, sizeof (origin), "%s", GNUNET_i2s (&os));
1001 GNUNET_snprintf (pred, sizeof (pred), "%s", GNUNET_i2s (peer));
1002 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1003 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
1004 (unsigned long long)
1005 GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
1006 origin, pred, GNUNET_i2s (&my_identity),
1007 (unsigned int) matching_bits);
1011 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1012 if (NULL == peer_entry)
1018 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
1020 if (ts.abs_value == current_timestamp.abs_value)
1021 idx = estimate_index;
1022 else if (ts.abs_value ==
1023 current_timestamp.abs_value - gnunet_nse_interval.rel_value)
1024 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1025 else if (ts.abs_value ==
1026 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 */
1030 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1032 GNUNET_break_op (0);
1035 next_message = *incoming_flood;
1040 GNUNET_STATISTICS_update (stats,
1041 "# flood messages discarded (clock skew too large)",
1045 if (0 == (memcmp (peer, &my_identity, sizeof (struct GNUNET_PeerIdentity))))
1047 /* send to self, update our own estimate IF this also comes from us! */
1049 memcmp (&incoming_flood->pkey, &my_public_key, sizeof (my_public_key)))
1050 update_network_size_estimate ();
1053 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1055 /* cancel transmission from us to this peer for this round */
1056 if (idx == estimate_index)
1058 if (peer_entry->previous_round == GNUNET_YES)
1060 /* cancel any activity for current round */
1061 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1063 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1064 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1066 if (peer_entry->th != NULL)
1068 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1069 peer_entry->th = NULL;
1075 /* cancel previous round only */
1076 peer_entry->previous_round = GNUNET_YES;
1079 if (matching_bits == ntohl (size_estimate_messages[idx].matching_bits))
1081 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1083 if ((idx < estimate_index) && (peer_entry->previous_round == GNUNET_YES))
1084 peer_entry->previous_round = GNUNET_NO;
1085 /* push back our result now, that peer is spreading bad information... */
1086 if (NULL == peer_entry->th)
1088 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1089 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1090 peer_entry->transmit_task =
1091 GNUNET_SCHEDULER_add_now (&transmit_task, peer_entry);
1093 /* Not closer than our most recent message, no need to do work here */
1094 GNUNET_STATISTICS_update (stats,
1095 "# flood messages ignored (had closer already)",
1099 if (GNUNET_YES != verify_message_crypto (incoming_flood))
1101 GNUNET_break_op (0);
1104 size_estimate_messages[idx] = *incoming_flood;
1105 size_estimate_messages[idx].hop_count =
1106 htonl (ntohl (incoming_flood->hop_count) + 1);
1108 GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1, hop_count_max);
1110 /* have a new, better size estimate, inform clients */
1111 update_network_size_estimate ();
1114 GNUNET_CONTAINER_multihashmap_iterate (peers, &update_flood_times,
1122 * Method called whenever a peer connects.
1124 * @param cls closure
1125 * @param peer peer identity this notification is about
1126 * @param atsi performance data
1127 * @param atsi_count number of records in 'atsi'
1130 handle_core_connect (void *cls, const struct GNUNET_PeerIdentity *peer,
1131 const struct GNUNET_ATS_Information *atsi,
1132 unsigned int atsi_count)
1134 struct NSEPeerEntry *peer_entry;
1137 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' connected to us\n",
1140 peer_entry = GNUNET_malloc (sizeof (struct NSEPeerEntry));
1141 peer_entry->id = *peer;
1142 GNUNET_assert (GNUNET_OK ==
1143 GNUNET_CONTAINER_multihashmap_put (peers, &peer->hashPubKey,
1145 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1146 peer_entry->transmit_task =
1147 GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1), &transmit_task,
1153 * Method called whenever a peer disconnects.
1155 * @param cls closure
1156 * @param peer peer identity this notification is about
1159 handle_core_disconnect (void *cls, const struct GNUNET_PeerIdentity *peer)
1161 struct NSEPeerEntry *pos;
1164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Peer `%s' disconnected from us\n",
1167 pos = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
1173 GNUNET_assert (GNUNET_YES ==
1174 GNUNET_CONTAINER_multihashmap_remove (peers, &peer->hashPubKey,
1176 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1177 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1178 if (pos->th != NULL)
1180 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1188 * Task run during shutdown.
1194 shutdown_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1196 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1198 GNUNET_SCHEDULER_cancel (flood_task);
1199 flood_task = GNUNET_SCHEDULER_NO_TASK;
1201 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1203 GNUNET_SCHEDULER_cancel (proof_task);
1204 proof_task = GNUNET_SCHEDULER_NO_TASK;
1205 write_proof (); /* remember progress */
1209 GNUNET_SERVER_notification_context_destroy (nc);
1212 if (coreAPI != NULL)
1214 GNUNET_CORE_disconnect (coreAPI);
1219 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1224 GNUNET_CONTAINER_multihashmap_destroy (peers);
1227 if (my_private_key != NULL)
1229 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1230 my_private_key = NULL;
1232 #if ENABLE_HISTOGRAM
1235 GNUNET_BIO_write_close (wh);
1243 * Called on core init/fail.
1245 * @param cls service closure
1246 * @param server handle to the server for this service
1247 * @param identity the public identity of this peer
1250 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1251 const struct GNUNET_PeerIdentity *identity)
1253 struct GNUNET_TIME_Absolute now;
1254 struct GNUNET_TIME_Absolute prev_time;
1259 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Connection to core FAILED!\n");
1261 GNUNET_SCHEDULER_shutdown ();
1265 memcmp (&my_identity, identity,
1266 sizeof (struct GNUNET_PeerIdentity)));
1267 now = GNUNET_TIME_absolute_get ();
1268 current_timestamp.abs_value =
1269 (now.abs_value / gnunet_nse_interval.rel_value) *
1270 gnunet_nse_interval.rel_value;
1271 next_timestamp.abs_value =
1272 current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1273 estimate_index = HISTORY_SIZE - 1;
1275 if (GNUNET_YES == check_proof_of_work (&my_public_key, my_proof))
1277 prev_time.abs_value =
1278 current_timestamp.abs_value - (estimate_index -
1279 1) * gnunet_nse_interval.rel_value;
1280 setup_flood_message (estimate_index, prev_time);
1284 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining
1285 (next_timestamp), &update_flood_message,
1291 * Handle network size estimate clients.
1293 * @param cls closure
1294 * @param server the initialized server
1295 * @param c configuration to use
1298 run (void *cls, struct GNUNET_SERVER_Handle *server,
1299 const struct GNUNET_CONFIGURATION_Handle *c)
1304 static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1305 {&handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START,
1306 sizeof (struct GNUNET_MessageHeader)},
1309 static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
1310 {&handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD,
1311 sizeof (struct GNUNET_NSE_FloodMessage)},
1317 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "INTERVAL",
1318 &gnunet_nse_interval)) ||
1320 GNUNET_CONFIGURATION_get_value_time (cfg, "NSE", "WORKDELAY",
1321 &proof_find_delay)) ||
1323 GNUNET_CONFIGURATION_get_value_number (cfg, "NSE", "WORKBITS",
1324 &nse_work_required)))
1326 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1328 ("NSE service is lacking key configuration settings. Exiting.\n"));
1329 GNUNET_SCHEDULER_shutdown ();
1332 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1334 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1335 _("Invalid work requirement for NSE service. Exiting.\n"));
1336 GNUNET_SCHEDULER_shutdown ();
1342 GNUNET_CONFIGURATION_get_value_filename (cfg, "GNUNETD", "HOSTKEY",
1345 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1347 ("NSE service is lacking key configuration settings. Exiting.\n"));
1348 GNUNET_SCHEDULER_shutdown ();
1351 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1352 GNUNET_free (keyfile);
1353 if (my_private_key == NULL)
1355 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1356 _("NSE service could not access hostkey. Exiting.\n"));
1357 GNUNET_SCHEDULER_shutdown ();
1360 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1361 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key),
1362 &my_identity.hashPubKey);
1364 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "PROOFFILE", &proof))
1366 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1368 ("NSE service is lacking key configuration settings. Exiting.\n"));
1369 if (my_private_key != NULL)
1371 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1372 my_private_key = NULL;
1374 GNUNET_SCHEDULER_shutdown ();
1377 if ((GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1378 (sizeof (my_proof) !=
1379 GNUNET_DISK_fn_read (proof, &my_proof, sizeof (my_proof))))
1381 GNUNET_free (proof);
1383 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1386 peers = GNUNET_CONTAINER_multihashmap_create (128);
1387 GNUNET_SERVER_add_handlers (server, handlers);
1388 nc = GNUNET_SERVER_notification_context_create (server, 1);
1389 /* Connect to core service and register core handlers */
1390 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1391 1, NULL, /* Closure passed to functions */
1392 &core_init, /* Call core_init once connected */
1393 &handle_core_connect, /* Handle connects */
1394 &handle_core_disconnect, /* Handle disconnects */
1395 NULL, /* Don't want notified about all incoming messages */
1396 GNUNET_NO, /* For header only inbound notification */
1397 NULL, /* Don't want notified about all outbound messages */
1398 GNUNET_NO, /* For header only outbound notification */
1399 core_handlers); /* Register these handlers */
1400 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task,
1402 #if ENABLE_HISTOGRAM
1404 GNUNET_CONFIGURATION_get_value_filename (cfg, "NSE", "HISTOGRAM", &proof))
1406 wh = GNUNET_BIO_write_open (proof);
1407 GNUNET_free (proof);
1410 if (coreAPI == NULL)
1412 GNUNET_SCHEDULER_shutdown ();
1415 stats = GNUNET_STATISTICS_create ("nse", cfg);
1420 * The main function for the statistics service.
1422 * @param argc number of arguments from the command line
1423 * @param argv command line arguments
1424 * @return 0 ok, 1 on error
1427 main (int argc, char *const *argv)
1429 return (GNUNET_OK ==
1430 GNUNET_SERVICE_run (argc, argv, "nse", GNUNET_SERVICE_OPTION_NONE,
1431 &run, NULL)) ? 0 : 1;
1434 /* end of gnunet-service-nse.c */