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 we generate a histogram with the time stamps of when we received
50 * NSE messages to disk? (for performance evaluation only, not useful in
53 #define ENABLE_HISTOGRAM GNUNET_YES
56 * Over how many values do we calculate the weighted average?
58 #define HISTORY_SIZE 8
61 * Size of the queue to core.
63 #define CORE_QUEUE_SIZE 2
66 * Message priority to use.
68 #define NSE_PRIORITY 5
71 * Amount of work required (W-bit collisions) for NSE proofs, in collision-bits.
73 static unsigned long long nse_work_required;
76 * Interval for sending network size estimation flood requests.
78 static struct GNUNET_TIME_Relative gnunet_nse_interval;
81 * Interval between proof find runs.
83 static struct GNUNET_TIME_Relative proof_find_delay;
87 static struct GNUNET_BIO_WriteHandle *wh;
92 * Per-peer information.
98 * Pending message for this peer.
100 struct GNUNET_MessageHeader *pending_message;
103 * Core handle for sending messages to this peer.
105 struct GNUNET_CORE_TransmitHandle *th;
108 * What is the identity of the peer?
110 struct GNUNET_PeerIdentity id;
113 * Task scheduled to send message to this peer.
115 GNUNET_SCHEDULER_TaskIdentifier transmit_task;
118 * Did we receive or send a message about the previous round
119 * to this peer yet? GNUNET_YES if the previous round has
120 * been taken care of.
127 * Network size estimate reply; sent when "this"
128 * peer's timer has run out before receiving a
129 * valid reply from another peer.
131 struct GNUNET_NSE_FloodMessage
134 * Type: GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD
136 struct GNUNET_MessageHeader header;
139 * Number of hops this message has taken so far.
146 struct GNUNET_CRYPTO_RsaSignaturePurpose purpose;
149 * The current timestamp value (which all
150 * peers should agree on).
152 struct GNUNET_TIME_AbsoluteNBO timestamp;
155 * Number of matching bits between the hash
156 * of timestamp and the initiator's public
159 uint32_t matching_bits;
162 * Public key of the originator.
164 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded pkey;
167 * Proof of work, causing leading zeros when hashed with pkey.
169 uint64_t proof_of_work;
172 * Signature (over range specified in purpose).
174 struct GNUNET_CRYPTO_RsaSignature signature;
179 * Handle to our current configuration.
181 static const struct GNUNET_CONFIGURATION_Handle *cfg;
184 * Handle to the statistics service.
186 static struct GNUNET_STATISTICS_Handle *stats;
189 * Handle to the core service.
191 static struct GNUNET_CORE_Handle *coreAPI;
194 * Map of all connected peers.
196 static struct GNUNET_CONTAINER_MultiHashMap *peers;
199 * The current network size estimate. Number of bits matching on
202 static double current_size_estimate;
205 * The standard deviation of the last HISTORY_SIZE network
208 static double current_std_dev = NAN;
211 * Current hop counter estimate (estimate for network diameter).
213 static uint32_t hop_count_max;
216 * Message for the next round, if we got any.
218 static struct GNUNET_NSE_FloodMessage next_message;
221 * Array of recent size estimate messages.
223 static struct GNUNET_NSE_FloodMessage size_estimate_messages[HISTORY_SIZE];
226 * Index of most recent estimate.
228 static unsigned int estimate_index;
231 * Number of valid entries in the history.
233 static unsigned int estimate_count;
236 * Task scheduled to update our flood message for the next round.
238 static GNUNET_SCHEDULER_TaskIdentifier flood_task;
241 * Task scheduled to compute our proof.
243 static GNUNET_SCHEDULER_TaskIdentifier proof_task;
246 * Notification context, simplifies client broadcasts.
248 static struct GNUNET_SERVER_NotificationContext *nc;
251 * The next major time.
253 static struct GNUNET_TIME_Absolute next_timestamp;
256 * The current major time.
258 static struct GNUNET_TIME_Absolute current_timestamp;
261 * The public key of this peer.
263 static struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded my_public_key;
266 * The private key of this peer.
268 static struct GNUNET_CRYPTO_RsaPrivateKey *my_private_key;
271 * The peer identity of this peer.
273 static struct GNUNET_PeerIdentity my_identity;
276 * Proof of work for this peer.
278 static uint64_t my_proof;
282 * Initialize a message to clients with the current network
285 * @param em message to fill in
288 setup_estimate_message (struct GNUNET_NSE_ClientMessage *em)
302 /* Weighted incremental algorithm for stddev according to West (1979) */
306 for (i=0;i<estimate_count; i++)
308 val = htonl (size_estimate_messages[(estimate_index - i + HISTORY_SIZE) % HISTORY_SIZE].matching_bits);
309 weight = estimate_count + 1 - i;
311 temp = weight + sumweight;
313 r = q * weight / temp;
314 sum += sumweight * q * r;
318 variance = sum / (sumweight - 1.0);
319 GNUNET_assert (variance >= 0);
320 std_dev = sqrt (variance);
321 current_std_dev = std_dev;
322 current_size_estimate = mean;
325 = htons (sizeof(struct GNUNET_NSE_ClientMessage));
327 = htons (GNUNET_MESSAGE_TYPE_NSE_ESTIMATE);
328 em->reserved = htonl (0);
329 em->size_estimate = mean - 0.5;
330 em->std_deviation = std_dev;
331 GNUNET_STATISTICS_set (stats,
332 "# nodes in the network (estimate)",
333 (uint64_t) pow (2, mean - 0.5), GNUNET_NO);
338 * Handler for START message from client, triggers an
339 * immediate current network estimate notification.
340 * Also, we remember the client for updates upon future
341 * estimate measurements.
344 * @param client who sent the message
345 * @param message the message received
348 handle_start_message(void *cls, struct GNUNET_SERVER_Client *client,
349 const struct GNUNET_MessageHeader *message)
351 struct GNUNET_NSE_ClientMessage em;
354 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
355 "Received START message from client\n");
357 GNUNET_SERVER_notification_context_add (nc, client);
358 setup_estimate_message (&em);
359 GNUNET_SERVER_notification_context_unicast (nc, client, &em.header, GNUNET_YES);
360 GNUNET_SERVER_receive_done (client, GNUNET_OK);
365 * How long should we delay a message to go the given number of
368 * @param matching_bits number of matching bits to consider
371 get_matching_bits_delay (uint32_t matching_bits)
373 /* Calculated as: S + f/2 - (f / pi) * (atan(x - p'))*/
374 // S is next_timestamp (ignored in return value)
375 // f is frequency (gnunet_nse_interval)
376 // x is matching_bits
377 // p' is current_size_estimate
378 return ((double) gnunet_nse_interval.rel_value / (double) 2.0)
379 - ((gnunet_nse_interval.rel_value / M_PI) * atan (matching_bits - current_size_estimate));
384 * What delay randomization should we apply for a given number of matching bits?
386 * @param matching_bits number of matching bits
387 * @return random delay to apply
389 static struct GNUNET_TIME_Relative
390 get_delay_randomization (uint32_t matching_bits)
392 struct GNUNET_TIME_Relative ret;
394 if (matching_bits == 0)
395 return GNUNET_TIME_UNIT_ZERO;
396 ret.rel_value = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
397 (uint32_t) (get_matching_bits_delay (matching_bits - 1) / (double) (hop_count_max + 1)));
403 * Get the number of matching bits that the given timestamp has to the given peer ID.
405 * @param timestamp time to generate key
406 * @param id peer identity to compare with
407 * @return number of matching bits
410 get_matching_bits (struct GNUNET_TIME_Absolute timestamp,
411 const struct GNUNET_PeerIdentity *id)
413 GNUNET_HashCode timestamp_hash;
415 GNUNET_CRYPTO_hash (×tamp.abs_value,
416 sizeof(timestamp.abs_value),
418 return GNUNET_CRYPTO_hash_matching_bits (×tamp_hash,
424 * Get the transmission delay that should be applied for a
427 * @param round_offset -1 for the previous round (random delay between 0 and 50ms)
428 * 0 for the current round (based on our proximity to time key)
429 * @return delay that should be applied
431 static struct GNUNET_TIME_Relative
432 get_transmit_delay (int round_offset)
434 struct GNUNET_TIME_Relative ret;
435 struct GNUNET_TIME_Absolute tgt;
437 uint32_t matching_bits;
439 switch (round_offset)
442 /* previous round is randomized between 0 and 50 ms */
443 ret.rel_value = GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
446 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
447 "Transmitting previous round behind schedule in %llu ms\n",
448 (unsigned long long) ret.rel_value);
452 /* current round is based on best-known matching_bits */
453 matching_bits = ntohl (size_estimate_messages[estimate_index].matching_bits);
454 dist_delay = get_matching_bits_delay (matching_bits);
455 dist_delay += get_delay_randomization (matching_bits).rel_value;
456 ret.rel_value = (uint64_t) dist_delay;
458 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
459 "For round %llu, delay for %u matching bits is %llu ms\n",
460 (unsigned long long) current_timestamp.abs_value,
461 (unsigned int) matching_bits,
462 (unsigned long long) ret.rel_value);
464 /* now consider round start time and add delay to it */
465 tgt = GNUNET_TIME_absolute_add (current_timestamp, ret);
466 return GNUNET_TIME_absolute_get_remaining (tgt);
469 return GNUNET_TIME_UNIT_FOREVER_REL;
474 * Task that triggers a NSE P2P transmission.
476 * @param cls the 'struct NSEPeerEntry'
477 * @param tc scheduler context
480 transmit_task (void *cls,
481 const struct GNUNET_SCHEDULER_TaskContext *tc);
485 * Called when core is ready to send a message we asked for
486 * out to the destination.
488 * @param cls closure (NULL)
489 * @param size number of bytes available in buf
490 * @param buf where the callee should write the message
491 * @return number of bytes written to buf
494 transmit_ready (void *cls, size_t size, void *buf)
496 struct NSEPeerEntry *peer_entry = cls;
499 peer_entry->th = NULL;
502 /* client disconnected */
505 GNUNET_assert (size >= sizeof (struct GNUNET_NSE_FloodMessage));
506 idx = estimate_index;
507 if (peer_entry->previous_round == GNUNET_NO)
509 idx = (idx + HISTORY_SIZE - 1) % HISTORY_SIZE;
510 peer_entry->previous_round = GNUNET_YES;
511 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (0),
515 if ( (ntohl (size_estimate_messages[idx].hop_count) == 0) &&
516 (GNUNET_SCHEDULER_NO_TASK != proof_task) )
518 GNUNET_STATISTICS_update (stats,
519 "# flood messages not generated (no proof yet)",
525 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
526 "In round %llu, sending to `%s' estimate with %u bits\n",
527 (unsigned long long) GNUNET_TIME_absolute_ntoh (size_estimate_messages[idx].timestamp).abs_value,
528 GNUNET_i2s (&peer_entry->id),
529 (unsigned int) ntohl (size_estimate_messages[idx].matching_bits));
531 if (ntohl (size_estimate_messages[idx].hop_count) == 0)
532 GNUNET_STATISTICS_update (stats,
533 "# flood messages started",
536 GNUNET_STATISTICS_update (stats,
537 "# flood messages transmitted",
541 &size_estimate_messages[idx],
542 sizeof (struct GNUNET_NSE_FloodMessage));
543 GNUNET_STATISTICS_update (stats,
544 "# flood messages sent",
547 return sizeof (struct GNUNET_NSE_FloodMessage);
552 * Task that triggers a NSE P2P transmission.
554 * @param cls the 'struct NSEPeerEntry'
555 * @param tc scheduler context
558 transmit_task (void *cls,
559 const struct GNUNET_SCHEDULER_TaskContext *tc)
561 struct NSEPeerEntry *peer_entry = cls;
563 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
565 = GNUNET_CORE_notify_transmit_ready (coreAPI,
568 GNUNET_TIME_UNIT_FOREVER_REL,
570 sizeof (struct GNUNET_NSE_FloodMessage),
571 &transmit_ready, peer_entry);
576 * We've sent on our flood message or one that we received which was
577 * validated and closer than ours. Update the global list of recent
578 * messages and the average. Also re-broadcast the message to any
582 update_network_size_estimate ()
584 struct GNUNET_NSE_ClientMessage em;
586 setup_estimate_message (&em);
587 GNUNET_SERVER_notification_context_broadcast (nc,
594 * Setup a flood message in our history array at the given
595 * slot offset for the given timestamp.
597 * @param slot index to use
598 * @param ts timestamp to use
601 setup_flood_message (unsigned int slot,
602 struct GNUNET_TIME_Absolute ts)
604 struct GNUNET_NSE_FloodMessage *fm;
605 uint32_t matching_bits;
607 matching_bits = get_matching_bits (ts, &my_identity);
608 fm = &size_estimate_messages[slot];
609 fm->header.size = htons (sizeof(struct GNUNET_NSE_FloodMessage));
610 fm->header.type = htons (GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD);
611 fm->hop_count = htonl (0);
612 fm->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_NSE_SEND);
613 fm->purpose.size = htonl (sizeof(struct GNUNET_NSE_FloodMessage)
614 - sizeof (struct GNUNET_MessageHeader)
616 - sizeof (struct GNUNET_CRYPTO_RsaSignature));
617 fm->matching_bits = htonl (matching_bits);
618 fm->timestamp = GNUNET_TIME_absolute_hton (ts);
619 fm->pkey = my_public_key;
620 fm->proof_of_work = my_proof;
621 GNUNET_CRYPTO_rsa_sign (my_private_key,
628 * Schedule transmission for the given peer for the current round based
629 * on what we know about the desired delay.
632 * @param key hash of peer identity
633 * @param value the 'struct NSEPeerEntry'
634 * @return GNUNET_OK (continue to iterate)
637 schedule_current_round (void *cls,
638 const GNUNET_HashCode *key,
641 struct NSEPeerEntry *peer_entry = value;
642 struct GNUNET_TIME_Relative delay;
644 if (peer_entry->th != NULL)
646 peer_entry->previous_round = GNUNET_NO;
649 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
651 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
652 peer_entry->previous_round = GNUNET_NO;
654 delay = get_transmit_delay ((peer_entry->previous_round == GNUNET_NO) ? -1 : 0);
655 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
663 * Update our flood message to be sent (and our timestamps).
666 * @param tc context for this message
669 update_flood_message(void *cls,
670 const struct GNUNET_SCHEDULER_TaskContext *tc)
672 struct GNUNET_TIME_Relative offset;
675 flood_task = GNUNET_SCHEDULER_NO_TASK;
676 offset = GNUNET_TIME_absolute_get_remaining (next_timestamp);
677 if (0 != offset.rel_value)
679 /* somehow run early, delay more */
681 = GNUNET_SCHEDULER_add_delayed (offset,
682 &update_flood_message,
686 current_timestamp = next_timestamp;
687 next_timestamp = GNUNET_TIME_absolute_add (current_timestamp,
688 gnunet_nse_interval);
689 estimate_index = (estimate_index + 1) % HISTORY_SIZE;
690 if (estimate_count < HISTORY_SIZE)
692 if (next_timestamp.abs_value ==
693 GNUNET_TIME_absolute_ntoh (next_message.timestamp).abs_value)
695 /* we received a message for this round way early, use it! */
696 size_estimate_messages[estimate_index] = next_message;
697 size_estimate_messages[estimate_index].hop_count
698 = htonl (1 + ntohl (next_message.hop_count));
701 setup_flood_message (estimate_index, current_timestamp);
702 next_message.matching_bits = htonl (0); /* reset for 'next' round */
704 for (i=0;i<HISTORY_SIZE;i++)
705 hop_count_max = GNUNET_MAX (ntohl (size_estimate_messages[i].hop_count),
707 GNUNET_CONTAINER_multihashmap_iterate (peers,
708 &schedule_current_round,
710 flood_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
711 &update_flood_message, NULL);
716 * Count the leading zeroes in hash.
719 * @return the number of leading zero bits.
722 count_leading_zeroes(const GNUNET_HashCode *hash)
724 unsigned int hash_count;
727 while ((0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count)))
734 * Check whether the given public key
735 * and integer are a valid proof of work.
737 * @param pkey the public key
738 * @param val the integer
740 * @return GNUNET_YES if valid, GNUNET_NO if not
743 check_proof_of_work(const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pkey,
746 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(val)];
747 GNUNET_HashCode result;
752 memcpy (&buf[sizeof(val)],
754 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
755 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
756 return (count_leading_zeroes (&result) >= nse_work_required) ? GNUNET_YES : GNUNET_NO;
761 * Write our current proof to disk.
769 GNUNET_CONFIGURATION_get_value_filename (cfg,
773 if (sizeof (my_proof) !=
774 GNUNET_DISK_fn_write (proof,
777 GNUNET_DISK_PERM_USER_READ | GNUNET_DISK_PERM_USER_WRITE))
778 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
787 * Find our proof of work.
789 * @param cls closure (unused)
790 * @param tc task context
793 find_proof (void *cls,
794 const struct GNUNET_SCHEDULER_TaskContext *tc)
796 #define ROUND_SIZE 10
798 char buf[sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded) + sizeof(uint64_t)];
799 GNUNET_HashCode result;
802 proof_task = GNUNET_SCHEDULER_NO_TASK;
803 memcpy (&buf[sizeof(uint64_t)],
805 sizeof(struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded));
808 while ( (counter != UINT64_MAX) && (i < ROUND_SIZE) )
813 GNUNET_CRYPTO_hash (buf, sizeof (buf), &result);
814 if (nse_work_required <= count_leading_zeroes(&result))
817 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
818 _("Proof of work found: %llu!\n"),
819 (unsigned long long) GNUNET_ntohll (counter));
820 for (i=0;i<HISTORY_SIZE;i++)
821 if (ntohl (size_estimate_messages[i].hop_count) == 0)
823 size_estimate_messages[i].proof_of_work = my_proof;
824 GNUNET_CRYPTO_rsa_sign (my_private_key,
825 &size_estimate_messages[i].purpose,
826 &size_estimate_messages[i].signature);
834 if (my_proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
837 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
838 "Testing proofs currently at %llu\n",
839 (unsigned long long) counter);
841 /* remember progress every 100 rounds */
849 proof_task = GNUNET_SCHEDULER_add_delayed (proof_find_delay,
856 * An incoming flood message has been received which claims
857 * to have more bits matching than any we know in this time
858 * period. Verify the signature and/or proof of work.
860 * @param incoming_flood the message to verify
862 * @return GNUNET_YES if the message is verified
863 * GNUNET_NO if the key/signature don't verify
866 verify_message_crypto(const struct GNUNET_NSE_FloodMessage *incoming_flood)
869 check_proof_of_work (&incoming_flood->pkey,
870 incoming_flood->proof_of_work))
872 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
873 _("Proof of work invalid: %llu!\n"),
874 (unsigned long long) GNUNET_ntohll (incoming_flood->proof_of_work));
879 GNUNET_CRYPTO_rsa_verify (GNUNET_SIGNATURE_PURPOSE_NSE_SEND,
880 &incoming_flood->purpose,
881 &incoming_flood->signature,
882 &incoming_flood->pkey))
892 * Update transmissions for the given peer for the current round based
893 * on updated proximity information.
895 * @param cls peer entry to exclude from updates
896 * @param key hash of peer identity
897 * @param value the 'struct NSEPeerEntry'
898 * @return GNUNET_OK (continue to iterate)
901 update_flood_times (void *cls,
902 const GNUNET_HashCode *key,
905 struct NSEPeerEntry *exclude = cls;
906 struct NSEPeerEntry *peer_entry = value;
907 struct GNUNET_TIME_Relative delay;
909 if (peer_entry->th != NULL)
910 return GNUNET_OK; /* already active */
911 if (peer_entry == exclude)
912 return GNUNET_OK; /* trigger of the update */
913 if (peer_entry->previous_round == GNUNET_NO)
915 /* still stuck in previous round, no point to update, check that
916 we are active here though... */
917 GNUNET_break (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK);
920 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
922 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
923 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
925 delay = get_transmit_delay (0);
926 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (delay,
934 * Core handler for size estimate flooding messages.
936 * @param cls closure unused
937 * @param message message
938 * @param peer peer identity this message is from (ignored)
939 * @param atsi performance data (ignored)
943 handle_p2p_size_estimate(void *cls,
944 const struct GNUNET_PeerIdentity *peer,
945 const struct GNUNET_MessageHeader *message,
946 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
948 const struct GNUNET_NSE_FloodMessage *incoming_flood;
949 struct GNUNET_TIME_Absolute ts;
950 struct NSEPeerEntry *peer_entry;
951 uint32_t matching_bits;
956 GNUNET_BIO_write_int64 (wh, GNUNET_TIME_absolute_get ().abs_value);
958 incoming_flood = (const struct GNUNET_NSE_FloodMessage *) message;
959 GNUNET_STATISTICS_update (stats,
960 "# flood messages received",
963 matching_bits = ntohl (incoming_flood->matching_bits);
968 struct GNUNET_PeerIdentity os;
970 GNUNET_CRYPTO_hash (&incoming_flood->pkey,
971 sizeof (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded),
973 GNUNET_snprintf (origin, sizeof (origin),
976 GNUNET_snprintf (pred, sizeof (pred),
979 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
980 "Flood at %llu from `%s' via `%s' at `%s' with bits %u\n",
981 (unsigned long long) GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp).abs_value,
984 GNUNET_i2s (&my_identity),
985 (unsigned int) matching_bits);
989 peer_entry = GNUNET_CONTAINER_multihashmap_get (peers, &peer->hashPubKey);
990 if (NULL == peer_entry)
995 ts = GNUNET_TIME_absolute_ntoh (incoming_flood->timestamp);
996 if (ts.abs_value == current_timestamp.abs_value)
997 idx = estimate_index;
998 else if (ts.abs_value == current_timestamp.abs_value - gnunet_nse_interval.rel_value)
999 idx = (estimate_index + HISTORY_SIZE - 1) % HISTORY_SIZE;
1000 else if (ts.abs_value == 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 */
1005 verify_message_crypto (incoming_flood))
1007 GNUNET_break_op (0);
1010 next_message = *incoming_flood;
1015 GNUNET_STATISTICS_update (stats,
1016 "# flood messages discarded (clock skew too large)",
1021 if (0 == (memcmp (peer, &my_identity, sizeof(struct GNUNET_PeerIdentity))))
1023 /* send to self, update our own estimate IF this also comes from us! */
1024 if (0 == memcmp (&incoming_flood->pkey,
1026 sizeof (my_public_key)))
1027 update_network_size_estimate ();
1030 if (matching_bits >= ntohl (size_estimate_messages[idx].matching_bits))
1032 /* cancel transmission from us to this peer for this round */
1033 if (idx == estimate_index)
1035 if (peer_entry->previous_round == GNUNET_YES)
1037 /* cancel any activity for current round */
1038 if (peer_entry->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1040 GNUNET_SCHEDULER_cancel (peer_entry->transmit_task);
1041 peer_entry->transmit_task = GNUNET_SCHEDULER_NO_TASK;
1043 if (peer_entry->th != NULL)
1045 GNUNET_CORE_notify_transmit_ready_cancel (peer_entry->th);
1046 peer_entry->th = NULL;
1052 /* cancel previous round only */
1053 peer_entry->previous_round = GNUNET_YES;
1056 if (matching_bits <= ntohl (size_estimate_messages[idx].matching_bits))
1058 /* Not closer than our most recent message, no need to do work here */
1059 GNUNET_STATISTICS_update (stats,
1060 "# flood messages ignored (had closer already)",
1066 verify_message_crypto (incoming_flood))
1068 GNUNET_break_op (0);
1071 size_estimate_messages[idx] = *incoming_flood;
1072 size_estimate_messages[idx].hop_count = htonl (ntohl (incoming_flood->hop_count) + 1);
1073 hop_count_max = GNUNET_MAX (ntohl (incoming_flood->hop_count) + 1,
1076 /* have a new, better size estimate, inform clients */
1077 update_network_size_estimate ();
1080 GNUNET_CONTAINER_multihashmap_iterate (peers,
1081 &update_flood_times,
1089 * Method called whenever a peer connects.
1091 * @param cls closure
1092 * @param peer peer identity this notification is about
1093 * @param atsi performance data
1096 handle_core_connect(void *cls, const struct GNUNET_PeerIdentity *peer,
1097 const struct GNUNET_TRANSPORT_ATS_Information *atsi)
1099 struct NSEPeerEntry *peer_entry;
1102 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1103 "Peer `%s' connected to us\n",
1106 peer_entry = GNUNET_malloc(sizeof(struct NSEPeerEntry));
1107 peer_entry->id = *peer;
1108 GNUNET_CONTAINER_multihashmap_put (peers,
1111 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY);
1112 peer_entry->transmit_task = GNUNET_SCHEDULER_add_delayed (get_transmit_delay (-1),
1119 * Method called whenever a peer disconnects.
1121 * @param cls closure
1122 * @param peer peer identity this notification is about
1125 handle_core_disconnect(void *cls, const struct GNUNET_PeerIdentity *peer)
1127 struct NSEPeerEntry *pos;
1130 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1131 "Peer `%s' disconnected from us\n",
1134 pos = GNUNET_CONTAINER_multihashmap_get (peers,
1141 GNUNET_assert (GNUNET_YES ==
1142 GNUNET_CONTAINER_multihashmap_remove (peers,
1145 if (pos->transmit_task != GNUNET_SCHEDULER_NO_TASK)
1146 GNUNET_SCHEDULER_cancel (pos->transmit_task);
1147 if (pos->th != NULL)
1148 GNUNET_CORE_notify_transmit_ready_cancel (pos->th);
1154 * Task run during shutdown.
1160 shutdown_task(void *cls,
1161 const struct GNUNET_SCHEDULER_TaskContext *tc)
1163 if (flood_task != GNUNET_SCHEDULER_NO_TASK)
1165 GNUNET_SCHEDULER_cancel (flood_task);
1166 flood_task = GNUNET_SCHEDULER_NO_TASK;
1168 if (proof_task != GNUNET_SCHEDULER_NO_TASK)
1170 GNUNET_SCHEDULER_cancel (proof_task);
1171 proof_task = GNUNET_SCHEDULER_NO_TASK;
1172 write_proof (); /* remember progress */
1176 GNUNET_SERVER_notification_context_destroy (nc);
1179 if (coreAPI != NULL)
1181 GNUNET_CORE_disconnect (coreAPI);
1186 GNUNET_STATISTICS_destroy (stats, GNUNET_NO);
1191 GNUNET_CONTAINER_multihashmap_destroy (peers);
1194 if (my_private_key != NULL)
1196 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1197 my_private_key = NULL;
1199 #if ENABLE_HISTOGRAM
1202 GNUNET_BIO_write_close (wh);
1210 * Called on core init/fail.
1212 * @param cls service closure
1213 * @param server handle to the server for this service
1214 * @param identity the public identity of this peer
1215 * @param publicKey the public key of this peer
1218 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1219 const struct GNUNET_PeerIdentity *identity,
1220 const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *publicKey)
1222 struct GNUNET_TIME_Absolute now;
1223 struct GNUNET_TIME_Absolute prev_time;
1229 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1230 "Connection to core FAILED!\n");
1232 GNUNET_SCHEDULER_shutdown ();
1235 GNUNET_assert (0 == memcmp (&my_identity, identity, sizeof (struct GNUNET_PeerIdentity)));
1236 now = GNUNET_TIME_absolute_get ();
1237 current_timestamp.abs_value = (now.abs_value / gnunet_nse_interval.rel_value) * gnunet_nse_interval.rel_value;
1238 next_timestamp.abs_value = current_timestamp.abs_value + gnunet_nse_interval.rel_value;
1240 for (i=0;i<HISTORY_SIZE;i++)
1242 prev_time.abs_value = current_timestamp.abs_value - (HISTORY_SIZE - i - 1) * gnunet_nse_interval.rel_value;
1243 setup_flood_message (i, prev_time);
1245 estimate_index = HISTORY_SIZE - 1;
1248 = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_absolute_get_remaining (next_timestamp),
1249 &update_flood_message, NULL);
1254 * Handle network size estimate clients.
1256 * @param cls closure
1257 * @param server the initialized server
1258 * @param c configuration to use
1261 run(void *cls, struct GNUNET_SERVER_Handle *server,
1262 const struct GNUNET_CONFIGURATION_Handle *c)
1267 static const struct GNUNET_SERVER_MessageHandler handlers[] =
1269 { &handle_start_message, NULL, GNUNET_MESSAGE_TYPE_NSE_START, sizeof (struct GNUNET_MessageHeader) },
1270 { NULL, NULL, 0, 0 }
1272 static const struct GNUNET_CORE_MessageHandler core_handlers[] =
1274 { &handle_p2p_size_estimate, GNUNET_MESSAGE_TYPE_NSE_P2P_FLOOD, sizeof (struct GNUNET_NSE_FloodMessage) },
1280 GNUNET_CONFIGURATION_get_value_time (cfg,
1282 &gnunet_nse_interval)) ||
1284 GNUNET_CONFIGURATION_get_value_time (cfg,
1286 &proof_find_delay)) ||
1288 GNUNET_CONFIGURATION_get_value_number (cfg,
1290 &nse_work_required)) )
1292 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1293 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1294 GNUNET_SCHEDULER_shutdown ();
1297 if (nse_work_required >= sizeof (GNUNET_HashCode) * 8)
1299 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1300 _ ("Invalid work requirement for NSE service. Exiting.\n"));
1301 GNUNET_SCHEDULER_shutdown ();
1307 GNUNET_CONFIGURATION_get_value_filename (cfg,
1308 "GNUNETD", "HOSTKEY",
1311 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1312 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1313 GNUNET_SCHEDULER_shutdown ();
1316 my_private_key = GNUNET_CRYPTO_rsa_key_create_from_file (keyfile);
1317 GNUNET_free (keyfile);
1318 if (my_private_key == NULL)
1320 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1321 _("NSE service could not access hostkey. Exiting.\n"));
1322 GNUNET_SCHEDULER_shutdown ();
1325 GNUNET_CRYPTO_rsa_key_get_public (my_private_key, &my_public_key);
1326 GNUNET_CRYPTO_hash (&my_public_key, sizeof (my_public_key), &my_identity.hashPubKey);
1328 GNUNET_CONFIGURATION_get_value_filename (cfg,
1332 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1333 _ ("NSE service is lacking key configuration settings. Exiting.\n"));
1334 if (my_private_key != NULL)
1336 GNUNET_CRYPTO_rsa_key_free (my_private_key);
1337 my_private_key = NULL;
1339 GNUNET_SCHEDULER_shutdown ();
1342 if ( (GNUNET_YES != GNUNET_DISK_file_test (proof)) ||
1343 (sizeof (my_proof) !=
1344 GNUNET_DISK_fn_read (proof,
1346 sizeof (my_proof))) )
1348 GNUNET_free (proof);
1349 proof_task = GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE,
1353 peers = GNUNET_CONTAINER_multihashmap_create (128);
1354 GNUNET_SERVER_add_handlers (server, handlers);
1355 nc = GNUNET_SERVER_notification_context_create (server, 1);
1356 /* Connect to core service and register core handlers */
1357 coreAPI = GNUNET_CORE_connect (cfg, /* Main configuration */
1358 CORE_QUEUE_SIZE, /* queue size */
1359 NULL, /* Closure passed to functions */
1360 &core_init, /* Call core_init once connected */
1361 &handle_core_connect, /* Handle connects */
1362 &handle_core_disconnect, /* Handle disconnects */
1363 NULL, /* Do we care about "status" updates? */
1364 NULL, /* Don't want notified about all incoming messages */
1365 GNUNET_NO, /* For header only inbound notification */
1366 NULL, /* Don't want notified about all outbound messages */
1367 GNUNET_NO, /* For header only outbound notification */
1368 core_handlers); /* Register these handlers */
1369 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1370 &shutdown_task, NULL);
1371 #if ENABLE_HISTOGRAM
1373 GNUNET_CONFIGURATION_get_value_filename (cfg,
1377 wh = GNUNET_BIO_write_open (proof);
1378 GNUNET_free (proof);
1381 if (coreAPI == NULL)
1383 GNUNET_SCHEDULER_shutdown ();
1386 stats = GNUNET_STATISTICS_create ("nse", cfg);
1391 * The main function for the statistics service.
1393 * @param argc number of arguments from the command line
1394 * @param argv command line arguments
1395 * @return 0 ok, 1 on error
1398 main(int argc, char * const *argv)
1400 return (GNUNET_OK == GNUNET_SERVICE_run (argc, argv,
1402 GNUNET_SERVICE_OPTION_NONE, &run,
1406 /* end of gnunet-service-nse.c */