2 This file is part of GNUnet
3 Copyright (C) 2012, 2013 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 consensus/gnunet-service-consensus.c
23 * @brief multi-peer set reconciliation
24 * @author Florian Dold
28 #include "gnunet_util_lib.h"
29 #include "gnunet_protocols.h"
30 #include "gnunet_applications.h"
31 #include "gnunet_set_service.h"
32 #include "gnunet_consensus_service.h"
33 #include "consensus_protocol.h"
34 #include "consensus.h"
38 * Log macro that prefixes the local peer and the peer we are in contact with.
40 * @param kind log level
41 * @param cpi ConsensusPeerInformation of the partner peer
42 * @param m log message
44 #define LOG_PP(kind, cpi, m,...) GNUNET_log (kind, "P%d for P%d: " m, \
45 cpi->session->local_peer_idx, (int) (cpi - cpi->session->info),##__VA_ARGS__)
49 * Number of exponential rounds, used in the exp and completion round.
51 #define NUM_EXP_REPETITIONS 4
54 /* forward declarations */
56 /* mutual recursion with struct ConsensusSession */
57 struct ConsensusPeerInformation;
59 /* mutual recursion with round_over */
61 subround_over (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc);
65 * Describes the current round a consensus session is in.
70 * Not started the protocol yet.
72 CONSENSUS_ROUND_BEGIN=0,
74 * Distribution of elements with the exponential scheme.
76 CONSENSUS_ROUND_EXCHANGE,
78 * Collect and distribute missing values.
80 CONSENSUS_ROUND_COMPLETION,
82 * Consensus concluded. After timeout and finished communication with client,
83 * consensus session will be destroyed.
85 CONSENSUS_ROUND_FINISH
90 * Information about the current round.
95 * The current main round.
97 enum ConsensusRound round;
99 * The current exp round repetition, valid if
100 * the main round is an exp round.
102 uint32_t exp_repetition;
104 * The current exp subround, valid if
105 * the main round is an exp round.
107 uint32_t exp_subround;
112 * A consensus session consists of one local client and the remote authorities.
114 struct ConsensusSession
117 * Consensus sessions are kept in a DLL.
119 struct ConsensusSession *next;
122 * Consensus sessions are kept in a DLL.
124 struct ConsensusSession *prev;
127 * Global consensus identification, computed
128 * from the session id and participating authorities.
130 struct GNUNET_HashCode global_id;
133 * Client that inhabits the session
135 struct GNUNET_SERVER_Client *client;
138 * Queued messages to the client.
140 struct GNUNET_MQ_Handle *client_mq;
143 * Time when the conclusion of the consensus should begin.
145 struct GNUNET_TIME_Absolute conclude_start;
148 * Timeout for all rounds together, single rounds will schedule a timeout task
149 * with a fraction of the conclude timeout.
150 * Only valid once the current round is not CONSENSUS_ROUND_BEGIN.
152 struct GNUNET_TIME_Absolute conclude_deadline;
155 * Timeout task identifier for the current round or subround.
157 struct GNUNET_SCHEDULER_Task * round_timeout_tid;
160 * Number of other peers in the consensus.
162 unsigned int num_peers;
165 * Information about the other peers,
168 struct ConsensusPeerInformation *info;
171 * Index of the local peer in the peers array
173 unsigned int local_peer_idx;
178 enum ConsensusRound current_round;
181 * Permutation of peers for the current round,
186 * Inverse permutation of peers for the current round,
188 uint32_t *shuffle_inv;
191 * Current round of the exponential scheme.
193 uint32_t exp_repetition;
196 * Current sub-round of the exponential scheme.
198 uint32_t exp_subround;
201 * The partner for the current exp-round.
202 * The local peer will initiate the set reconciliation with the
205 struct ConsensusPeerInformation *partner_outgoing;
208 * The partner for the current exp-round
209 * The incoming peer will initiate the set reconciliation with
212 struct ConsensusPeerInformation *partner_incoming;
215 * The consensus set of this session.
217 struct GNUNET_SET_Handle *element_set;
220 * Listener for requests from other peers.
221 * Uses the session's global id as app id.
223 struct GNUNET_SET_ListenHandle *set_listener;
228 * Information about a peer that is in a consensus session.
230 struct ConsensusPeerInformation
233 * Peer identitty of the peer in the consensus session
235 struct GNUNET_PeerIdentity peer_id;
238 * Back-reference to the consensus session,
239 * to that ConsensusPeerInformation can be used as a closure
241 struct ConsensusSession *session;
244 * Have we finished the set operation for this (sub-)round?
249 * Set operation we are currently executing with this peer.
251 struct GNUNET_SET_OperationHandle *set_op;
254 * Set operation we are planning on executing with this peer.
256 struct GNUNET_SET_OperationHandle *delayed_set_op;
259 * Info about the round of the delayed set operation.
261 struct RoundInfo delayed_round_info;
266 * Linked list of sessions this peer participates in.
268 static struct ConsensusSession *sessions_head;
271 * Linked list of sessions this peer participates in.
273 static struct ConsensusSession *sessions_tail;
276 * Configuration of the consensus service.
278 static const struct GNUNET_CONFIGURATION_Handle *cfg;
281 * Handle to the server for this service.
283 static struct GNUNET_SERVER_Handle *srv;
286 * Peer that runs this service.
288 static struct GNUNET_PeerIdentity my_peer;
292 * Check if the current subround has finished.
293 * Must only be called when an exp-round is the current round.
295 * @param session session to check for exp-round completion
296 * @return GNUNET_YES if the subround has finished,
300 have_exp_subround_finished (const struct ConsensusSession *session)
304 GNUNET_assert (CONSENSUS_ROUND_EXCHANGE == session->current_round);
307 if ( (NULL != session->partner_outgoing) &&
308 (GNUNET_NO == session->partner_outgoing->set_op_finished) )
310 if ( (NULL != session->partner_incoming) &&
311 (GNUNET_NO == session->partner_incoming->set_op_finished) )
313 if (0 == not_finished)
320 * Destroy a session, free all resources associated with it.
322 * @param session the session to destroy
325 destroy_session (struct ConsensusSession *session)
329 GNUNET_CONTAINER_DLL_remove (sessions_head, sessions_tail, session);
330 if (NULL != session->element_set)
332 GNUNET_SET_destroy (session->element_set);
333 session->element_set = NULL;
335 if (NULL != session->set_listener)
337 GNUNET_SET_listen_cancel (session->set_listener);
338 session->set_listener = NULL;
340 if (NULL != session->client_mq)
342 GNUNET_MQ_destroy (session->client_mq);
343 session->client_mq = NULL;
345 if (NULL != session->client)
347 GNUNET_SERVER_client_disconnect (session->client);
348 session->client = NULL;
350 if (NULL != session->shuffle)
352 GNUNET_free (session->shuffle);
353 session->shuffle = NULL;
355 if (NULL != session->shuffle_inv)
357 GNUNET_free (session->shuffle_inv);
358 session->shuffle_inv = NULL;
360 if (NULL != session->info)
362 for (i = 0; i < session->num_peers; i++)
364 struct ConsensusPeerInformation *cpi;
365 cpi = &session->info[i];
366 if (NULL != cpi->set_op)
368 GNUNET_SET_operation_cancel (cpi->set_op);
372 GNUNET_free (session->info);
373 session->info = NULL;
375 GNUNET_free (session);
380 * Iterator for set elements. [FIXME: bad comment]
383 * @param element the current element, NULL if all elements have been
385 * @return #GNUNET_YES to continue iterating, #GNUNET_NO to stop.
388 send_to_client_iter (void *cls,
389 const struct GNUNET_SET_Element *element)
391 struct ConsensusSession *session = cls;
392 struct GNUNET_MQ_Envelope *ev;
396 struct GNUNET_CONSENSUS_ElementMessage *m;
398 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
399 "P%d: got element for client\n",
400 session->local_peer_idx);
402 ev = GNUNET_MQ_msg_extra (m, element->size,
403 GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_RECEIVED_ELEMENT);
404 m->element_type = htons (element->element_type);
405 memcpy (&m[1], element->data, element->size);
406 GNUNET_MQ_send (session->client_mq, ev);
410 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
411 "P%d: finished iterating elements for client\n",
412 session->local_peer_idx);
413 ev = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE_DONE);
414 GNUNET_MQ_send (session->client_mq, ev);
421 * Start the next round.
422 * This function can be invoked as a timeout task, or called manually (tc will be NULL then).
424 * @param cls the session
425 * @param tc task context, for when this task is invoked by the scheduler,
426 * NULL if invoked for another reason
429 round_over (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
431 struct ConsensusSession *session;
435 /* don't kick off next round if we're shutting down */
436 if ((NULL != tc) && (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
440 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%d: round over\n", session->local_peer_idx);
443 session->round_timeout_tid = NULL;
445 if (session->round_timeout_tid != NULL)
447 GNUNET_SCHEDULER_cancel (session->round_timeout_tid);
448 session->round_timeout_tid = NULL;
451 for (i = 0; i < session->num_peers; i++)
453 if (NULL != session->info[i].set_op)
455 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%d: canceling stray op with P%d\n",
456 session->local_peer_idx, i);
457 GNUNET_SET_operation_cancel (session->info[i].set_op);
458 session->info[i].set_op = NULL;
460 /* we're in the new round, nothing finished yet */
461 session->info[i].set_op_finished = GNUNET_NO;
464 switch (session->current_round)
466 case CONSENSUS_ROUND_BEGIN:
467 session->current_round = CONSENSUS_ROUND_EXCHANGE;
468 session->exp_repetition = 0;
469 subround_over (session, NULL);
471 case CONSENSUS_ROUND_EXCHANGE:
472 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%d: finished, sending elements to client\n",
473 session->local_peer_idx);
474 session->current_round = CONSENSUS_ROUND_FINISH;
475 res = GNUNET_SET_iterate (session->element_set, send_to_client_iter, session);
476 if (GNUNET_SYSERR == res)
478 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "can't iterate set: set invalid\n");
480 else if (GNUNET_NO == res)
482 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "can't iterate set: iterator already active\n");
492 * Create a new permutation for the session's peers in session->shuffle.
493 * Uses a Fisher-Yates shuffle with pseudo-randomness coming from
494 * both the global session id and the current round index.
496 * @param session the session to create the new permutation for
499 shuffle (struct ConsensusSession *session)
502 uint32_t randomness[session->num_peers-1];
504 if (NULL == session->shuffle)
505 session->shuffle = GNUNET_malloc (session->num_peers * sizeof (*session->shuffle));
506 if (NULL == session->shuffle_inv)
507 session->shuffle_inv = GNUNET_malloc (session->num_peers * sizeof (*session->shuffle_inv));
509 GNUNET_CRYPTO_kdf (randomness, sizeof (randomness),
510 &session->exp_repetition, sizeof (uint32_t),
511 &session->global_id, sizeof (struct GNUNET_HashCode),
514 for (i = 0; i < session->num_peers; i++)
515 session->shuffle[i] = i;
517 for (i = session->num_peers - 1; i > 0; i--)
521 x = randomness[i-1] % session->num_peers;
522 tmp = session->shuffle[x];
523 session->shuffle[x] = session->shuffle[i];
524 session->shuffle[i] = tmp;
527 /* create the inverse */
528 for (i = 0; i < session->num_peers; i++)
529 session->shuffle_inv[session->shuffle[i]] = i;
534 * Find and set the partner_incoming and partner_outgoing of our peer,
535 * one of them may not exist (and thus set to NULL) if the number of peers
536 * in the session is not a power of two.
538 * @param session the consensus session
541 find_partners (struct ConsensusSession *session)
544 unsigned int num_ghosts;
545 unsigned int largest_arc;
548 /* shuffled local index */
549 int my_idx = session->shuffle[session->local_peer_idx];
551 /* distance to neighboring peer in current subround */
552 arc = 1 << session->exp_subround;
554 while (largest_arc < session->num_peers)
556 num_ghosts = largest_arc - session->num_peers;
557 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "largest arc: %u\n", largest_arc);
558 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "arc: %u\n", arc);
559 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "num ghosts: %u\n", num_ghosts);
561 if (0 == (my_idx & arc))
563 /* we are outgoing */
564 partner_idx = (my_idx + arc) % session->num_peers;
565 session->partner_outgoing = &session->info[session->shuffle_inv[partner_idx]];
566 GNUNET_assert (GNUNET_NO == session->partner_outgoing->set_op_finished);
567 /* are we a 'ghost' of a peer that would exist if
568 * the number of peers was a power of two, and thus have to partner
569 * with an additional peer?
571 if (my_idx < num_ghosts)
573 int ghost_partner_idx;
574 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "my index %d, arc %d, peers %u\n", my_idx, arc, session->num_peers);
575 ghost_partner_idx = (my_idx - (int) arc) % (int) session->num_peers;
576 /* platform dependent; modulo sometimes returns negative values */
577 if (ghost_partner_idx < 0)
578 ghost_partner_idx += session->num_peers;
579 /* we only need to have a ghost partner if the partner is outgoing */
580 if (0 == (ghost_partner_idx & arc))
582 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "ghost partner is %d\n", ghost_partner_idx);
583 session->partner_incoming = &session->info[session->shuffle_inv[ghost_partner_idx]];
584 GNUNET_assert (GNUNET_NO == session->partner_incoming->set_op_finished);
588 session->partner_incoming = NULL;
591 /* we only have an incoming connection */
592 partner_idx = (my_idx - (int) arc) % (int) session->num_peers;
594 partner_idx += session->num_peers;
595 session->partner_outgoing = NULL;
596 session->partner_incoming = &session->info[session->shuffle_inv[partner_idx]];
597 GNUNET_assert (GNUNET_NO == session->partner_incoming->set_op_finished);
602 * Callback for set operation results. Called for each element
606 * @param element a result element, only valid if status is GNUNET_SET_STATUS_OK
607 * @param status see enum GNUNET_SET_Status
610 set_result_cb (void *cls,
611 const struct GNUNET_SET_Element *element,
612 enum GNUNET_SET_Status status)
614 struct ConsensusPeerInformation *cpi = cls;
615 unsigned int remote_idx = cpi - cpi->session->info;
616 unsigned int local_idx = cpi->session->local_peer_idx;
618 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: set result from P%u with status %u\n",
619 local_idx, remote_idx, (unsigned int) status);
621 GNUNET_assert ((cpi == cpi->session->partner_outgoing) ||
622 (cpi == cpi->session->partner_incoming));
626 case GNUNET_SET_STATUS_OK:
627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: set result from P%u: element\n",
628 local_idx, remote_idx);
630 case GNUNET_SET_STATUS_FAILURE:
631 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: set result from P%u: failure\n",
632 local_idx, remote_idx);
635 case GNUNET_SET_STATUS_HALF_DONE:
636 case GNUNET_SET_STATUS_DONE:
637 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: set result from P%u: done\n",
638 local_idx, remote_idx);
639 cpi->set_op_finished = GNUNET_YES;
641 if (have_exp_subround_finished (cpi->session) == GNUNET_YES)
643 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: all reconciliations of subround done\n",
645 subround_over (cpi->session, NULL);
649 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: waiting for further set results\n",
658 switch (cpi->session->current_round)
660 case CONSENSUS_ROUND_COMPLETION:
661 case CONSENSUS_ROUND_EXCHANGE:
662 GNUNET_SET_add_element (cpi->session->element_set, element, NULL, NULL);
672 * Compare the round the session is in with the round of the given context message.
674 * @param session a consensus session
675 * @param ri a round context message
676 * @return 0 if it's the same round, -1 if the session is in an earlier round,
677 * 1 if the session is in a later round
680 rounds_compare (struct ConsensusSession *session,
681 struct RoundInfo* ri)
683 if (session->current_round < ri->round)
685 if (session->current_round > ri->round)
687 if (session->current_round == CONSENSUS_ROUND_EXCHANGE)
689 if (session->exp_repetition < ri->exp_repetition)
691 if (session->exp_repetition > ri->exp_repetition)
693 if (session->exp_subround < ri->exp_subround)
695 if (session->exp_subround > ri->exp_subround)
699 /* other rounds have no subrounds / repetitions to compare */
705 * Do the next subround in the exp-scheme.
706 * This function can be invoked as a timeout task, or called manually (tc will be NULL then).
708 * @param cls the session
709 * @param tc task context, for when this task is invoked by the scheduler,
710 * NULL if invoked for another reason
713 subround_over (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
715 struct ConsensusSession *session;
716 struct GNUNET_TIME_Relative subround_timeout;
719 /* don't kick off next subround if we're shutting down */
720 if ((NULL != tc) && (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN))
725 GNUNET_assert (CONSENSUS_ROUND_EXCHANGE == session->current_round);
729 session->round_timeout_tid = NULL;
730 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: consensus subround timed out\n",
731 session->local_peer_idx);
735 if (session->round_timeout_tid != NULL)
737 GNUNET_SCHEDULER_cancel (session->round_timeout_tid);
738 session->round_timeout_tid = NULL;
741 for (i = 0; i < session->num_peers; i++)
743 if (NULL != session->info[i].set_op)
745 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%d: canceling stray op with P%d\n",
746 session->local_peer_idx, i);
747 GNUNET_SET_operation_cancel (session->info[i].set_op);
748 session->info[i].set_op = NULL;
750 /* we're in the new round, nothing finished yet */
751 session->info[i].set_op_finished = GNUNET_NO;
754 if (session->exp_repetition >= NUM_EXP_REPETITIONS)
756 round_over (session, NULL);
760 if (session->exp_repetition == 0)
762 /* initialize everything for the log-rounds */
763 session->exp_repetition = 1;
764 session->exp_subround = 0;
765 if (NULL == session->shuffle)
766 session->shuffle = GNUNET_malloc ((sizeof (int)) * session->num_peers);
767 if (NULL == session->shuffle_inv)
768 session->shuffle_inv = GNUNET_malloc ((sizeof (int)) * session->num_peers);
769 for (i = 0; i < session->num_peers; i++)
770 session->shuffle[i] = session->shuffle_inv[i] = i;
772 else if (session->exp_subround + 1 >= (int) ceil (log2 (session->num_peers)))
774 /* subrounds done, start new log-round */
775 session->exp_repetition++;
776 session->exp_subround = 0;
781 session->exp_subround++;
785 GNUNET_TIME_relative_divide (GNUNET_TIME_absolute_get_difference (session->conclude_start, session->conclude_deadline),
786 2 * NUM_EXP_REPETITIONS * ((int) ceil (log2 (session->num_peers))));
788 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "subround timeout: %u ms\n", subround_timeout.rel_value_us / 1000);
790 session->round_timeout_tid = GNUNET_SCHEDULER_add_delayed (subround_timeout, subround_over, session);
792 /* determine the incoming and outgoing partner */
793 find_partners (session);
795 GNUNET_assert (session->partner_outgoing != &session->info[session->local_peer_idx]);
796 GNUNET_assert (session->partner_incoming != &session->info[session->local_peer_idx]);
798 /* initiate set operation with the outgoing partner */
799 if (NULL != session->partner_outgoing)
801 struct GNUNET_CONSENSUS_RoundContextMessage *msg;
802 msg = GNUNET_new (struct GNUNET_CONSENSUS_RoundContextMessage);
803 msg->header.type = htons (GNUNET_MESSAGE_TYPE_CONSENSUS_P2P_ROUND_CONTEXT);
804 msg->header.size = htons (sizeof *msg);
805 msg->round = htonl (session->current_round);
806 msg->exp_repetition = htonl (session->exp_repetition);
807 msg->exp_subround = htonl (session->exp_subround);
809 if (NULL != session->partner_outgoing->set_op)
812 GNUNET_SET_operation_cancel (session->partner_outgoing->set_op);
814 session->partner_outgoing->set_op =
815 GNUNET_SET_prepare (&session->partner_outgoing->peer_id,
817 (struct GNUNET_MessageHeader *) msg,
818 GNUNET_SET_RESULT_ADDED,
819 set_result_cb, session->partner_outgoing);
821 if (GNUNET_OK != GNUNET_SET_commit (session->partner_outgoing->set_op, session->element_set))
824 session->partner_outgoing->set_op = NULL;
825 session->partner_outgoing->set_op_finished = GNUNET_YES;
829 /* commit to the delayed set operation */
830 if ((NULL != session->partner_incoming) && (NULL != session->partner_incoming->delayed_set_op))
832 int cmp = rounds_compare (session, &session->partner_incoming->delayed_round_info);
834 if (NULL != session->partner_incoming->set_op)
837 GNUNET_SET_operation_cancel (session->partner_incoming->set_op);
838 session->partner_incoming->set_op = NULL;
842 if (GNUNET_OK != GNUNET_SET_commit (session->partner_incoming->delayed_set_op, session->element_set))
846 session->partner_incoming->set_op = session->partner_incoming->delayed_set_op;
847 session->partner_incoming->delayed_set_op = NULL;
848 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%d resumed delayed round with P%d\n",
849 session->local_peer_idx, (int) (session->partner_incoming - session->info));
853 /* this should not happen -- a round has been skipped! */
858 #ifdef GNUNET_EXTRA_LOGGING
862 if (session->partner_outgoing == NULL)
865 out = (int) (session->partner_outgoing - session->info);
866 if (session->partner_incoming == NULL)
869 in = (int) (session->partner_incoming - session->info);
870 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: doing exp-round, r=%d, sub=%d, in: %d, out: %d\n", session->local_peer_idx,
871 session->exp_repetition, session->exp_subround, in, out);
873 #endif /* GNUNET_EXTRA_LOGGING */
879 * Search peer in the list of peers in session.
881 * @param peer peer to find
882 * @param session session with peer
883 * @return index of peer, -1 if peer is not in session
886 get_peer_idx (const struct GNUNET_PeerIdentity *peer, const struct ConsensusSession *session)
889 for (i = 0; i < session->num_peers; i++)
890 if (0 == memcmp (peer, &session->info[i].peer_id, sizeof *peer))
897 * Compute a global, (hopefully) unique consensus session id,
898 * from the local id of the consensus session, and the identities of all participants.
899 * Thus, if the local id of two consensus sessions coincide, but are not comprised of
900 * exactly the same peers, the global id will be different.
902 * @param session session to generate the global id for
903 * @param session_id local id of the consensus session
906 compute_global_id (struct ConsensusSession *session,
907 const struct GNUNET_HashCode *session_id)
910 struct GNUNET_HashCode tmp;
911 struct GNUNET_HashCode phash;
913 /* FIXME: use kdf? */
915 session->global_id = *session_id;
916 for (i = 0; i < session->num_peers; ++i)
918 GNUNET_CRYPTO_hash (&session->info[i].peer_id, sizeof (struct GNUNET_PeerIdentity), &phash);
919 GNUNET_CRYPTO_hash_xor (&session->global_id, &phash, &tmp);
920 session->global_id = tmp;
921 GNUNET_CRYPTO_hash (&session->global_id, sizeof (struct GNUNET_PeerIdentity), &tmp);
922 session->global_id = tmp;
928 * Compare two peer identities.
930 * @param h1 some peer identity
931 * @param h2 some peer identity
932 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
935 peer_id_cmp (const void *h1, const void *h2)
937 return memcmp (h1, h2, sizeof (struct GNUNET_PeerIdentity));
942 * Create the sorted list of peers for the session,
943 * add the local peer if not in the join message.
946 initialize_session_peer_list (struct ConsensusSession *session,
947 struct GNUNET_CONSENSUS_JoinMessage *join_msg)
949 unsigned int local_peer_in_list;
950 uint32_t listed_peers;
951 const struct GNUNET_PeerIdentity *msg_peers;
952 struct GNUNET_PeerIdentity *peers;
955 GNUNET_assert (NULL != join_msg);
957 /* peers in the join message, may or may not include the local peer */
958 listed_peers = ntohl (join_msg->num_peers);
960 session->num_peers = listed_peers;
962 msg_peers = (struct GNUNET_PeerIdentity *) &join_msg[1];
964 local_peer_in_list = GNUNET_NO;
965 for (i = 0; i < listed_peers; i++)
967 if (0 == memcmp (&msg_peers[i], &my_peer, sizeof (struct GNUNET_PeerIdentity)))
969 local_peer_in_list = GNUNET_YES;
974 if (GNUNET_NO == local_peer_in_list)
975 session->num_peers++;
977 peers = GNUNET_malloc (session->num_peers * sizeof (struct GNUNET_PeerIdentity));
979 if (GNUNET_NO == local_peer_in_list)
980 peers[session->num_peers - 1] = my_peer;
982 memcpy (peers, msg_peers, listed_peers * sizeof (struct GNUNET_PeerIdentity));
983 qsort (peers, session->num_peers, sizeof (struct GNUNET_PeerIdentity), &peer_id_cmp);
985 session->info = GNUNET_malloc (session->num_peers * sizeof (struct ConsensusPeerInformation));
987 for (i = 0; i < session->num_peers; ++i)
989 /* initialize back-references, so consensus peer information can
990 * be used as closure */
991 session->info[i].session = session;
992 session->info[i].peer_id = peers[i];
1000 * Called when another peer wants to do a set operation with the
1003 * @param cls closure
1004 * @param other_peer the other peer
1005 * @param context_msg message with application specific information from
1007 * @param request request from the other peer, use GNUNET_SET_accept
1008 * to accept it, otherwise the request will be refused
1009 * Note that we don't use a return value here, as it is also
1010 * necessary to specify the set we want to do the operation with,
1011 * whith sometimes can be derived from the context message.
1012 * Also necessary to specify the timeout.
1015 set_listen_cb (void *cls,
1016 const struct GNUNET_PeerIdentity *other_peer,
1017 const struct GNUNET_MessageHeader *context_msg,
1018 struct GNUNET_SET_Request *request)
1020 struct ConsensusSession *session = cls;
1021 struct GNUNET_CONSENSUS_RoundContextMessage *msg = (struct GNUNET_CONSENSUS_RoundContextMessage *) context_msg;
1022 struct ConsensusPeerInformation *cpi;
1023 struct GNUNET_SET_OperationHandle *set_op;
1024 struct RoundInfo round_info;
1028 if (NULL == context_msg)
1030 GNUNET_break_op (0);
1034 index = get_peer_idx (other_peer, session);
1038 GNUNET_break_op (0);
1042 round_info.round = ntohl (msg->round);
1043 round_info.exp_repetition = ntohl (msg->exp_repetition);
1044 round_info.exp_subround = ntohl (msg->exp_subround);
1046 cpi = &session->info[index];
1048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%d got set request from P%d\n", session->local_peer_idx, index);
1050 switch (session->current_round)
1052 case CONSENSUS_ROUND_BEGIN:
1053 /* we're in the begin round, so requests for the exchange round may
1054 * come in, they will be delayed for now! */
1055 case CONSENSUS_ROUND_EXCHANGE:
1056 cmp = rounds_compare (session, &round_info);
1059 /* the other peer is too late */
1060 LOG_PP (GNUNET_ERROR_TYPE_DEBUG, cpi, "too late for the current round\n");
1063 /* kill old request, if any. this is legal,
1064 * as the other peer would not make a new request if it would want to
1065 * complete the old one! */
1066 if (NULL != cpi->set_op)
1068 LOG_PP (GNUNET_ERROR_TYPE_INFO, cpi, "got new request from same peer, canceling old one\n");
1069 GNUNET_SET_operation_cancel (cpi->set_op);
1072 set_op = GNUNET_SET_accept (request, GNUNET_SET_RESULT_ADDED,
1073 set_result_cb, &session->info[index]);
1076 /* we're in exactly the right round for the incoming request */
1077 if (cpi != cpi->session->partner_incoming)
1079 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "P%u: got request from %u (with matching round), "
1080 "but incoming partner is %d\n", cpi->session->local_peer_idx, cpi - cpi->session->info,
1081 ((NULL == cpi->session->partner_incoming) ? -1 : (cpi->session->partner_incoming - cpi->session->info)));
1082 GNUNET_SET_operation_cancel (set_op);
1085 cpi->set_op = set_op;
1086 if (GNUNET_OK != GNUNET_SET_commit (set_op, session->element_set))
1090 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%d commited to set request from P%d\n", session->local_peer_idx, index);
1094 /* we still have wait until we have finished the current round,
1095 * as the other peer's round is larger */
1096 cpi->delayed_set_op = set_op;
1097 cpi->delayed_round_info = round_info;
1098 /* The current setop is finished, as we canceled the current setop above. */
1099 cpi->set_op_finished = GNUNET_YES;
1100 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%d delaying set request from P%d\n", session->local_peer_idx, index);
1104 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "P%d got unexpected set request in round %d from P%d\n",
1105 session->local_peer_idx, session->current_round, index);
1106 GNUNET_break_op (0);
1113 * Initialize the session, continue receiving messages from the owning client
1115 * @param session the session to initialize
1116 * @param join_msg the join message from the client
1119 initialize_session (struct ConsensusSession *session,
1120 struct GNUNET_CONSENSUS_JoinMessage *join_msg)
1122 struct ConsensusSession *other_session;
1124 initialize_session_peer_list (session, join_msg);
1125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "session with %u peers\n", session->num_peers);
1126 compute_global_id (session, &join_msg->session_id);
1128 /* check if some local client already owns the session.
1129 * it is only legal to have a session with an existing global id
1130 * if all other sessions with this global id are finished.*/
1131 other_session = sessions_head;
1132 while (NULL != other_session)
1134 if ((other_session != session) &&
1135 (0 == GNUNET_CRYPTO_hash_cmp (&session->global_id, &other_session->global_id)))
1137 if (CONSENSUS_ROUND_FINISH != other_session->current_round)
1140 destroy_session (session);
1145 other_session = other_session->next;
1148 session->conclude_deadline = GNUNET_TIME_absolute_ntoh (join_msg->deadline);
1149 session->conclude_start = GNUNET_TIME_absolute_ntoh (join_msg->start);
1151 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "consensus with timeout %ums created\n",
1152 (GNUNET_TIME_absolute_get_difference (session->conclude_start, session->conclude_deadline)).rel_value_us / 1000);
1154 session->local_peer_idx = get_peer_idx (&my_peer, session);
1155 GNUNET_assert (-1 != session->local_peer_idx);
1156 session->element_set = GNUNET_SET_create (cfg, GNUNET_SET_OPERATION_UNION);
1157 GNUNET_assert (NULL != session->element_set);
1158 session->set_listener = GNUNET_SET_listen (cfg, GNUNET_SET_OPERATION_UNION,
1159 &session->global_id,
1160 set_listen_cb, session);
1161 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "%d is the local peer\n", session->local_peer_idx);
1162 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "session %s initialized\n", GNUNET_h2s (&session->global_id));
1166 static struct ConsensusSession *
1167 get_session_by_client (struct GNUNET_SERVER_Client *client)
1169 struct ConsensusSession *session;
1171 session = sessions_head;
1172 while (NULL != session)
1174 if (session->client == client)
1176 session = session->next;
1183 * Called when a client wants to join a consensus session.
1186 * @param client client that sent the message
1187 * @param m message sent by the client
1190 client_join (void *cls,
1191 struct GNUNET_SERVER_Client *client,
1192 const struct GNUNET_MessageHeader *m)
1194 struct ConsensusSession *session;
1196 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "join message sent by client\n");
1198 session = get_session_by_client (client);
1199 if (NULL != session)
1202 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1205 session = GNUNET_new (struct ConsensusSession);
1206 session->client = client;
1207 session->client_mq = GNUNET_MQ_queue_for_server_client (client);
1208 GNUNET_CONTAINER_DLL_insert (sessions_head, sessions_tail, session);
1209 initialize_session (session, (struct GNUNET_CONSENSUS_JoinMessage *) m);
1210 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1212 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "join done\n");
1217 * Called when a client performs an insert operation.
1219 * @param cls (unused)
1220 * @param client client handle
1221 * @param m message sent by the client
1224 client_insert (void *cls,
1225 struct GNUNET_SERVER_Client *client,
1226 const struct GNUNET_MessageHeader *m)
1228 struct ConsensusSession *session;
1229 struct GNUNET_CONSENSUS_ElementMessage *msg;
1230 struct GNUNET_SET_Element *element;
1231 ssize_t element_size;
1233 session = get_session_by_client (client);
1235 if (NULL == session)
1238 GNUNET_SERVER_client_disconnect (client);
1242 if (CONSENSUS_ROUND_BEGIN != session->current_round)
1245 GNUNET_SERVER_client_disconnect (client);
1249 msg = (struct GNUNET_CONSENSUS_ElementMessage *) m;
1250 element_size = ntohs (msg->header.size) - sizeof (struct GNUNET_CONSENSUS_ElementMessage);
1251 if (element_size < 0)
1257 element = GNUNET_malloc (sizeof (struct GNUNET_SET_Element) + element_size);
1258 element->element_type = msg->element_type;
1259 element->size = element_size;
1260 memcpy (&element[1], &msg[1], element_size);
1261 element->data = &element[1];
1262 GNUNET_SET_add_element (session->element_set, element, NULL, NULL);
1263 GNUNET_free (element);
1264 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1266 // GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: element added\n", session->local_peer_idx);
1271 * Called when a client performs the conclude operation.
1273 * @param cls (unused)
1274 * @param client client handle
1275 * @param message message sent by the client
1278 client_conclude (void *cls,
1279 struct GNUNET_SERVER_Client *client,
1280 const struct GNUNET_MessageHeader *message)
1282 struct ConsensusSession *session;
1284 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "conclude requested\n");
1285 session = get_session_by_client (client);
1286 if (NULL == session)
1288 /* client not found */
1290 GNUNET_SERVER_client_disconnect (client);
1293 if (CONSENSUS_ROUND_BEGIN != session->current_round)
1295 /* client requested conclude twice */
1299 if (session->num_peers <= 1)
1301 session->current_round = CONSENSUS_ROUND_FINISH;
1302 GNUNET_SET_iterate (session->element_set, send_to_client_iter, session);
1306 /* the 'begin' round is over, start with the next, actual round */
1307 round_over (session, NULL);
1310 GNUNET_assert (CONSENSUS_ROUND_BEGIN != session->current_round);
1311 GNUNET_SERVER_receive_done (client, GNUNET_OK);
1316 * Called to clean up, after a shutdown has been requested.
1318 * @param cls closure
1319 * @param tc context information (why was this task triggered now)
1322 shutdown_task (void *cls,
1323 const struct GNUNET_SCHEDULER_TaskContext *tc)
1325 while (NULL != sessions_head)
1326 destroy_session (sessions_head);
1328 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handled shutdown request\n");
1333 * Clean up after a client after it is
1334 * disconnected (either by us or by itself)
1336 * @param cls closure, unused
1337 * @param client the client to clean up after
1340 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1342 struct ConsensusSession *session;
1344 session = get_session_by_client (client);
1345 if (NULL == session)
1347 if ((CONSENSUS_ROUND_BEGIN == session->current_round) ||
1348 (CONSENSUS_ROUND_FINISH == session->current_round))
1350 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected, destroying session\n");
1351 destroy_session (session);
1354 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "client disconnected, but waiting for consensus to finish\n");
1359 * Start processing consensus requests.
1361 * @param cls closure
1362 * @param server the initialized server
1363 * @param c configuration to use
1366 run (void *cls, struct GNUNET_SERVER_Handle *server,
1367 const struct GNUNET_CONFIGURATION_Handle *c)
1369 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
1370 {&client_conclude, NULL, GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_CONCLUDE,
1371 sizeof (struct GNUNET_MessageHeader)},
1372 {&client_insert, NULL, GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_INSERT, 0},
1373 {&client_join, NULL, GNUNET_MESSAGE_TYPE_CONSENSUS_CLIENT_JOIN, 0},
1379 if (GNUNET_OK != GNUNET_CRYPTO_get_peer_identity (cfg, &my_peer))
1381 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not retrieve host identity\n");
1383 GNUNET_SCHEDULER_shutdown ();
1386 GNUNET_SERVER_add_handlers (server, server_handlers);
1387 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task, NULL);
1388 GNUNET_SERVER_disconnect_notify (server, handle_client_disconnect, NULL);
1389 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "consensus running\n");
1394 * The main function for the consensus service.
1396 * @param argc number of arguments from the command line
1397 * @param argv command line arguments
1398 * @return 0 ok, 1 on error
1401 main (int argc, char *const *argv)
1404 ret = GNUNET_SERVICE_run (argc, argv, "consensus", GNUNET_SERVICE_OPTION_NONE, &run, NULL);
1405 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "exit (%d)\n", GNUNET_OK != ret);
1406 return (GNUNET_OK == ret) ? 0 : 1;