2 This file is part of GNUnet.
3 Copyright (C) 2013, 2014, 2016 GNUnet e.V.
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., 51 Franklin Street, Fifth Floor,
18 Boston, MA 02110-1301, 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_SERVICE_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;
107 * CADET port we are listening on.
109 struct GNUNET_CADET_Port *port;
114 struct MpiElement *sorted_elements;
117 * E(ai)(Bob) after applying the mask
119 struct GNUNET_CRYPTO_PaillierCiphertext *e_a;
122 * Bob's permutation p of R
124 struct GNUNET_CRYPTO_PaillierCiphertext *r;
127 * Bob's permutation q of R
129 struct GNUNET_CRYPTO_PaillierCiphertext *r_prime;
134 struct GNUNET_CRYPTO_PaillierCiphertext s;
139 struct GNUNET_CRYPTO_PaillierCiphertext s_prime;
142 * Handle for our associated incoming CADET session, or NULL
143 * if we have not gotten one yet.
145 struct CadetIncomingSession *cadet;
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 * State of this session. In
179 * #GNUNET_SCALARPRODUCT_STATUS_ACTIVE while operation is
180 * ongoing, afterwards in #GNUNET_SCALARPRODUCT_STATUS_SUCCESS or
181 * #GNUNET_SCALARPRODUCT_STATUS_FAILURE.
183 enum GNUNET_SCALARPRODUCT_ResponseStatus status;
186 * Are we already in #destroy_service_session()?
194 * An incoming session from CADET.
196 struct CadetIncomingSession
200 * Associated client session, or NULL.
202 struct BobServiceSession *s;
207 struct GNUNET_CADET_Channel *channel;
210 * Originator's peer identity. (Only for diagnostics.)
212 struct GNUNET_PeerIdentity peer;
215 * (hopefully) unique transaction ID
217 struct GNUNET_HashCode session_id;
220 * Public key of the remote service.
222 struct GNUNET_CRYPTO_PaillierPublicKey remote_pubkey;
225 * The message queue for this channel.
227 struct GNUNET_MQ_Handle *cadet_mq;
230 * Has this CADET session been added to the map yet?
231 * #GNUNET_YES if so, in which case @e session_id is
237 * Are we already in #destroy_cadet_session()?
245 * GNUnet configuration handle
247 static const struct GNUNET_CONFIGURATION_Handle *cfg;
250 * Service's own public key
252 static struct GNUNET_CRYPTO_PaillierPublicKey my_pubkey;
255 * Service's own private key
257 static struct GNUNET_CRYPTO_PaillierPrivateKey my_privkey;
260 * Service's offset for values that could possibly be negative but are plaintext for encryption.
262 static gcry_mpi_t my_offset;
265 * Map of `struct BobServiceSession`, by session keys.
267 static struct GNUNET_CONTAINER_MultiHashMap *client_sessions;
270 * Map of `struct CadetIncomingSession`, by session keys.
272 static struct GNUNET_CONTAINER_MultiHashMap *cadet_sessions;
275 * Handle to the CADET service.
277 static struct GNUNET_CADET_Handle *my_cadet;
282 * Finds a not terminated client session in the respective map based on
285 * @param key the session key we want to search for
286 * @return the matching session, or NULL for none
288 static struct BobServiceSession *
289 find_matching_client_session (const struct GNUNET_HashCode *key)
291 return GNUNET_CONTAINER_multihashmap_get (client_sessions,
297 * Finds a CADET session in the respective map based on session key.
299 * @param key the session key we want to search for
300 * @return the matching session, or NULL for none
302 static struct CadetIncomingSession *
303 find_matching_cadet_session (const struct GNUNET_HashCode *key)
305 return GNUNET_CONTAINER_multihashmap_get (cadet_sessions,
311 * Callback used to free the elements in the map.
314 * @param key key of the element
315 * @param value the value to free
318 free_element_cb (void *cls,
319 const struct GNUNET_HashCode *key,
322 struct GNUNET_SCALARPRODUCT_Element *element = value;
324 GNUNET_free (element);
330 * Destroy session state, we are done with it.
332 * @param session the session to free elements from
335 destroy_cadet_session (struct CadetIncomingSession *s);
339 * Destroy session state, we are done with it.
341 * @param session the session to free elements from
344 destroy_service_session (struct BobServiceSession *s)
346 struct CadetIncomingSession *in;
349 if (GNUNET_YES == s->in_destroy)
351 s->in_destroy = GNUNET_YES;
352 if (NULL != (in = s->cadet))
355 destroy_cadet_session (in);
357 if (NULL != s->client)
359 struct GNUNET_SERVICE_Client *c = s->client;
362 GNUNET_SERVICE_client_drop (c);
364 GNUNET_assert (GNUNET_YES ==
365 GNUNET_CONTAINER_multihashmap_remove (client_sessions,
368 if (NULL != s->intersected_elements)
370 GNUNET_CONTAINER_multihashmap_iterate (s->intersected_elements,
373 GNUNET_CONTAINER_multihashmap_destroy (s->intersected_elements);
374 s->intersected_elements = NULL;
376 if (NULL != s->intersection_op)
378 GNUNET_SET_operation_cancel (s->intersection_op);
379 s->intersection_op = NULL;
381 if (NULL != s->intersection_set)
383 GNUNET_SET_destroy (s->intersection_set);
384 s->intersection_set = NULL;
388 GNUNET_free (s->e_a);
391 if (NULL != s->sorted_elements)
393 for (i=0;i<s->used_element_count;i++)
394 gcry_mpi_release (s->sorted_elements[i].value);
395 GNUNET_free (s->sorted_elements);
396 s->sorted_elements = NULL;
403 if (NULL != s->r_prime)
405 GNUNET_free (s->r_prime);
408 GNUNET_CADET_close_port (s->port);
414 * Destroy incoming CADET session state, we are done with it.
416 * @param in the session to free elements from
419 destroy_cadet_session (struct CadetIncomingSession *in)
421 struct BobServiceSession *s;
423 if (GNUNET_YES == in->in_destroy)
425 in->in_destroy = GNUNET_YES;
426 if (NULL != (s = in->s))
429 destroy_service_session (s);
431 if (GNUNET_YES == in->in_map)
433 GNUNET_assert (GNUNET_YES ==
434 GNUNET_CONTAINER_multihashmap_remove (cadet_sessions,
437 in->in_map = GNUNET_NO;
439 if (NULL != in->cadet_mq)
441 GNUNET_MQ_destroy (in->cadet_mq);
444 if (NULL != in->channel)
446 GNUNET_CADET_channel_destroy (in->channel);
454 * Notify the client that the session has succeeded or failed. This
455 * message gets sent to Bob's client if the operation completed or
456 * Alice disconnected.
458 * @param session the associated client session to fail or succeed
461 prepare_client_end_notification (struct BobServiceSession *session)
463 struct ClientResponseMessage *msg;
464 struct GNUNET_MQ_Envelope *e;
466 if (NULL == session->client_mq)
467 return; /* no client left to be notified */
468 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
469 "Sending session-end notification with status %d to client for session %s\n",
471 GNUNET_h2s (&session->session_id));
472 e = GNUNET_MQ_msg (msg,
473 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_RESULT);
475 msg->product_length = htonl (0);
476 msg->status = htonl (session->status);
477 GNUNET_MQ_send (session->client_mq,
483 * Function called whenever a channel is destroyed. Should clean up
484 * any associated state.
486 * It must NOT call #GNUNET_CADET_channel_destroy() on the channel.
488 * @param cls closure (set from #GNUNET_CADET_connect())
489 * @param channel connection to the other end (henceforth invalid)
490 * @param channel_ctx place where local state associated
491 * with the channel is stored
494 cb_channel_destruction (void *cls,
495 const struct GNUNET_CADET_Channel *channel,
498 struct CadetIncomingSession *in = channel_ctx;
499 struct BobServiceSession *s;
501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
502 "Peer disconnected, terminating session %s with peer %s\n",
503 GNUNET_h2s (&in->session_id),
504 GNUNET_i2s (&in->peer));
505 if (NULL != (s = in->s))
507 if (GNUNET_SCALARPRODUCT_STATUS_ACTIVE == s->status)
509 s->status = GNUNET_SCALARPRODUCT_STATUS_FAILURE;
510 prepare_client_end_notification (s);
513 if (NULL != in->cadet_mq)
515 GNUNET_MQ_destroy (in->cadet_mq);
519 destroy_cadet_session (in);
524 * MQ finished giving our last message to CADET, now notify
525 * the client that we are finished.
528 bob_cadet_done_cb (void *cls)
530 struct BobServiceSession *session = cls;
532 session->status = GNUNET_SCALARPRODUCT_STATUS_SUCCESS;
533 prepare_client_end_notification (session);
538 * Maximum count of elements we can put into a multipart message
540 #define ELEMENT_CAPACITY ((GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE - 1 - sizeof (struct BobCryptodataMultipartMessage)) / sizeof (struct GNUNET_CRYPTO_PaillierCiphertext))
544 * Send a multipart chunk of a service response from Bob to Alice.
545 * This element only contains the two permutations of R, R'.
547 * @param s the associated service session
550 transmit_bobs_cryptodata_message_multipart (struct BobServiceSession *s)
552 struct GNUNET_CRYPTO_PaillierCiphertext *payload;
553 struct BobCryptodataMultipartMessage *msg;
554 struct GNUNET_MQ_Envelope *e;
559 while (s->cadet_transmitted_element_count != s->used_element_count)
561 todo_count = s->used_element_count - s->cadet_transmitted_element_count;
562 if (todo_count > ELEMENT_CAPACITY / 2)
563 todo_count = ELEMENT_CAPACITY / 2;
565 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
566 "Sending %u additional crypto values to Alice\n",
567 (unsigned int) todo_count);
568 e = GNUNET_MQ_msg_extra (msg,
569 todo_count * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * 2,
570 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_CRYPTODATA_MULTIPART);
571 msg->contained_element_count = htonl (todo_count);
572 payload = (struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
573 for (i = s->cadet_transmitted_element_count, j = 0; i < s->cadet_transmitted_element_count + todo_count; i++)
575 //r[i][p] and r[i][q]
576 GNUNET_memcpy (&payload[j++],
578 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
579 GNUNET_memcpy (&payload[j++],
581 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
583 s->cadet_transmitted_element_count += todo_count;
584 if (s->cadet_transmitted_element_count == s->used_element_count)
585 GNUNET_MQ_notify_sent (e,
588 GNUNET_MQ_send (s->cadet->cadet_mq,
591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
592 "All values queued for Alice, Bob is done\n");
597 * Bob generates the response message to be sent to Alice after
598 * computing the values (1), (2), S and S'.
600 * (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)})$
601 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
602 * S: $S := E_A(sum (r_i + b_i)^2)$
603 * S': $S' := E_A(sum r_i^2)$
605 * @param s the associated requesting session with Alice
608 transmit_bobs_cryptodata_message (struct BobServiceSession *s)
610 struct BobCryptodataMessage *msg;
611 struct GNUNET_MQ_Envelope *e;
612 struct GNUNET_CRYPTO_PaillierCiphertext *payload;
615 s->cadet_transmitted_element_count
616 = ((GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE - 1 - sizeof (struct BobCryptodataMessage))
617 / sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) / 2) - 1;
618 if (s->cadet_transmitted_element_count > s->used_element_count)
619 s->cadet_transmitted_element_count = s->used_element_count;
621 e = GNUNET_MQ_msg_extra (msg,
622 (2 + s->cadet_transmitted_element_count * 2)
623 * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext),
624 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_CRYPTODATA);
625 msg->contained_element_count = htonl (s->cadet_transmitted_element_count);
627 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
628 "Sending %u/%u crypto values to Alice\n",
629 (unsigned int) s->cadet_transmitted_element_count,
630 (unsigned int) s->used_element_count);
632 payload = (struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
633 GNUNET_memcpy (&payload[0],
635 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
636 GNUNET_memcpy (&payload[1],
638 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
640 payload = &payload[2];
642 for (i = 0; i < s->cadet_transmitted_element_count; i++)
644 //k[i][p] and k[i][q]
645 GNUNET_memcpy (&payload[i * 2],
647 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
648 GNUNET_memcpy (&payload[i * 2 + 1],
650 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
652 if (s->cadet_transmitted_element_count == s->used_element_count)
653 GNUNET_MQ_notify_sent (e,
656 GNUNET_MQ_send (s->cadet->cadet_mq,
658 transmit_bobs_cryptodata_message_multipart (s);
660 #undef ELEMENT_CAPACITY
664 * Computes the square sum over a vector of a given length.
666 * @param vector the vector to compute over
667 * @param length the length of the vector
668 * @return an MPI value containing the calculated sum, never NULL
669 * TODO: code duplication with Alice!
672 compute_square_sum (const gcry_mpi_t *vector,
679 GNUNET_assert (NULL != (sum = gcry_mpi_new (0)));
680 GNUNET_assert (NULL != (elem = gcry_mpi_new (0)));
681 for (i = 0; i < length; i++)
683 gcry_mpi_mul (elem, vector[i], vector[i]);
684 gcry_mpi_add (sum, sum, elem);
686 gcry_mpi_release (elem);
693 * (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)})$
694 * (2)[]: $E_A(a_{pi'(i)}) otimes E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
695 * S: $S := E_A(sum (r_i + b_i)^2)$
696 * S': $S' := E_A(sum r_i^2)$
698 * @param request the requesting session + bob's requesting peer
699 * @return #GNUNET_OK on success
702 compute_service_response (struct BobServiceSession *session)
710 const struct MpiElement *b;
711 struct GNUNET_CRYPTO_PaillierCiphertext *a;
712 struct GNUNET_CRYPTO_PaillierCiphertext *r;
713 struct GNUNET_CRYPTO_PaillierCiphertext *r_prime;
715 count = session->used_element_count;
717 b = session->sorted_elements;
718 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
720 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
722 rand = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
723 for (i = 0; i < count; i++)
724 GNUNET_assert (NULL != (rand[i] = gcry_mpi_new (0)));
725 r = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * count);
726 r_prime = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * count);
728 for (i = 0; i < count; i++)
732 svalue = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
734 // long to gcry_mpi_t
736 gcry_mpi_sub_ui (rand[i],
740 rand[i] = gcry_mpi_set_ui (rand[i], svalue);
743 tmp = gcry_mpi_new (0);
744 // encrypt the element
745 // for the sake of readability I decided to have dedicated permutation
746 // vectors, which get rid of all the lookups in p/q.
747 // however, ap/aq are not absolutely necessary but are just abstraction
748 // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
749 for (i = 0; i < count; i++)
751 // E(S - r_pi - b_pi)
752 gcry_mpi_sub (tmp, my_offset, rand[p[i]]);
753 gcry_mpi_sub (tmp, tmp, b[p[i]].value);
755 GNUNET_CRYPTO_paillier_encrypt (&session->cadet->remote_pubkey,
760 // E(S - r_pi - b_pi) * E(S + a_pi) == E(2*S + a - r - b)
762 GNUNET_CRYPTO_paillier_hom_add (&session->cadet->remote_pubkey,
772 // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
773 for (i = 0; i < count; i++)
776 gcry_mpi_sub (tmp, my_offset, rand[q[i]]);
778 GNUNET_CRYPTO_paillier_encrypt (&session->cadet->remote_pubkey,
783 // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
785 GNUNET_CRYPTO_paillier_hom_add (&session->cadet->remote_pubkey,
794 gcry_mpi_release (tmp);
796 // Calculate S' = E(SUM( r_i^2 ))
797 tmp = compute_square_sum (rand, count);
799 GNUNET_CRYPTO_paillier_encrypt (&session->cadet->remote_pubkey,
803 gcry_mpi_release (tmp);
805 // Calculate S = E(SUM( (r_i + b_i)^2 ))
806 for (i = 0; i < count; i++)
807 gcry_mpi_add (rand[i], rand[i], b[i].value);
808 tmp = compute_square_sum (rand, count);
810 GNUNET_CRYPTO_paillier_encrypt (&session->cadet->remote_pubkey,
814 gcry_mpi_release (tmp);
817 session->r_prime = r_prime;
819 for (i = 0; i < count; i++)
820 gcry_mpi_release (rand[i]);
821 GNUNET_free (session->e_a);
830 GNUNET_free (r_prime);
831 gcry_mpi_release (tmp);
834 for (i = 0; i < count; i++)
835 gcry_mpi_release (rand[i]);
837 return GNUNET_SYSERR;
842 * Iterator to copy over messages from the hash map
843 * into an array for sorting.
845 * @param cls the `struct BobServiceSession *`
846 * @param key the key (unused)
847 * @param value the `struct GNUNET_SCALARPRODUCT_Element *`
848 * TODO: code duplication with Alice!
851 copy_element_cb (void *cls,
852 const struct GNUNET_HashCode *key,
855 struct BobServiceSession *s = cls;
856 struct GNUNET_SCALARPRODUCT_Element *e = value;
860 mval = gcry_mpi_new (0);
861 val = (int64_t) GNUNET_ntohll (e->value);
863 gcry_mpi_sub_ui (mval, mval, -val);
865 gcry_mpi_add_ui (mval, mval, val);
866 s->sorted_elements [s->used_element_count].value = mval;
867 s->sorted_elements [s->used_element_count].key = &e->key;
868 s->used_element_count++;
874 * Compare two `struct MpiValue`s by key for sorting.
876 * @param a pointer to first `struct MpiValue *`
877 * @param b pointer to first `struct MpiValue *`
878 * @return -1 for a < b, 0 for a=b, 1 for a > b.
879 * TODO: code duplication with Alice!
882 element_cmp (const void *a,
885 const struct MpiElement *ma = a;
886 const struct MpiElement *mb = b;
888 return GNUNET_CRYPTO_hash_cmp (ma->key,
894 * Intersection operation and receiving data via CADET from
895 * Alice are both done, compute and transmit our reply via
898 * @param s session to transmit reply for.
901 transmit_cryptographic_reply (struct BobServiceSession *s)
903 struct GNUNET_CADET_Channel *channel;
905 /* TODO: code duplication with Alice! */
906 LOG (GNUNET_ERROR_TYPE_DEBUG,
907 "Received everything, building reply for Alice\n");
909 = GNUNET_malloc (GNUNET_CONTAINER_multihashmap_size (s->intersected_elements) *
910 sizeof (struct MpiElement));
911 s->used_element_count = 0;
912 GNUNET_CONTAINER_multihashmap_iterate (s->intersected_elements,
915 qsort (s->sorted_elements,
916 s->used_element_count,
917 sizeof (struct MpiElement),
920 compute_service_response (s))
922 channel = s->cadet->channel;
923 s->cadet->channel = NULL;
924 GNUNET_CADET_channel_destroy (channel);
927 transmit_bobs_cryptodata_message (s);
932 * Handle a multipart-chunk of a request from another service to
933 * calculate a scalarproduct with us.
935 * @param cls closure (set from #GNUNET_CADET_connect)
936 * @param channel connection to the other end
937 * @param channel_ctx place to store local state associated with the @a channel
938 * @param message the actual message
939 * @return #GNUNET_OK to keep the connection open,
940 * #GNUNET_SYSERR to close it (signal serious error)
943 handle_alices_cryptodata_message (void *cls,
944 struct GNUNET_CADET_Channel *channel,
946 const struct GNUNET_MessageHeader *message)
948 struct CadetIncomingSession *in = *channel_ctx;
949 struct BobServiceSession *s;
950 const struct AliceCryptodataMessage *msg;
951 const struct GNUNET_CRYPTO_PaillierCiphertext *payload;
952 uint32_t contained_elements;
960 return GNUNET_SYSERR;
966 return GNUNET_SYSERR;
968 msize = ntohs (message->size);
969 if (msize <= sizeof (struct AliceCryptodataMessage))
972 return GNUNET_SYSERR;
974 msg = (const struct AliceCryptodataMessage *) message;
975 contained_elements = ntohl (msg->contained_element_count);
976 /* Our intersection may still be ongoing, but this is nevertheless
977 an upper bound on the required array size */
978 max = GNUNET_CONTAINER_multihashmap_size (s->intersected_elements);
979 msg_length = sizeof (struct AliceCryptodataMessage)
980 + contained_elements * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext);
981 if ( (msize != msg_length) ||
982 (0 == contained_elements) ||
983 (contained_elements > UINT16_MAX) ||
984 (max < contained_elements + s->cadet_received_element_count) )
987 return GNUNET_SYSERR;
989 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
990 "Received %u crypto values from Alice\n",
991 (unsigned int) contained_elements);
993 payload = (const struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
995 s->e_a = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) *
997 GNUNET_memcpy (&s->e_a[s->cadet_received_element_count],
999 sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * contained_elements);
1000 s->cadet_received_element_count += contained_elements;
1002 if ( (s->cadet_received_element_count == max) &&
1003 (NULL == s->intersection_op) )
1005 /* intersection has finished also on our side, and
1006 we got the full set, so we can proceed with the
1007 CADET response(s) */
1008 transmit_cryptographic_reply (s);
1010 GNUNET_CADET_receive_done (s->cadet->channel);
1016 * Callback for set operation results. Called for each element
1017 * that needs to be removed from the result set.
1019 * @param cls closure with the `struct BobServiceSession`
1020 * @param element a result element, only valid if status is #GNUNET_SET_STATUS_OK
1021 * @param status what has happened with the set intersection?
1024 cb_intersection_element_removed (void *cls,
1025 const struct GNUNET_SET_Element *element,
1026 enum GNUNET_SET_Status status)
1028 struct BobServiceSession *s = cls;
1029 struct GNUNET_SCALARPRODUCT_Element *se;
1033 case GNUNET_SET_STATUS_OK:
1034 /* this element has been removed from the set */
1035 se = GNUNET_CONTAINER_multihashmap_get (s->intersected_elements,
1037 GNUNET_assert (NULL != se);
1038 LOG (GNUNET_ERROR_TYPE_DEBUG,
1039 "Removed element with key %s and value %lld\n",
1040 GNUNET_h2s (&se->key),
1041 (long long) GNUNET_ntohll (se->value));
1042 GNUNET_assert (GNUNET_YES ==
1043 GNUNET_CONTAINER_multihashmap_remove (s->intersected_elements,
1048 case GNUNET_SET_STATUS_DONE:
1049 s->intersection_op = NULL;
1050 GNUNET_break (NULL == s->intersection_set);
1051 GNUNET_CADET_receive_done (s->cadet->channel);
1052 LOG (GNUNET_ERROR_TYPE_DEBUG,
1053 "Finished intersection, %d items remain\n",
1054 GNUNET_CONTAINER_multihashmap_size (s->intersected_elements));
1055 if (s->client_received_element_count ==
1056 GNUNET_CONTAINER_multihashmap_size (s->intersected_elements))
1058 /* CADET transmission from Alice is also already done,
1059 start with our own reply */
1060 transmit_cryptographic_reply (s);
1063 case GNUNET_SET_STATUS_HALF_DONE:
1064 /* unexpected for intersection */
1067 case GNUNET_SET_STATUS_FAILURE:
1068 /* unhandled status code */
1069 LOG (GNUNET_ERROR_TYPE_DEBUG,
1070 "Set intersection failed!\n");
1071 s->intersection_op = NULL;
1072 if (NULL != s->intersection_set)
1074 GNUNET_SET_destroy (s->intersection_set);
1075 s->intersection_set = NULL;
1077 s->status = GNUNET_SCALARPRODUCT_STATUS_FAILURE;
1078 prepare_client_end_notification (s);
1088 * We've paired up a client session with an incoming CADET request.
1089 * Initiate set intersection work.
1091 * @param s client session to start intersection for
1094 start_intersection (struct BobServiceSession *s)
1096 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1097 "Got session with key %s and %u elements, starting intersection.\n",
1098 GNUNET_h2s (&s->session_id),
1099 (unsigned int) s->total);
1102 = GNUNET_SET_prepare (&s->cadet->peer,
1105 GNUNET_SET_RESULT_REMOVED,
1106 &cb_intersection_element_removed,
1109 GNUNET_SET_commit (s->intersection_op,
1110 s->intersection_set))
1113 s->status = GNUNET_SCALARPRODUCT_STATUS_FAILURE;
1114 prepare_client_end_notification (s);
1117 GNUNET_SET_destroy (s->intersection_set);
1118 s->intersection_set = NULL;
1123 * Handle a request from Alice to calculate a scalarproduct with us (Bob).
1125 * @param cls closure (set from #GNUNET_CADET_connect)
1126 * @param channel connection to the other end
1127 * @param channel_ctx place to store the `struct CadetIncomingSession *`
1128 * @param message the actual message
1129 * @return #GNUNET_OK to keep the connection open,
1130 * #GNUNET_SYSERR to close it (signal serious error)
1133 handle_alices_computation_request (void *cls,
1134 struct GNUNET_CADET_Channel *channel,
1136 const struct GNUNET_MessageHeader *message)
1138 struct CadetIncomingSession *in = *channel_ctx;
1139 struct BobServiceSession *s;
1140 const struct ServiceRequestMessage *msg;
1142 msg = (const struct ServiceRequestMessage *) message;
1143 if (GNUNET_YES == in->in_map)
1145 GNUNET_break_op (0);
1146 return GNUNET_SYSERR;
1148 if (NULL != find_matching_cadet_session (&msg->session_id))
1150 /* not unique, got one like this already */
1151 GNUNET_break_op (0);
1152 return GNUNET_SYSERR;
1154 in->session_id = msg->session_id;
1155 in->remote_pubkey = msg->public_key;
1156 GNUNET_assert (GNUNET_YES ==
1157 GNUNET_CONTAINER_multihashmap_put (cadet_sessions,
1160 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1161 s = find_matching_client_session (&in->session_id);
1164 /* no client waiting for this request, wait for client */
1167 GNUNET_assert (NULL == s->cadet);
1171 if (s->client_received_element_count == s->total)
1172 start_intersection (s);
1178 * Function called for inbound channels on Bob's end. Does some
1179 * preliminary initialization, more happens after we get Alice's first
1182 * @param cls closure with the `struct BobServiceSession`
1183 * @param channel new handle to the channel
1184 * @param initiator peer that started the channel
1185 * @param port unused
1186 * @param options unused
1187 * @return session associated with the channel
1190 cb_channel_incoming (void *cls,
1191 struct GNUNET_CADET_Channel *channel,
1192 const struct GNUNET_PeerIdentity *initiator,
1193 const struct GNUNET_HashCode *port,
1194 enum GNUNET_CADET_ChannelOption options)
1196 struct CadetIncomingSession *in;
1198 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1199 "New incoming channel from peer %s.\n",
1200 GNUNET_i2s (initiator));
1201 in = GNUNET_new (struct CadetIncomingSession);
1202 in->peer = *initiator;
1203 in->channel = channel;
1204 in->cadet_mq = GNUNET_CADET_mq_create (in->channel);
1211 * We're receiving additional set data. Check it is well-formed.
1213 * @param cls identification of the client
1214 * @param msg the actual message
1215 * @return #GNUNET_OK if @a msg is well-formed
1218 check_bob_client_message_multipart (void *cls,
1219 const struct ComputationBobCryptodataMultipartMessage *msg)
1221 struct BobServiceSession *s = cls;
1222 uint32_t contained_count;
1225 msize = ntohs (msg->header.size);
1226 contained_count = ntohl (msg->element_count_contained);
1227 if ( (msize != (sizeof (struct ComputationBobCryptodataMultipartMessage) +
1228 contained_count * sizeof (struct GNUNET_SCALARPRODUCT_Element))) ||
1229 (0 == contained_count) ||
1230 (UINT16_MAX < contained_count) ||
1231 (s->total == s->client_received_element_count) ||
1232 (s->total < s->client_received_element_count + contained_count) )
1235 return GNUNET_SYSERR;
1242 * We're receiving additional set data. Add it to our
1243 * set and if we are done, initiate the transaction.
1245 * @param cls identification of the client
1246 * @param msg the actual message
1249 handle_bob_client_message_multipart (void *cls,
1250 const struct ComputationBobCryptodataMultipartMessage *msg)
1252 struct BobServiceSession *s = cls;
1253 uint32_t contained_count;
1254 const struct GNUNET_SCALARPRODUCT_Element *elements;
1255 struct GNUNET_SET_Element set_elem;
1256 struct GNUNET_SCALARPRODUCT_Element *elem;
1258 contained_count = ntohl (msg->element_count_contained);
1259 elements = (const struct GNUNET_SCALARPRODUCT_Element *) &msg[1];
1260 for (uint32_t i = 0; i < contained_count; i++)
1262 elem = GNUNET_new (struct GNUNET_SCALARPRODUCT_Element);
1263 GNUNET_memcpy (elem,
1265 sizeof (struct GNUNET_SCALARPRODUCT_Element));
1266 if (GNUNET_SYSERR ==
1267 GNUNET_CONTAINER_multihashmap_put (s->intersected_elements,
1270 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1276 set_elem.data = &elem->key;
1277 set_elem.size = sizeof (elem->key);
1278 set_elem.element_type = 0;
1279 GNUNET_SET_add_element (s->intersection_set,
1283 s->client_received_element_count += contained_count;
1284 GNUNET_SERVICE_client_continue (s->client);
1285 if (s->total != s->client_received_element_count)
1290 if (NULL == s->cadet)
1292 /* no Alice waiting for this request, wait for Alice */
1295 start_intersection (s);
1300 * Handler for Bob's a client request message. Check @a msg is
1303 * @param cls identification of the client
1304 * @param msg the actual message
1305 * @return #GNUNET_OK if @a msg is well-formed
1308 check_bob_client_message (void *cls,
1309 const struct BobComputationMessage *msg)
1311 struct BobServiceSession *s = cls;
1312 uint32_t contained_count;
1313 uint32_t total_count;
1316 if (GNUNET_SCALARPRODUCT_STATUS_INIT != s->status)
1319 return GNUNET_SYSERR;
1321 msize = ntohs (msg->header.size);
1322 total_count = ntohl (msg->element_count_total);
1323 contained_count = ntohl (msg->element_count_contained);
1324 if ( (0 == total_count) ||
1325 (0 == contained_count) ||
1326 (UINT16_MAX < contained_count) ||
1327 (msize != (sizeof (struct BobComputationMessage) +
1328 contained_count * sizeof (struct GNUNET_SCALARPRODUCT_Element))) )
1330 GNUNET_break_op (0);
1331 return GNUNET_SYSERR;
1333 if (NULL != find_matching_client_session (&msg->session_key))
1336 return GNUNET_SYSERR;
1343 * Handler for Bob's a client request message. Bob is in the response
1344 * role, keep the values + session and waiting for a matching session
1345 * or process a waiting request from Alice.
1347 * @param cls identification of the client
1348 * @param msg the actual message
1351 handle_bob_client_message (void *cls,
1352 const struct BobComputationMessage *msg)
1354 struct BobServiceSession *s = cls;
1355 struct CadetIncomingSession *in;
1356 uint32_t contained_count;
1357 uint32_t total_count;
1358 const struct GNUNET_SCALARPRODUCT_Element *elements;
1359 struct GNUNET_SET_Element set_elem;
1360 struct GNUNET_SCALARPRODUCT_Element *elem;
1362 total_count = ntohl (msg->element_count_total);
1363 contained_count = ntohl (msg->element_count_contained);
1365 s->status = GNUNET_SCALARPRODUCT_STATUS_ACTIVE;
1366 s->total = total_count;
1367 s->client_received_element_count = contained_count;
1368 s->session_id = msg->session_key;
1369 s->port = GNUNET_CADET_open_port (my_cadet,
1371 &cb_channel_incoming,
1373 if (NULL == s->port)
1376 GNUNET_SERVICE_client_drop (s->client);
1379 GNUNET_break (GNUNET_YES ==
1380 GNUNET_CONTAINER_multihashmap_put (client_sessions,
1383 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
1384 elements = (const struct GNUNET_SCALARPRODUCT_Element *) &msg[1];
1385 s->intersected_elements
1386 = GNUNET_CONTAINER_multihashmap_create (s->total,
1389 = GNUNET_SET_create (cfg,
1390 GNUNET_SET_OPERATION_INTERSECTION);
1391 for (uint32_t i = 0; i < contained_count; i++)
1393 if (0 == GNUNET_ntohll (elements[i].value))
1395 elem = GNUNET_new (struct GNUNET_SCALARPRODUCT_Element);
1396 GNUNET_memcpy (elem,
1398 sizeof (struct GNUNET_SCALARPRODUCT_Element));
1399 if (GNUNET_SYSERR ==
1400 GNUNET_CONTAINER_multihashmap_put (s->intersected_elements,
1403 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1409 set_elem.data = &elem->key;
1410 set_elem.size = sizeof (elem->key);
1411 set_elem.element_type = 0;
1412 GNUNET_SET_add_element (s->intersection_set,
1415 s->used_element_count++;
1417 GNUNET_SERVICE_client_continue (s->client);
1418 if (s->total != s->client_received_element_count)
1423 in = find_matching_cadet_session (&s->session_id);
1426 /* nothing yet, wait for Alice */
1429 GNUNET_assert (NULL == in->s);
1433 start_intersection (s);
1438 * Task run during shutdown.
1443 shutdown_task (void *cls)
1445 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1446 "Shutting down, initiating cleanup.\n");
1447 // FIXME: we have to cut our connections to CADET first!
1448 if (NULL != my_cadet)
1450 GNUNET_CADET_disconnect (my_cadet);
1453 GNUNET_CONTAINER_multihashmap_destroy (client_sessions);
1454 client_sessions = NULL;
1455 GNUNET_CONTAINER_multihashmap_destroy (cadet_sessions);
1456 cadet_sessions = NULL;
1461 * A client connected.
1463 * Setup the associated data structure.
1465 * @param cls closure, NULL
1466 * @param client identification of the client
1467 * @param mq message queue to communicate with @a client
1468 * @return our `struct BobServiceSession`
1471 client_connect_cb (void *cls,
1472 struct GNUNET_SERVICE_Client *client,
1473 struct GNUNET_MQ_Handle *mq)
1475 struct BobServiceSession *s;
1477 s = GNUNET_new (struct BobServiceSession);
1485 * A client disconnected.
1487 * Remove the associated session(s), release data structures
1488 * and cancel pending outgoing transmissions to the client.
1490 * @param cls closure, NULL
1491 * @param client identification of the client
1492 * @param app_cls our `struct BobServiceSession`
1495 client_disconnect_cb (void *cls,
1496 struct GNUNET_SERVICE_Client *client,
1499 struct BobServiceSession *s = app_cls;
1501 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1502 "Client disconnected from us.\n");
1504 destroy_service_session (s);
1509 * Initialization of the program and message handlers
1511 * @param cls closure
1512 * @param c configuration to use
1513 * @param service the initialized service
1517 const struct GNUNET_CONFIGURATION_Handle *c,
1518 struct GNUNET_SERVICE_Handle *service)
1520 static const struct GNUNET_CADET_MessageHandler cadet_handlers[] = {
1521 { &handle_alices_computation_request,
1522 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SESSION_INITIALIZATION,
1523 sizeof (struct ServiceRequestMessage) },
1524 { &handle_alices_cryptodata_message,
1525 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_CRYPTODATA,
1532 offset has to be sufficiently small to allow computation of:
1533 m1+m2 mod n == (S + a) + (S + b) mod n,
1534 if we have more complex operations, this factor needs to be lowered */
1535 my_offset = gcry_mpi_new (GNUNET_CRYPTO_PAILLIER_BITS / 3);
1536 gcry_mpi_set_bit (my_offset,
1537 GNUNET_CRYPTO_PAILLIER_BITS / 3);
1539 GNUNET_CRYPTO_paillier_create (&my_pubkey,
1541 client_sessions = GNUNET_CONTAINER_multihashmap_create (128,
1543 cadet_sessions = GNUNET_CONTAINER_multihashmap_create (128,
1545 my_cadet = GNUNET_CADET_connect (cfg, NULL,
1546 &cb_channel_destruction,
1548 GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1550 if (NULL == my_cadet)
1552 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1553 _("Connect to CADET failed\n"));
1554 GNUNET_SCHEDULER_shutdown ();
1561 * Define "main" method using service macro.
1564 ("scalarproduct-bob",
1565 GNUNET_SERVICE_OPTION_NONE,
1568 &client_disconnect_cb,
1570 GNUNET_MQ_hd_var_size (bob_client_message,
1571 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB,
1572 struct BobComputationMessage,
1574 GNUNET_MQ_hd_var_size (bob_client_message_multipart,
1575 GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_MULTIPART_BOB,
1576 struct ComputationBobCryptodataMultipartMessage,
1578 GNUNET_MQ_handler_end ());
1581 /* end of gnunet-service-scalarproduct_bob.c */