2 This file is part of GNUnet.
3 (C) 2013, 2014 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.
21 * @file scalarproduct/gnunet-service-scalarproduct_bob.c
22 * @brief scalarproduct service implementation
23 * @author Christian M. Fuchs
24 * @author Christian Grothoff
29 #include "gnunet_util_lib.h"
30 #include "gnunet_core_service.h"
31 #include "gnunet_cadet_service.h"
32 #include "gnunet_applications.h"
33 #include "gnunet_protocols.h"
34 #include "gnunet_scalarproduct_service.h"
35 #include "gnunet_set_service.h"
36 #include "scalarproduct.h"
37 #include "gnunet-service-scalarproduct.h"
39 #define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct-bob", __VA_ARGS__)
43 * An encrypted element key-value pair.
48 * Key used to identify matching pairs of values to multiply.
49 * Points into an existing data structure, to avoid copying
50 * and doubling memory use.
52 const struct GNUNET_HashCode *key;
55 * Value represented (a).
62 * An incoming session from CADET.
64 struct CadetIncomingSession;
68 * A scalarproduct session which tracks an offer for a
69 * multiplication service by a local client.
71 struct BobServiceSession
75 * (hopefully) unique transaction ID
77 struct GNUNET_HashCode session_id;
80 * The client this request is related to.
82 struct GNUNET_SERVER_Client *client;
85 * Client message queue.
87 struct GNUNET_MQ_Handle *client_mq;
90 * All non-0-value'd elements transmitted to us.
92 struct GNUNET_CONTAINER_MultiHashMap *intersected_elements;
95 * Set of elements for which we will be conducting an intersection.
96 * The resulting elements are then used for computing the scalar product.
98 struct GNUNET_SET_Handle *intersection_set;
101 * Set of elements for which will conduction an intersection.
102 * the resulting elements are then used for computing the scalar product.
104 struct GNUNET_SET_OperationHandle *intersection_op;
109 struct MpiElement *sorted_elements;
112 * E(ai)(Bob) after applying the mask
114 struct GNUNET_CRYPTO_PaillierCiphertext *e_a;
117 * Bob's permutation p of R
119 struct GNUNET_CRYPTO_PaillierCiphertext *r;
122 * Bob's permutation q of R
124 struct GNUNET_CRYPTO_PaillierCiphertext *r_prime;
129 struct GNUNET_CRYPTO_PaillierCiphertext s;
134 struct GNUNET_CRYPTO_PaillierCiphertext s_prime;
137 * Handle for our associated incoming CADET session, or NULL
138 * if we have not gotten one yet.
140 struct CadetIncomingSession *cadet;
143 * The computed scalar
148 * How many elements will be supplied in total from the client.
153 * Already transferred elements (received) for multipart
154 * messages from client. Always less than @e total.
156 uint32_t client_received_element_count;
159 * How many elements actually are used for the scalar product.
160 * Size of the arrays in @e r and @e r_prime. Also sometimes
161 * used as an index into the arrays during construction.
163 uint32_t used_element_count;
166 * Counts the number of values received from Alice by us.
167 * Always less than @e used_element_count.
169 uint32_t cadet_received_element_count;
172 * Counts the number of values transmitted from us to Alice.
173 * Always less than @e used_element_count.
175 uint32_t cadet_transmitted_element_count;
178 * Is this session active (#GNUNET_YES), Concluded (#GNUNET_NO), or had an error (#GNUNET_SYSERR)
183 * Are we already in #destroy_service_session()?
191 * An incoming session from CADET.
193 struct CadetIncomingSession
197 * Associated client session, or NULL.
199 struct BobServiceSession *s;
204 struct GNUNET_CADET_Channel *channel;
207 * Originator's peer identity. (Only for diagnostics.)
209 struct GNUNET_PeerIdentity peer;
212 * (hopefully) unique transaction ID
214 struct GNUNET_HashCode session_id;
217 * Public key of the remote service.
219 struct GNUNET_CRYPTO_PaillierPublicKey remote_pubkey;
222 * The message queue for this channel.
224 struct GNUNET_MQ_Handle *cadet_mq;
227 * Has this CADET session been added to the map yet?
228 * #GNUNET_YES if so, in which case @e session_id is
234 * Are we already in #destroy_cadet_session()?
242 * GNUnet configuration handle
244 static const struct GNUNET_CONFIGURATION_Handle *cfg;
247 * Service's own public key
249 static struct GNUNET_CRYPTO_PaillierPublicKey my_pubkey;
252 * Service's own private key
254 static struct GNUNET_CRYPTO_PaillierPrivateKey my_privkey;
257 * Service's offset for values that could possibly be negative but are plaintext for encryption.
259 static gcry_mpi_t my_offset;
262 * Map of `struct BobServiceSession`, by session keys.
264 static struct GNUNET_CONTAINER_MultiHashMap *client_sessions;
267 * Map of `struct CadetIncomingSession`, by session keys.
269 static struct GNUNET_CONTAINER_MultiHashMap *cadet_sessions;
272 * Handle to the CADET service.
274 static struct GNUNET_CADET_Handle *my_cadet;
279 * Finds a not terminated client session in the respective map based on
282 * @param key the session key we want to search for
283 * @return the matching session, or NULL for none
285 static struct BobServiceSession *
286 find_matching_client_session (const struct GNUNET_HashCode *key)
288 return GNUNET_CONTAINER_multihashmap_get (client_sessions,
294 * Finds a CADET session in the respective map based on session key.
296 * @param key the session key we want to search for
297 * @return the matching session, or NULL for none
299 static struct CadetIncomingSession *
300 find_matching_cadet_session (const struct GNUNET_HashCode *key)
302 return GNUNET_CONTAINER_multihashmap_get (cadet_sessions,
308 * Destroy session state, we are done with it.
310 * @param session the session to free elements from
313 destroy_cadet_session (struct CadetIncomingSession *s);
317 * Destroy session state, we are done with it.
319 * @param session the session to free elements from
322 destroy_service_session (struct BobServiceSession *s)
324 struct CadetIncomingSession *in;
327 if (GNUNET_YES == s->in_destroy)
329 s->in_destroy = GNUNET_YES;
330 if (NULL != (in = s->cadet))
333 destroy_cadet_session (in);
335 if (NULL != s->client_mq)
337 GNUNET_MQ_destroy (s->client_mq);
340 if (NULL != s->client)
342 GNUNET_SERVER_client_disconnect (s->client);
345 GNUNET_assert (GNUNET_YES ==
346 GNUNET_CONTAINER_multihashmap_remove (client_sessions,
349 if (NULL != s->intersected_elements)
351 /* FIXME: free elements */
352 GNUNET_CONTAINER_multihashmap_destroy (s->intersected_elements);
353 s->intersected_elements = NULL;
355 if (NULL != s->intersection_op)
357 GNUNET_SET_operation_cancel (s->intersection_op);
358 s->intersection_op = NULL;
360 if (NULL != s->intersection_set)
362 GNUNET_SET_destroy (s->intersection_set);
363 s->intersection_set = NULL;
367 GNUNET_free (s->e_a);
370 if (NULL != s->sorted_elements)
372 for (i=0;i<s->used_element_count;i++)
373 gcry_mpi_release (s->sorted_elements[i].value);
374 GNUNET_free (s->sorted_elements);
375 s->sorted_elements = NULL;
382 if (NULL != s->r_prime)
384 GNUNET_free (s->r_prime);
387 if (NULL != s->product)
389 gcry_mpi_release (s->product);
397 * Destroy incoming CADET session state, we are done with it.
399 * @param in the session to free elements from
402 destroy_cadet_session (struct CadetIncomingSession *in)
404 struct BobServiceSession *s;
406 if (GNUNET_YES == in->in_destroy)
408 in->in_destroy = GNUNET_YES;
409 if (NULL != (s = in->s))
412 destroy_service_session (s);
414 if (GNUNET_YES == in->in_map)
416 GNUNET_assert (GNUNET_YES ==
417 GNUNET_CONTAINER_multihashmap_remove (cadet_sessions,
420 in->in_map = GNUNET_NO;
422 if (NULL != in->cadet_mq)
424 GNUNET_MQ_destroy (in->cadet_mq);
427 if (NULL != in->channel)
429 GNUNET_CADET_channel_destroy (in->channel);
437 * Notify the client that the session has succeeded or failed. This
438 * message gets sent to Bob's client if the operation completed or
439 * Alice disconnected.
441 * @param session the associated client session to fail or succeed
444 prepare_client_end_notification (struct BobServiceSession *session)
446 struct ClientResponseMessage *msg;
447 struct GNUNET_MQ_Envelope *e;
449 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
450 "Sending session-end notification with status %d to client for session %s\n",
452 GNUNET_h2s (&session->session_id));
453 e = GNUNET_MQ_msg (msg,
454 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_RESULT);
456 msg->product_length = htonl (0);
457 msg->status = htonl (session->active);
458 GNUNET_MQ_send (session->client_mq,
464 * Function called whenever a channel is destroyed. Should clean up
465 * any associated state.
467 * It must NOT call #GNUNET_CADET_channel_destroy() on the channel.
469 * @param cls closure (set from #GNUNET_CADET_connect())
470 * @param channel connection to the other end (henceforth invalid)
471 * @param channel_ctx place where local state associated
472 * with the channel is stored
475 cb_channel_destruction (void *cls,
476 const struct GNUNET_CADET_Channel *channel,
479 struct CadetIncomingSession *in = channel_ctx;
480 struct BobServiceSession *s;
482 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
483 "Peer disconnected, terminating session %s with peer %s\n",
484 GNUNET_h2s (&in->session_id),
485 GNUNET_i2s (&in->peer));
487 if (NULL != (s = in->s))
489 if (GNUNET_YES == s->active)
491 s->active = GNUNET_SYSERR;
492 prepare_client_end_notification (s);
495 destroy_cadet_session (in);
500 * MQ finished giving our last message to CADET, now notify
501 * the client that we are finished.
504 bob_cadet_done_cb (void *cls)
506 struct BobServiceSession *session = cls;
508 session->active = GNUNET_NO; /* that means, done */
509 prepare_client_end_notification (session);
514 * Maximum count of elements we can put into a multipart message
516 #define ELEMENT_CAPACITY ((GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - sizeof (struct BobCryptodataMultipartMessage)) / sizeof (struct GNUNET_CRYPTO_PaillierCiphertext))
520 * Send a multipart chunk of a service response from Bob to Alice.
521 * This element only contains the two permutations of R, R'.
523 * @param s the associated service session
526 transmit_bobs_cryptodata_message_multipart (struct BobServiceSession *s)
528 struct GNUNET_CRYPTO_PaillierCiphertext *payload;
529 struct BobCryptodataMultipartMessage *msg;
530 struct GNUNET_MQ_Envelope *e;
535 while (s->cadet_transmitted_element_count != s->used_element_count)
537 todo_count = s->used_element_count - s->cadet_transmitted_element_count;
538 if (todo_count > ELEMENT_CAPACITY / 2)
539 todo_count = ELEMENT_CAPACITY / 2;
541 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
542 "Sending %u additional crypto values to Alice\n",
543 (unsigned int) todo_count);
544 e = GNUNET_MQ_msg_extra (msg,
545 todo_count * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * 2,
546 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_CRYPTODATA_MULTIPART);
547 msg->contained_element_count = htonl (todo_count);
548 payload = (struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
549 for (i = s->cadet_transmitted_element_count, j = 0; i < s->cadet_transmitted_element_count + todo_count; i++)
551 //r[i][p] and r[i][q]
552 memcpy (&payload[j++],
554 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
555 memcpy (&payload[j++],
557 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
559 s->cadet_transmitted_element_count += todo_count;
560 if (s->cadet_transmitted_element_count == s->used_element_count)
561 GNUNET_MQ_notify_sent (e,
564 GNUNET_MQ_send (s->cadet->cadet_mq,
571 * Bob generates the response message to be sent to Alice after
572 * computing the values (1), (2), S and S'.
574 * (1)[]: $E_A(a_{pi(i)}) times E_A(- r_{pi(i)} - b_{pi(i)}) &= E_A(a_{pi(i)} - r_{pi(i)} - b_{pi(i)})$
575 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
576 * S: $S := E_A(sum (r_i + b_i)^2)$
577 * S': $S' := E_A(sum r_i^2)$
579 * @param s the associated requesting session with Alice
582 transmit_bobs_cryptodata_message (struct BobServiceSession *s)
584 struct BobCryptodataMessage *msg;
585 struct GNUNET_MQ_Envelope *e;
586 struct GNUNET_CRYPTO_PaillierCiphertext *payload;
589 s->cadet_transmitted_element_count = (GNUNET_SERVER_MAX_MESSAGE_SIZE - 1 - sizeof (struct BobCryptodataMessage)) /
590 (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * 2) - 2;
591 if (s->cadet_transmitted_element_count > s->used_element_count)
592 s->cadet_transmitted_element_count = s->used_element_count;
594 e = GNUNET_MQ_msg_extra (msg,
595 (2 + s->cadet_transmitted_element_count * 2)
596 * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext),
597 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_CRYPTODATA);
598 msg->contained_element_count = htonl (s->cadet_transmitted_element_count);
600 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
601 "Sending %u/%u crypto values to Alice\n",
602 (unsigned int) s->cadet_transmitted_element_count,
603 (unsigned int) s->used_element_count);
605 payload = (struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
608 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
611 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
613 payload = &payload[2];
615 for (i = 0; i < s->cadet_transmitted_element_count; i++)
617 //k[i][p] and k[i][q]
618 memcpy (&payload[i * 2],
620 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
621 memcpy (&payload[i * 2 + 1],
623 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
625 if (s->cadet_transmitted_element_count == s->used_element_count)
626 GNUNET_MQ_notify_sent (e,
629 GNUNET_MQ_send (s->cadet->cadet_mq,
631 transmit_bobs_cryptodata_message_multipart (s);
636 * Computes the square sum over a vector of a given length.
638 * @param vector the vector to compute over
639 * @param length the length of the vector
640 * @return an MPI value containing the calculated sum, never NULL
641 * TODO: code duplication with Alice!
644 compute_square_sum (const gcry_mpi_t *vector,
651 GNUNET_assert (NULL != (sum = gcry_mpi_new (0)));
652 GNUNET_assert (NULL != (elem = gcry_mpi_new (0)));
653 for (i = 0; i < length; i++)
655 gcry_mpi_mul (elem, vector[i], vector[i]);
656 gcry_mpi_add (sum, sum, elem);
658 gcry_mpi_release (elem);
665 * (1)[]: $E_A(a_{pi(i)}) otimes E_A(- r_{pi(i)} - b_{pi(i)}) &= E_A(a_{pi(i)} - r_{pi(i)} - b_{pi(i)})$
666 * (2)[]: $E_A(a_{pi'(i)}) otimes E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
667 * S: $S := E_A(sum (r_i + b_i)^2)$
668 * S': $S' := E_A(sum r_i^2)$
670 * @param request the requesting session + bob's requesting peer
673 compute_service_response (struct BobServiceSession *session)
681 const struct MpiElement *b;
682 struct GNUNET_CRYPTO_PaillierCiphertext *a;
683 struct GNUNET_CRYPTO_PaillierCiphertext *r;
684 struct GNUNET_CRYPTO_PaillierCiphertext *r_prime;
686 count = session->used_element_count;
688 b = session->sorted_elements;
689 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
691 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
693 rand = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
694 for (i = 0; i < count; i++)
695 GNUNET_assert (NULL != (rand[i] = gcry_mpi_new (0)));
696 r = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * count);
697 r_prime = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * count);
699 for (i = 0; i < count; i++)
703 svalue = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
705 // long to gcry_mpi_t
707 gcry_mpi_sub_ui (rand[i],
711 rand[i] = gcry_mpi_set_ui (rand[i], svalue);
714 tmp = gcry_mpi_new (0);
715 // encrypt the element
716 // for the sake of readability I decided to have dedicated permutation
717 // vectors, which get rid of all the lookups in p/q.
718 // however, ap/aq are not absolutely necessary but are just abstraction
719 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
720 for (i = 0; i < count; i++)
722 // E(S - r_pi - b_pi)
723 gcry_mpi_sub (tmp, my_offset, rand[p[i]]);
724 gcry_mpi_sub (tmp, tmp, b[p[i]].value);
725 GNUNET_CRYPTO_paillier_encrypt (&session->cadet->remote_pubkey,
730 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
731 GNUNET_CRYPTO_paillier_hom_add (&session->cadet->remote_pubkey,
737 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
738 for (i = 0; i < count; i++)
741 gcry_mpi_sub (tmp, my_offset, rand[q[i]]);
742 GNUNET_assert (2 == GNUNET_CRYPTO_paillier_encrypt (&session->cadet->remote_pubkey,
747 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
748 GNUNET_assert (1 == GNUNET_CRYPTO_paillier_hom_add (&session->cadet->remote_pubkey,
754 // Calculate S' = E(SUM( r_i^2 ))
755 tmp = compute_square_sum (rand, count);
756 GNUNET_CRYPTO_paillier_encrypt (&session->cadet->remote_pubkey,
761 // Calculate S = E(SUM( (r_i + b_i)^2 ))
762 for (i = 0; i < count; i++)
763 gcry_mpi_add (rand[i], rand[i], b[i].value);
764 tmp = compute_square_sum (rand, count);
765 GNUNET_CRYPTO_paillier_encrypt (&session->cadet->remote_pubkey,
771 session->r_prime = r_prime;
773 // release rand, b and a
774 for (i = 0; i < count; i++)
775 gcry_mpi_release (rand[i]);
776 gcry_mpi_release (tmp);
777 GNUNET_free (session->e_a);
783 // copy the r[], r_prime[], S and Stick into a new message, prepare_service_response frees these
788 * Iterator to copy over messages from the hash map
789 * into an array for sorting.
791 * @param cls the `struct BobServiceSession *`
792 * @param key the key (unused)
793 * @param value the `struct GNUNET_SCALARPRODUCT_Element *`
794 * TODO: code duplication with Alice!
797 copy_element_cb (void *cls,
798 const struct GNUNET_HashCode *key,
801 struct BobServiceSession *s = cls;
802 struct GNUNET_SCALARPRODUCT_Element *e = value;
806 mval = gcry_mpi_new (0);
807 val = (int64_t) GNUNET_ntohll (e->value);
809 gcry_mpi_sub_ui (mval, mval, -val);
811 gcry_mpi_add_ui (mval, mval, val);
812 s->sorted_elements [s->used_element_count].value = mval;
813 s->sorted_elements [s->used_element_count].key = &e->key;
814 s->used_element_count++;
820 * Compare two `struct MpiValue`s by key for sorting.
822 * @param a pointer to first `struct MpiValue *`
823 * @param b pointer to first `struct MpiValue *`
824 * @return -1 for a < b, 0 for a=b, 1 for a > b.
825 * TODO: code duplication with Alice!
828 element_cmp (const void *a,
831 const struct MpiElement *ma = a;
832 const struct MpiElement *mb = b;
834 return GNUNET_CRYPTO_hash_cmp (ma->key,
840 * Intersection operation and receiving data via CADET from
841 * Alice are both done, compute and transmit our reply via
844 * @param s session to transmit reply for.
847 transmit_cryptographic_reply (struct BobServiceSession *s)
849 /* TODO: code duplication with Alice! */
850 LOG (GNUNET_ERROR_TYPE_DEBUG,
851 "Received everything, building reply for Alice\n");
853 = GNUNET_malloc (GNUNET_CONTAINER_multihashmap_size (s->intersected_elements) *
854 sizeof (struct MpiElement));
855 s->used_element_count = 0;
856 GNUNET_CONTAINER_multihashmap_iterate (s->intersected_elements,
859 qsort (s->sorted_elements,
860 s->used_element_count,
861 sizeof (struct MpiElement),
863 compute_service_response (s);
864 transmit_bobs_cryptodata_message (s);
869 * Handle a multipart-chunk of a request from another service to
870 * calculate a scalarproduct with us.
872 * @param cls closure (set from #GNUNET_CADET_connect)
873 * @param channel connection to the other end
874 * @param channel_ctx place to store local state associated with the @a channel
875 * @param message the actual message
876 * @return #GNUNET_OK to keep the connection open,
877 * #GNUNET_SYSERR to close it (signal serious error)
880 handle_alices_cryptodata_message (void *cls,
881 struct GNUNET_CADET_Channel *channel,
883 const struct GNUNET_MessageHeader *message)
885 struct CadetIncomingSession *in = *channel_ctx;
886 struct BobServiceSession *s;
887 const struct AliceCryptodataMessage *msg;
888 const struct GNUNET_CRYPTO_PaillierCiphertext *payload;
889 uint32_t contained_elements;
897 return GNUNET_SYSERR;
903 return GNUNET_SYSERR;
905 msize = ntohs (message->size);
906 if (msize <= sizeof (struct AliceCryptodataMessage))
909 return GNUNET_SYSERR;
911 msg = (const struct AliceCryptodataMessage *) message;
912 contained_elements = ntohl (msg->contained_element_count);
913 /* Our intersection may still be ongoing, but this is nevertheless
914 an upper bound on the required array size */
915 max = GNUNET_CONTAINER_multihashmap_size (s->intersected_elements);
916 msg_length = sizeof (struct AliceCryptodataMessage)
917 + contained_elements * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext);
918 if ( (msize != msg_length) ||
919 (0 == contained_elements) ||
920 (contained_elements > UINT16_MAX) ||
921 (max < contained_elements + s->cadet_received_element_count) )
924 return GNUNET_SYSERR;
926 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
927 "Received %u crypto values from Alice\n",
928 (unsigned int) contained_elements);
930 payload = (const struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
932 s->e_a = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) *
934 memcpy (&s->e_a[s->cadet_received_element_count],
936 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * contained_elements);
937 s->cadet_received_element_count += contained_elements;
939 if ( (s->cadet_received_element_count == max) &&
940 (NULL == s->intersection_op) )
942 /* intersection has finished also on our side, and
943 we got the full set, so we can proceed with the
945 transmit_cryptographic_reply (s);
952 * Callback for set operation results. Called for each element
953 * that needs to be removed from the result set.
955 * @param cls closure with the `struct BobServiceSession`
956 * @param element a result element, only valid if status is #GNUNET_SET_STATUS_OK
957 * @param status what has happened with the set intersection?
960 cb_intersection_element_removed (void *cls,
961 const struct GNUNET_SET_Element *element,
962 enum GNUNET_SET_Status status)
964 struct BobServiceSession *s = cls;
965 struct GNUNET_SCALARPRODUCT_Element *se;
969 case GNUNET_SET_STATUS_OK:
970 /* this element has been removed from the set */
971 se = GNUNET_CONTAINER_multihashmap_get (s->intersected_elements,
973 GNUNET_assert (NULL != se);
974 LOG (GNUNET_ERROR_TYPE_DEBUG,
975 "Removed element with key %s and value %lld\n",
976 GNUNET_h2s (&se->key),
977 (long long) GNUNET_ntohll (se->value));
978 GNUNET_assert (GNUNET_YES ==
979 GNUNET_CONTAINER_multihashmap_remove (s->intersected_elements,
984 case GNUNET_SET_STATUS_DONE:
985 s->intersection_op = NULL;
986 s->intersection_set = NULL;
987 LOG (GNUNET_ERROR_TYPE_DEBUG,
988 "Finished intersection, %d items remain\n",
989 GNUNET_CONTAINER_multihashmap_size (s->intersected_elements));
990 if (s->client_received_element_count ==
991 GNUNET_CONTAINER_multihashmap_size (s->intersected_elements))
993 /* CADET transmission from Alice is also already done,
994 start with our own reply */
995 transmit_cryptographic_reply (s);
998 case GNUNET_SET_STATUS_HALF_DONE:
999 /* unexpected for intersection */
1002 case GNUNET_SET_STATUS_FAILURE:
1003 /* unhandled status code */
1004 LOG (GNUNET_ERROR_TYPE_DEBUG,
1005 "Set intersection failed!\n");
1006 s->intersection_op = NULL;
1007 s->intersection_set = NULL;
1008 s->active = GNUNET_SYSERR;
1009 prepare_client_end_notification (s);
1019 * We've paired up a client session with an incoming CADET request.
1020 * Initiate set intersection work.
1022 * @param s client session to start intersection for
1025 start_intersection (struct BobServiceSession *s)
1027 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1028 "Got session with key %s and %u elements, starting intersection.\n",
1029 GNUNET_h2s (&s->session_id),
1030 (unsigned int) s->total);
1033 = GNUNET_SET_prepare (&s->cadet->peer,
1036 GNUNET_SET_RESULT_REMOVED,
1037 &cb_intersection_element_removed,
1039 GNUNET_SET_commit (s->intersection_op,
1040 s->intersection_set);
1045 * Handle a request from Alice to calculate a scalarproduct with us (Bob).
1047 * @param cls closure (set from #GNUNET_CADET_connect)
1048 * @param channel connection to the other end
1049 * @param channel_ctx place to store the `struct CadetIncomingSession *`
1050 * @param message the actual message
1051 * @return #GNUNET_OK to keep the connection open,
1052 * #GNUNET_SYSERR to close it (signal serious error)
1055 handle_alices_computation_request (void *cls,
1056 struct GNUNET_CADET_Channel *channel,
1058 const struct GNUNET_MessageHeader *message)
1060 struct CadetIncomingSession *in = *channel_ctx;
1061 struct BobServiceSession *s;
1062 const struct ServiceRequestMessage *msg;
1064 if (ntohs (message->size) != sizeof (struct ServiceRequestMessage))
1066 GNUNET_break_op (0);
1067 return GNUNET_SYSERR;
1069 msg = (const struct ServiceRequestMessage *) message;
1070 if (GNUNET_YES == in->in_map)
1072 GNUNET_break_op (0);
1073 return GNUNET_SYSERR;
1075 if (NULL != find_matching_cadet_session (&msg->session_id))
1077 /* not unique, got one like this already */
1078 GNUNET_break_op (0);
1079 return GNUNET_SYSERR;
1081 in->session_id = msg->session_id;
1082 in->remote_pubkey = msg->public_key;
1083 GNUNET_assert (GNUNET_YES ==
1084 GNUNET_CONTAINER_multihashmap_put (cadet_sessions,
1087 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1088 s = find_matching_client_session (&in->session_id);
1091 /* no client waiting for this request, wait for client */
1094 GNUNET_assert (NULL == s->cadet);
1098 if (s->client_received_element_count == s->total)
1099 start_intersection (s);
1105 * Function called for inbound channels on Bob's end. Does some
1106 * preliminary initialization, more happens after we get Alice's first
1109 * @param cls closure
1110 * @param channel new handle to the channel
1111 * @param initiator peer that started the channel
1112 * @param port unused
1113 * @param options unused
1114 * @return session associated with the channel
1117 cb_channel_incoming (void *cls,
1118 struct GNUNET_CADET_Channel *channel,
1119 const struct GNUNET_PeerIdentity *initiator,
1121 enum GNUNET_CADET_ChannelOption options)
1123 struct CadetIncomingSession *in;
1125 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1126 "New incoming channel from peer %s.\n",
1127 GNUNET_i2s (initiator));
1128 in = GNUNET_new (struct CadetIncomingSession);
1129 in->peer = *initiator;
1130 in->channel = channel;
1136 * We're receiving additional set data. Add it to our
1137 * set and if we are done, initiate the transaction.
1139 * @param cls closure
1140 * @param client identification of the client
1141 * @param message the actual message
1144 GSS_handle_bob_client_message_multipart (void *cls,
1145 struct GNUNET_SERVER_Client *client,
1146 const struct GNUNET_MessageHeader *message)
1148 const struct ComputationBobCryptodataMultipartMessage * msg;
1149 struct BobServiceSession *s;
1150 uint32_t contained_count;
1151 const struct GNUNET_SCALARPRODUCT_Element *elements;
1154 struct GNUNET_SET_Element set_elem;
1155 struct GNUNET_SCALARPRODUCT_Element *elem;
1157 s = GNUNET_SERVER_client_get_user_context (client,
1158 struct BobServiceSession);
1161 /* session needs to already exist */
1163 GNUNET_SERVER_receive_done (client,
1167 msize = ntohs (message->size);
1168 if (msize < sizeof (struct ComputationBobCryptodataMultipartMessage))
1171 GNUNET_SERVER_receive_done (client,
1175 msg = (const struct ComputationBobCryptodataMultipartMessage *) message;
1176 contained_count = ntohl (msg->element_count_contained);
1178 if ( (msize != (sizeof (struct ComputationBobCryptodataMultipartMessage) +
1179 contained_count * sizeof (struct GNUNET_SCALARPRODUCT_Element))) ||
1180 (0 == contained_count) ||
1181 (UINT16_MAX < contained_count) ||
1182 (s->total == s->client_received_element_count) ||
1183 (s->total < s->client_received_element_count + contained_count) )
1185 GNUNET_break_op (0);
1186 GNUNET_SERVER_receive_done (client,
1190 elements = (const struct GNUNET_SCALARPRODUCT_Element *) &msg[1];
1191 for (i = 0; i < contained_count; i++)
1193 if (0 == GNUNET_ntohll (elements[i].value))
1195 elem = GNUNET_new (struct GNUNET_SCALARPRODUCT_Element);
1198 sizeof (struct GNUNET_SCALARPRODUCT_Element));
1199 if (GNUNET_SYSERR ==
1200 GNUNET_CONTAINER_multihashmap_put (s->intersected_elements,
1203 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1209 set_elem.data = &elem->key;
1210 set_elem.size = sizeof (elem->key);
1211 set_elem.element_type = 0;
1212 GNUNET_SET_add_element (s->intersection_set,
1216 s->client_received_element_count += contained_count;
1217 GNUNET_SERVER_receive_done (client,
1219 if (s->total != s->client_received_element_count)
1224 if (NULL == s->cadet)
1226 /* no Alice waiting for this request, wait for Alice */
1229 start_intersection (s);
1234 * Handler for Bob's a client request message. Bob is in the response
1235 * role, keep the values + session and waiting for a matching session
1236 * or process a waiting request from Alice.
1238 * @param cls closure
1239 * @param client identification of the client
1240 * @param message the actual message
1243 GSS_handle_bob_client_message (void *cls,
1244 struct GNUNET_SERVER_Client *client,
1245 const struct GNUNET_MessageHeader *message)
1247 const struct BobComputationMessage *msg;
1248 struct BobServiceSession *s;
1249 struct CadetIncomingSession *in;
1250 uint32_t contained_count;
1251 uint32_t total_count;
1252 const struct GNUNET_SCALARPRODUCT_Element *elements;
1254 struct GNUNET_SET_Element set_elem;
1255 struct GNUNET_SCALARPRODUCT_Element *elem;
1258 s = GNUNET_SERVER_client_get_user_context (client,
1259 struct BobServiceSession);
1262 /* only one concurrent session per client connection allowed,
1263 simplifies logic a lot... */
1265 GNUNET_SERVER_receive_done (client,
1269 msize = ntohs (message->size);
1270 if (msize < sizeof (struct BobComputationMessage))
1273 GNUNET_SERVER_receive_done (client,
1277 msg = (const struct BobComputationMessage *) message;
1278 total_count = ntohl (msg->element_count_total);
1279 contained_count = ntohl (msg->element_count_contained);
1280 if ( (0 == total_count) ||
1281 (0 == contained_count) ||
1282 (UINT16_MAX < contained_count) ||
1283 (msize != (sizeof (struct BobComputationMessage) +
1284 contained_count * sizeof (struct GNUNET_SCALARPRODUCT_Element))) )
1286 GNUNET_break_op (0);
1287 GNUNET_SERVER_receive_done (client,
1291 if (NULL != find_matching_client_session (&msg->session_key))
1294 GNUNET_SERVER_receive_done (client,
1299 s = GNUNET_new (struct BobServiceSession);
1300 s->active = GNUNET_YES;
1302 s->client_mq = GNUNET_MQ_queue_for_server_client (client);
1303 s->total = total_count;
1304 s->client_received_element_count = contained_count;
1305 s->session_id = msg->session_key;
1306 GNUNET_break (GNUNET_YES ==
1307 GNUNET_CONTAINER_multihashmap_put (client_sessions,
1310 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1311 elements = (const struct GNUNET_SCALARPRODUCT_Element *) &msg[1];
1312 s->intersected_elements = GNUNET_CONTAINER_multihashmap_create (s->total,
1314 s->intersection_set = GNUNET_SET_create (cfg,
1315 GNUNET_SET_OPERATION_INTERSECTION);
1316 for (i = 0; i < contained_count; i++)
1318 if (0 == GNUNET_ntohll (elements[i].value))
1320 elem = GNUNET_new (struct GNUNET_SCALARPRODUCT_Element);
1323 sizeof (struct GNUNET_SCALARPRODUCT_Element));
1324 if (GNUNET_SYSERR ==
1325 GNUNET_CONTAINER_multihashmap_put (s->intersected_elements,
1328 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1334 set_elem.data = &elem->key;
1335 set_elem.size = sizeof (elem->key);
1336 set_elem.element_type = 0;
1337 GNUNET_SET_add_element (s->intersection_set,
1340 s->used_element_count++;
1342 GNUNET_SERVER_client_set_user_context (client,
1344 GNUNET_SERVER_receive_done (client,
1346 if (s->total != s->client_received_element_count)
1351 in = find_matching_cadet_session (&s->session_id);
1354 /* nothing yet, wait for Alice */
1357 GNUNET_assert (NULL == in->s);
1361 start_intersection (s);
1366 * Task run during shutdown.
1372 shutdown_task (void *cls,
1373 const struct GNUNET_SCHEDULER_TaskContext *tc)
1375 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1376 "Shutting down, initiating cleanup.\n");
1377 // FIXME: do we have to cut our connections to CADET first?
1378 if (NULL != my_cadet)
1380 GNUNET_CADET_disconnect (my_cadet);
1383 GNUNET_CONTAINER_multihashmap_destroy (client_sessions);
1384 client_sessions = NULL;
1385 GNUNET_CONTAINER_multihashmap_destroy (cadet_sessions);
1386 cadet_sessions = NULL;
1391 * A client disconnected.
1393 * Remove the associated session(s), release data structures
1394 * and cancel pending outgoing transmissions to the client.
1396 * @param cls closure, NULL
1397 * @param client identification of the client
1400 handle_client_disconnect (void *cls,
1401 struct GNUNET_SERVER_Client *client)
1403 struct BobServiceSession *s;
1407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1408 "Client disconnected from us.\n",
1410 s = GNUNET_SERVER_client_get_user_context (client,
1411 struct BobServiceSession);
1415 destroy_service_session (s);
1420 * Initialization of the program and message handlers
1422 * @param cls closure
1423 * @param server the initialized server
1424 * @param c configuration to use
1428 struct GNUNET_SERVER_Handle *server,
1429 const struct GNUNET_CONFIGURATION_Handle *c)
1431 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
1432 { &GSS_handle_bob_client_message, NULL,
1433 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB,
1435 { &GSS_handle_bob_client_message_multipart, NULL,
1436 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_MUTLIPART_BOB,
1440 static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1441 { &handle_alices_computation_request,
1442 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SESSION_INITIALIZATION,
1443 sizeof (struct ServiceRequestMessage) },
1444 { &handle_alices_cryptodata_message,
1445 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_CRYPTODATA,
1449 static const uint32_t ports[] = {
1450 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1456 offset has to be sufficiently small to allow computation of:
1457 m1+m2 mod n == (S + a) + (S + b) mod n,
1458 if we have more complex operations, this factor needs to be lowered */
1459 my_offset = gcry_mpi_new (GNUNET_CRYPTO_PAILLIER_BITS / 3);
1460 gcry_mpi_set_bit (my_offset,
1461 GNUNET_CRYPTO_PAILLIER_BITS / 3);
1463 GNUNET_CRYPTO_paillier_create (&my_pubkey,
1465 GNUNET_SERVER_add_handlers (server,
1467 GNUNET_SERVER_disconnect_notify (server,
1468 &handle_client_disconnect,
1470 client_sessions = GNUNET_CONTAINER_multihashmap_create (128,
1472 cadet_sessions = GNUNET_CONTAINER_multihashmap_create (128,
1474 my_cadet = GNUNET_CADET_connect (cfg, NULL,
1475 &cb_channel_incoming,
1476 &cb_channel_destruction,
1479 if (NULL == my_cadet)
1481 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1482 _("Connect to CADET failed\n"));
1483 GNUNET_SCHEDULER_shutdown ();
1486 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
1493 * The main function for the scalarproduct service.
1495 * @param argc number of arguments from the command line
1496 * @param argv command line arguments
1497 * @return 0 ok, 1 on error
1503 return (GNUNET_OK ==
1504 GNUNET_SERVICE_run (argc, argv,
1505 "scalarproduct-bob",
1506 GNUNET_SERVICE_OPTION_NONE,
1507 &run, NULL)) ? 0 : 1;
1510 /* end of gnunet-service-scalarproduct_bob.c */