Merge branch 'master' of gnunet.org:gnunet
[oweals/gnunet.git] / src / scalarproduct / gnunet-service-scalarproduct_bob.c
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2013, 2014, 2016 GNUnet e.V.
4
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.
9
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.
14
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.
19  */
20 /**
21  * @file scalarproduct/gnunet-service-scalarproduct_bob.c
22  * @brief scalarproduct service implementation
23  * @author Christian M. Fuchs
24  * @author Christian Grothoff
25  */
26 #include "platform.h"
27 #include <limits.h>
28 #include <gcrypt.h>
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"
38
39 #define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct-bob", __VA_ARGS__)
40
41
42 /**
43  * An encrypted element key-value pair.
44  */
45 struct MpiElement
46 {
47   /**
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.
51    */
52   const struct GNUNET_HashCode *key;
53
54   /**
55    * Value represented (a).
56    */
57   gcry_mpi_t value;
58 };
59
60
61 /**
62  * A scalarproduct session which tracks an offer for a
63  * multiplication service by a local client.
64  */
65 struct BobServiceSession
66 {
67
68   /**
69    * (hopefully) unique transaction ID
70    */
71   struct GNUNET_HashCode session_id;
72
73   /**
74    * The client this request is related to.
75    */
76   struct GNUNET_SERVICE_Client *client;
77
78   /**
79    * Client message queue.
80    */
81   struct GNUNET_MQ_Handle *client_mq;
82
83   /**
84    * All non-0-value'd elements transmitted to us.
85    */
86   struct GNUNET_CONTAINER_MultiHashMap *intersected_elements;
87
88   /**
89    * Set of elements for which we will be conducting an intersection.
90    * The resulting elements are then used for computing the scalar product.
91    */
92   struct GNUNET_SET_Handle *intersection_set;
93
94   /**
95    * Set of elements for which will conduction an intersection.
96    * the resulting elements are then used for computing the scalar product.
97    */
98   struct GNUNET_SET_OperationHandle *intersection_op;
99
100   /**
101    * CADET port we are listening on.
102    */
103   struct GNUNET_CADET_Port *port;
104
105   /**
106    * a(Alice)
107    */
108   struct MpiElement *sorted_elements;
109
110   /**
111    * E(ai)(Bob) after applying the mask
112    */
113   struct GNUNET_CRYPTO_PaillierCiphertext *e_a;
114
115   /**
116    * Bob's permutation p of R
117    */
118   struct GNUNET_CRYPTO_PaillierCiphertext *r;
119
120   /**
121    * Bob's permutation q of R
122    */
123   struct GNUNET_CRYPTO_PaillierCiphertext *r_prime;
124
125   /**
126    * Bob's "s"
127    */
128   struct GNUNET_CRYPTO_PaillierCiphertext s;
129
130   /**
131    * Bob's "s'"
132    */
133   struct GNUNET_CRYPTO_PaillierCiphertext s_prime;
134
135   /**
136    * Handle for our associated incoming CADET session, or NULL
137    * if we have not gotten one yet.
138    */
139   struct CadetIncomingSession *cadet;
140
141   /**
142    * How many elements will be supplied in total from the client.
143    */
144   uint32_t total;
145
146   /**
147    * Already transferred elements (received) for multipart
148    * messages from client. Always less than @e total.
149    */
150   uint32_t client_received_element_count;
151
152   /**
153    * How many elements actually are used for the scalar product.
154    * Size of the arrays in @e r and @e r_prime.  Also sometimes
155    * used as an index into the arrays during construction.
156    */
157   uint32_t used_element_count;
158
159   /**
160    * Counts the number of values received from Alice by us.
161    * Always less than @e used_element_count.
162    */
163   uint32_t cadet_received_element_count;
164
165   /**
166    * Counts the number of values transmitted from us to Alice.
167    * Always less than @e used_element_count.
168    */
169   uint32_t cadet_transmitted_element_count;
170
171   /**
172    * State of this session.   In
173    * #GNUNET_SCALARPRODUCT_STATUS_ACTIVE while operation is
174    * ongoing, afterwards in #GNUNET_SCALARPRODUCT_STATUS_SUCCESS or
175    * #GNUNET_SCALARPRODUCT_STATUS_FAILURE.
176    */
177   enum GNUNET_SCALARPRODUCT_ResponseStatus status;
178
179   /**
180    * Are we already in #destroy_service_session()?
181    */
182   int in_destroy;
183
184   /**
185    * The CADET channel.
186    */
187   struct GNUNET_CADET_Channel *channel;
188
189   /**
190    * Originator's peer identity. (Only for diagnostics.)
191    */
192   struct GNUNET_PeerIdentity peer;
193
194   /**
195    * Public key of the remote service.
196    */
197   struct GNUNET_CRYPTO_PaillierPublicKey remote_pubkey;
198
199   /**
200    * The message queue for this channel.
201    */
202   struct GNUNET_MQ_Handle *cadet_mq;
203
204 };
205
206
207
208 /**
209  * GNUnet configuration handle
210  */
211 static const struct GNUNET_CONFIGURATION_Handle *cfg;
212
213 /**
214  * Service's own public key
215  */
216 static struct GNUNET_CRYPTO_PaillierPublicKey my_pubkey;
217
218 /**
219  * Service's own private key
220  */
221 static struct GNUNET_CRYPTO_PaillierPrivateKey my_privkey;
222
223 /**
224  * Service's offset for values that could possibly be negative but are plaintext for encryption.
225  */
226 static gcry_mpi_t my_offset;
227
228 /**
229  * Handle to the CADET service.
230  */
231 static struct GNUNET_CADET_Handle *my_cadet;
232
233
234 /**
235  * Callback used to free the elements in the map.
236  *
237  * @param cls NULL
238  * @param key key of the element
239  * @param value the value to free
240  */
241 static int
242 free_element_cb (void *cls,
243                  const struct GNUNET_HashCode *key,
244                  void *value)
245 {
246   struct GNUNET_SCALARPRODUCT_Element *element = value;
247
248   GNUNET_free (element);
249   return GNUNET_OK;
250 }
251
252
253 /**
254  * Destroy session state, we are done with it.
255  *
256  * @param session the session to free elements from
257  */
258 static void
259 destroy_service_session (struct BobServiceSession *s)
260 {
261   unsigned int i;
262
263   if (GNUNET_YES == s->in_destroy)
264     return;
265   s->in_destroy = GNUNET_YES;
266   if (NULL != s->client)
267   {
268     struct GNUNET_SERVICE_Client *c = s->client;
269
270     s->client = NULL;
271     GNUNET_SERVICE_client_drop (c);
272   }
273   if (NULL != s->intersected_elements)
274   {
275     GNUNET_CONTAINER_multihashmap_iterate (s->intersected_elements,
276                                            &free_element_cb,
277                                            NULL);
278     GNUNET_CONTAINER_multihashmap_destroy (s->intersected_elements);
279     s->intersected_elements = NULL;
280   }
281   if (NULL != s->intersection_op)
282   {
283     GNUNET_SET_operation_cancel (s->intersection_op);
284     s->intersection_op = NULL;
285   }
286   if (NULL != s->intersection_set)
287   {
288     GNUNET_SET_destroy (s->intersection_set);
289     s->intersection_set = NULL;
290   }
291   if (NULL != s->e_a)
292   {
293     GNUNET_free (s->e_a);
294     s->e_a = NULL;
295   }
296   if (NULL != s->sorted_elements)
297   {
298     for (i=0;i<s->used_element_count;i++)
299       gcry_mpi_release (s->sorted_elements[i].value);
300     GNUNET_free (s->sorted_elements);
301     s->sorted_elements = NULL;
302   }
303   if (NULL != s->r)
304   {
305     GNUNET_free (s->r);
306     s->r = NULL;
307   }
308   if (NULL != s->r_prime)
309   {
310     GNUNET_free (s->r_prime);
311     s->r_prime = NULL;
312   }
313   if (NULL != s->port)
314   {
315     GNUNET_CADET_close_port (s->port);
316     s->port = NULL;
317   }
318   if (NULL != s->channel)
319   {
320     GNUNET_CADET_channel_destroy (s->channel);
321     s->channel = NULL;
322   }
323   GNUNET_free (s);
324 }
325
326
327 /**
328  * Notify the client that the session has succeeded or failed.  This
329  * message gets sent to Bob's client if the operation completed or
330  * Alice disconnected.
331  *
332  * @param session the associated client session to fail or succeed
333  */
334 static void
335 prepare_client_end_notification (struct BobServiceSession *session)
336 {
337   struct ClientResponseMessage *msg;
338   struct GNUNET_MQ_Envelope *e;
339
340   if (NULL == session->client_mq)
341     return; /* no client left to be notified */
342   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
343               "Sending session-end notification with status %d to client for session %s\n",
344               session->status,
345               GNUNET_h2s (&session->session_id));
346   e = GNUNET_MQ_msg (msg,
347                      GNUNET_MESSAGE_TYPE_SCALARPRODUCT_RESULT);
348   msg->range = 0;
349   msg->product_length = htonl (0);
350   msg->status = htonl (session->status);
351   GNUNET_MQ_send (session->client_mq,
352                   e);
353 }
354
355
356 /**
357  * Function called whenever a channel is destroyed.  Should clean up
358  * any associated state.
359  *
360  * It must NOT call #GNUNET_CADET_channel_destroy() on the channel.
361  *
362  * @param cls the `struct BobServiceSession`
363  * @param channel connection to the other end (henceforth invalid)
364  */
365 static void
366 cb_channel_destruction (void *cls,
367                         const struct GNUNET_CADET_Channel *channel)
368 {
369   struct BobServiceSession *s = cls;
370
371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
372               "Peer disconnected, terminating session %s with peer %s\n",
373               GNUNET_h2s (&s->session_id),
374               GNUNET_i2s (&s->peer));
375   if (GNUNET_SCALARPRODUCT_STATUS_ACTIVE == s->status)
376   {
377     s->status = GNUNET_SCALARPRODUCT_STATUS_FAILURE;
378     prepare_client_end_notification (s);
379   }
380   s->channel = NULL;
381   destroy_service_session (s);
382 }
383
384
385 /**
386  * MQ finished giving our last message to CADET, now notify
387  * the client that we are finished.
388  */
389 static void
390 bob_cadet_done_cb (void *cls)
391 {
392   struct BobServiceSession *session = cls;
393
394   session->status = GNUNET_SCALARPRODUCT_STATUS_SUCCESS;
395   prepare_client_end_notification (session);
396 }
397
398
399 /**
400  * Maximum count of elements we can put into a multipart message
401  */
402 #define ELEMENT_CAPACITY ((GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE - 1 - sizeof (struct BobCryptodataMultipartMessage)) / sizeof (struct GNUNET_CRYPTO_PaillierCiphertext))
403
404
405 /**
406  * Send a multipart chunk of a service response from Bob to Alice.
407  * This element only contains the two permutations of R, R'.
408  *
409  * @param s the associated service session
410  */
411 static void
412 transmit_bobs_cryptodata_message_multipart (struct BobServiceSession *s)
413 {
414   struct GNUNET_CRYPTO_PaillierCiphertext *payload;
415   struct BobCryptodataMultipartMessage *msg;
416   struct GNUNET_MQ_Envelope *e;
417   unsigned int i;
418   unsigned int j;
419   uint32_t todo_count;
420
421   while (s->cadet_transmitted_element_count != s->used_element_count)
422   {
423     todo_count = s->used_element_count - s->cadet_transmitted_element_count;
424     if (todo_count > ELEMENT_CAPACITY / 2)
425       todo_count = ELEMENT_CAPACITY / 2;
426
427     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
428                 "Sending %u additional crypto values to Alice\n",
429                 (unsigned int) todo_count);
430     e = GNUNET_MQ_msg_extra (msg,
431                              todo_count * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * 2,
432                              GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_CRYPTODATA_MULTIPART);
433     msg->contained_element_count = htonl (todo_count);
434     payload = (struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
435     for (i = s->cadet_transmitted_element_count, j = 0; i < s->cadet_transmitted_element_count + todo_count; i++)
436     {
437       //r[i][p] and r[i][q]
438       GNUNET_memcpy (&payload[j++],
439               &s->r[i],
440               sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
441       GNUNET_memcpy (&payload[j++],
442               &s->r_prime[i],
443               sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
444     }
445     s->cadet_transmitted_element_count += todo_count;
446     if (s->cadet_transmitted_element_count == s->used_element_count)
447       GNUNET_MQ_notify_sent (e,
448                              &bob_cadet_done_cb,
449                              s);
450     GNUNET_MQ_send (s->cadet_mq,
451                     e);
452   }
453   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
454               "All values queued for Alice, Bob is done\n");
455 }
456
457
458 /**
459  * Bob generates the response message to be sent to Alice after
460  * computing the values (1), (2), S and S'.
461  *
462  *  (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)})$
463  *  (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
464  *      S: $S := E_A(sum (r_i + b_i)^2)$
465  *     S': $S' := E_A(sum r_i^2)$
466  *
467  * @param s the associated requesting session with Alice
468  */
469 static void
470 transmit_bobs_cryptodata_message (struct BobServiceSession *s)
471 {
472   struct BobCryptodataMessage *msg;
473   struct GNUNET_MQ_Envelope *e;
474   struct GNUNET_CRYPTO_PaillierCiphertext *payload;
475   unsigned int i;
476
477   s->cadet_transmitted_element_count
478     = ((GNUNET_CONSTANTS_MAX_CADET_MESSAGE_SIZE - 1 - sizeof (struct BobCryptodataMessage))
479        / sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) / 2) - 1;
480   if (s->cadet_transmitted_element_count > s->used_element_count)
481     s->cadet_transmitted_element_count = s->used_element_count;
482
483   e = GNUNET_MQ_msg_extra (msg,
484                            (2 + s->cadet_transmitted_element_count * 2)
485                            * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext),
486                            GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_CRYPTODATA);
487   msg->contained_element_count = htonl (s->cadet_transmitted_element_count);
488
489   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
490               "Sending %u/%u crypto values to Alice\n",
491               (unsigned int) s->cadet_transmitted_element_count,
492               (unsigned int) s->used_element_count);
493
494   payload = (struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
495   GNUNET_memcpy (&payload[0],
496                  &s->s,
497                  sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
498   GNUNET_memcpy (&payload[1],
499                  &s->s_prime,
500                  sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
501
502   payload = &payload[2];
503   // convert k[][]
504   for (i = 0; i < s->cadet_transmitted_element_count; i++)
505   {
506     //k[i][p] and k[i][q]
507     GNUNET_memcpy (&payload[i * 2],
508             &s->r[i],
509             sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
510     GNUNET_memcpy (&payload[i * 2 + 1],
511             &s->r_prime[i],
512             sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
513   }
514   if (s->cadet_transmitted_element_count == s->used_element_count)
515     GNUNET_MQ_notify_sent (e,
516                            &bob_cadet_done_cb,
517                            s);
518   GNUNET_MQ_send (s->cadet_mq,
519                   e);
520   transmit_bobs_cryptodata_message_multipart (s);
521 }
522 #undef ELEMENT_CAPACITY
523
524
525 /**
526  * Computes the square sum over a vector of a given length.
527  *
528  * @param vector the vector to compute over
529  * @param length the length of the vector
530  * @return an MPI value containing the calculated sum, never NULL
531  * TODO: code duplication with Alice!
532  */
533 static gcry_mpi_t
534 compute_square_sum (const gcry_mpi_t *vector,
535                     uint32_t length)
536 {
537   gcry_mpi_t elem;
538   gcry_mpi_t sum;
539   uint32_t i;
540
541   GNUNET_assert (NULL != (sum = gcry_mpi_new (0)));
542   GNUNET_assert (NULL != (elem = gcry_mpi_new (0)));
543   for (i = 0; i < length; i++)
544   {
545     gcry_mpi_mul (elem, vector[i], vector[i]);
546     gcry_mpi_add (sum, sum, elem);
547   }
548   gcry_mpi_release (elem);
549   return sum;
550 }
551
552
553 /**
554  * Compute the values
555  *  (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)})$
556  *  (2)[]: $E_A(a_{pi'(i)}) otimes E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
557  *      S: $S := E_A(sum (r_i + b_i)^2)$
558  *     S': $S' := E_A(sum r_i^2)$
559  *
560  * @param request the requesting session + bob's requesting peer
561  * @return #GNUNET_OK on success
562  */
563 static int
564 compute_service_response (struct BobServiceSession *session)
565 {
566   uint32_t i;
567   unsigned int *p;
568   unsigned int *q;
569   uint32_t count;
570   gcry_mpi_t *rand;
571   gcry_mpi_t tmp;
572   const struct MpiElement *b;
573   struct GNUNET_CRYPTO_PaillierCiphertext *a;
574   struct GNUNET_CRYPTO_PaillierCiphertext *r;
575   struct GNUNET_CRYPTO_PaillierCiphertext *r_prime;
576
577   count = session->used_element_count;
578   a = session->e_a;
579   b = session->sorted_elements;
580   q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
581                                     count);
582   p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK,
583                                     count);
584   rand = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
585   for (i = 0; i < count; i++)
586     GNUNET_assert (NULL != (rand[i] = gcry_mpi_new (0)));
587   r = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * count);
588   r_prime = GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * count);
589
590   for (i = 0; i < count; i++)
591   {
592     int32_t svalue;
593
594     svalue = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
595                                                  UINT32_MAX);
596     // long to gcry_mpi_t
597     if (svalue < 0)
598       gcry_mpi_sub_ui (rand[i],
599                        rand[i],
600                        - svalue);
601     else
602       rand[i] = gcry_mpi_set_ui (rand[i], svalue);
603   }
604
605   tmp = gcry_mpi_new (0);
606   // encrypt the element
607   // for the sake of readability I decided to have dedicated permutation
608   // vectors, which get rid of all the lookups in p/q.
609   // however, ap/aq are not absolutely necessary but are just abstraction
610   // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
611   for (i = 0; i < count; i++)
612   {
613     // E(S - r_pi - b_pi)
614     gcry_mpi_sub (tmp, my_offset, rand[p[i]]);
615     gcry_mpi_sub (tmp, tmp, b[p[i]].value);
616     GNUNET_assert (2 ==
617                    GNUNET_CRYPTO_paillier_encrypt (&session->remote_pubkey,
618                                                    tmp,
619                                                    2,
620                                                    &r[i]));
621
622     // E(S - r_pi - b_pi) * E(S + a_pi) ==  E(2*S + a - r - b)
623     if (GNUNET_OK !=
624         GNUNET_CRYPTO_paillier_hom_add (&session->remote_pubkey,
625                                         &r[i],
626                                         &a[p[i]],
627                                         &r[i]))
628     {
629       GNUNET_break_op (0);
630       goto error_cleanup;
631     }
632   }
633
634   // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
635   for (i = 0; i < count; i++)
636   {
637     // E(S - r_qi)
638     gcry_mpi_sub (tmp, my_offset, rand[q[i]]);
639     GNUNET_assert (2 ==
640                    GNUNET_CRYPTO_paillier_encrypt (&session->remote_pubkey,
641                                                    tmp,
642                                                    2,
643                                                    &r_prime[i]));
644
645     // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
646     if (GNUNET_OK !=
647         GNUNET_CRYPTO_paillier_hom_add (&session->remote_pubkey,
648                                         &r_prime[i],
649                                         &a[q[i]],
650                                         &r_prime[i]))
651     {
652       GNUNET_break_op (0);
653       goto error_cleanup;
654     }
655   }
656   gcry_mpi_release (tmp);
657
658   // Calculate S' =  E(SUM( r_i^2 ))
659   tmp = compute_square_sum (rand, count);
660   GNUNET_assert (1 ==
661                  GNUNET_CRYPTO_paillier_encrypt (&session->remote_pubkey,
662                                                  tmp,
663                                                  1,
664                                                  &session->s_prime));
665   gcry_mpi_release (tmp);
666
667   // Calculate S = E(SUM( (r_i + b_i)^2 ))
668   for (i = 0; i < count; i++)
669     gcry_mpi_add (rand[i], rand[i], b[i].value);
670   tmp = compute_square_sum (rand, count);
671   GNUNET_assert (1 ==
672                  GNUNET_CRYPTO_paillier_encrypt (&session->remote_pubkey,
673                                                  tmp,
674                                                  1,
675                                                  &session->s));
676   gcry_mpi_release (tmp);
677
678   session->r = r;
679   session->r_prime = r_prime;
680
681   for (i = 0; i < count; i++)
682     gcry_mpi_release (rand[i]);
683   GNUNET_free (session->e_a);
684   session->e_a = NULL;
685   GNUNET_free (p);
686   GNUNET_free (q);
687   GNUNET_free (rand);
688   return GNUNET_OK;
689
690  error_cleanup:
691   GNUNET_free (r);
692   GNUNET_free (r_prime);
693   gcry_mpi_release (tmp);
694   GNUNET_free (p);
695   GNUNET_free (q);
696   for (i = 0; i < count; i++)
697     gcry_mpi_release (rand[i]);
698   GNUNET_free (rand);
699   return GNUNET_SYSERR;
700 }
701
702
703 /**
704  * Iterator to copy over messages from the hash map
705  * into an array for sorting.
706  *
707  * @param cls the `struct BobServiceSession *`
708  * @param key the key (unused)
709  * @param value the `struct GNUNET_SCALARPRODUCT_Element *`
710  * TODO: code duplication with Alice!
711  */
712 static int
713 copy_element_cb (void *cls,
714                  const struct GNUNET_HashCode *key,
715                  void *value)
716 {
717   struct BobServiceSession *s = cls;
718   struct GNUNET_SCALARPRODUCT_Element *e = value;
719   gcry_mpi_t mval;
720   int64_t val;
721
722   mval = gcry_mpi_new (0);
723   val = (int64_t) GNUNET_ntohll (e->value);
724   if (0 > val)
725     gcry_mpi_sub_ui (mval, mval, -val);
726   else
727     gcry_mpi_add_ui (mval, mval, val);
728   s->sorted_elements [s->used_element_count].value = mval;
729   s->sorted_elements [s->used_element_count].key = &e->key;
730   s->used_element_count++;
731   return GNUNET_OK;
732 }
733
734
735 /**
736  * Compare two `struct MpiValue`s by key for sorting.
737  *
738  * @param a pointer to first `struct MpiValue *`
739  * @param b pointer to first `struct MpiValue *`
740  * @return -1 for a < b, 0 for a=b, 1 for a > b.
741  * TODO: code duplication with Alice!
742  */
743 static int
744 element_cmp (const void *a,
745              const void *b)
746 {
747   const struct MpiElement *ma = a;
748   const struct MpiElement *mb = b;
749
750   return GNUNET_CRYPTO_hash_cmp (ma->key,
751                                  mb->key);
752 }
753
754
755 /**
756  * Intersection operation and receiving data via CADET from
757  * Alice are both done, compute and transmit our reply via
758  * CADET.
759  *
760  * @param s session to transmit reply for.
761  */
762 static void
763 transmit_cryptographic_reply (struct BobServiceSession *s)
764 {
765   struct GNUNET_CADET_Channel *channel;
766
767   /* TODO: code duplication with Alice! */
768   LOG (GNUNET_ERROR_TYPE_DEBUG,
769        "Received everything, building reply for Alice\n");
770   s->sorted_elements
771     = GNUNET_malloc (GNUNET_CONTAINER_multihashmap_size (s->intersected_elements) *
772                      sizeof (struct MpiElement));
773   s->used_element_count = 0;
774   GNUNET_CONTAINER_multihashmap_iterate (s->intersected_elements,
775                                          &copy_element_cb,
776                                          s);
777   qsort (s->sorted_elements,
778          s->used_element_count,
779          sizeof (struct MpiElement),
780          &element_cmp);
781   if (GNUNET_OK !=
782       compute_service_response (s))
783   {
784     channel = s->channel;
785     s->channel = NULL;
786     GNUNET_CADET_channel_destroy (channel);
787     return;
788   }
789   transmit_bobs_cryptodata_message (s);
790 }
791
792
793 /**
794  * Check a multipart-chunk of a request from another service to
795  * calculate a scalarproduct with us.
796  *
797  * @param cls the `struct BobServiceSession *`
798  * @param msg the actual message
799  * @return #GNUNET_OK to keep the connection open,
800  *         #GNUNET_SYSERR to close it (signal serious error)
801  */
802 static int
803 check_alices_cryptodata_message (void *cls,
804                                  const struct AliceCryptodataMessage *msg)
805 {
806   struct BobServiceSession *s = cls;
807   uint32_t contained_elements;
808   size_t msg_length;
809   uint16_t msize;
810   unsigned int max;
811
812   msize = ntohs (msg->header.size);
813   contained_elements = ntohl (msg->contained_element_count);
814   /* Our intersection may still be ongoing, but this is nevertheless
815      an upper bound on the required array size */
816   max = GNUNET_CONTAINER_multihashmap_size (s->intersected_elements);
817   msg_length = sizeof (struct AliceCryptodataMessage)
818     + contained_elements * sizeof (struct GNUNET_CRYPTO_PaillierCiphertext);
819   if ( (msize != msg_length) ||
820        (0 == contained_elements) ||
821        (contained_elements > UINT16_MAX) ||
822        (max < contained_elements + s->cadet_received_element_count) )
823   {
824     GNUNET_break_op (0);
825     return GNUNET_SYSERR;
826   }
827   return GNUNET_OK;
828 }
829
830
831 /**
832  * Handle a multipart-chunk of a request from another service to
833  * calculate a scalarproduct with us.
834  *
835  * @param cls the `struct BobServiceSession *`
836  * @param msg the actual message
837  */
838 static void
839 handle_alices_cryptodata_message (void *cls,
840                                   const struct AliceCryptodataMessage *msg)
841 {
842   struct BobServiceSession *s = cls;
843   const struct GNUNET_CRYPTO_PaillierCiphertext *payload;
844   uint32_t contained_elements;
845   unsigned int max;
846
847   contained_elements = ntohl (msg->contained_element_count);
848   /* Our intersection may still be ongoing, but this is nevertheless
849      an upper bound on the required array size */
850   max = GNUNET_CONTAINER_multihashmap_size (s->intersected_elements);
851   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
852               "Received %u crypto values from Alice\n",
853               (unsigned int) contained_elements);
854
855   payload = (const struct GNUNET_CRYPTO_PaillierCiphertext *) &msg[1];
856   if (NULL == s->e_a)
857     s->e_a = GNUNET_new_array (max,
858                                struct GNUNET_CRYPTO_PaillierCiphertext);
859   GNUNET_memcpy (&s->e_a[s->cadet_received_element_count],
860                  payload,
861                  sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * contained_elements);
862   s->cadet_received_element_count += contained_elements;
863
864   if ( (s->cadet_received_element_count == max) &&
865        (NULL == s->intersection_op) )
866   {
867     /* intersection has finished also on our side, and
868        we got the full set, so we can proceed with the
869        CADET response(s) */
870     transmit_cryptographic_reply (s);
871   }
872   GNUNET_CADET_receive_done (s->channel);
873 }
874
875
876 /**
877  * Callback for set operation results. Called for each element
878  * that needs to be removed from the result set.
879  *
880  * @param cls closure with the `struct BobServiceSession`
881  * @param element a result element, only valid if status is #GNUNET_SET_STATUS_OK
882  * @param status what has happened with the set intersection?
883  */
884 static void
885 cb_intersection_element_removed (void *cls,
886                                  const struct GNUNET_SET_Element *element,
887                                  enum GNUNET_SET_Status status)
888 {
889   struct BobServiceSession *s = cls;
890   struct GNUNET_SCALARPRODUCT_Element *se;
891
892   switch (status)
893   {
894   case GNUNET_SET_STATUS_OK:
895     /* this element has been removed from the set */
896     se = GNUNET_CONTAINER_multihashmap_get (s->intersected_elements,
897                                             element->data);
898     GNUNET_assert (NULL != se);
899     LOG (GNUNET_ERROR_TYPE_DEBUG,
900          "Removed element with key %s and value %lld\n",
901          GNUNET_h2s (&se->key),
902          (long long) GNUNET_ntohll (se->value));
903     GNUNET_assert (GNUNET_YES ==
904                    GNUNET_CONTAINER_multihashmap_remove (s->intersected_elements,
905                                                          element->data,
906                                                          se));
907     GNUNET_free (se);
908     return;
909   case GNUNET_SET_STATUS_DONE:
910     s->intersection_op = NULL;
911     GNUNET_break (NULL == s->intersection_set);
912     GNUNET_CADET_receive_done (s->channel);
913     LOG (GNUNET_ERROR_TYPE_DEBUG,
914          "Finished intersection, %d items remain\n",
915          GNUNET_CONTAINER_multihashmap_size (s->intersected_elements));
916     if (s->client_received_element_count ==
917         GNUNET_CONTAINER_multihashmap_size (s->intersected_elements))
918     {
919       /* CADET transmission from Alice is also already done,
920          start with our own reply */
921       transmit_cryptographic_reply (s);
922     }
923     return;
924   case GNUNET_SET_STATUS_HALF_DONE:
925     /* unexpected for intersection */
926     GNUNET_break (0);
927     return;
928   case GNUNET_SET_STATUS_FAILURE:
929     /* unhandled status code */
930     LOG (GNUNET_ERROR_TYPE_DEBUG,
931          "Set intersection failed!\n");
932     s->intersection_op = NULL;
933     if (NULL != s->intersection_set)
934     {
935       GNUNET_SET_destroy (s->intersection_set);
936       s->intersection_set = NULL;
937     }
938     s->status = GNUNET_SCALARPRODUCT_STATUS_FAILURE;
939     prepare_client_end_notification (s);
940     return;
941   default:
942     GNUNET_break (0);
943     return;
944   }
945 }
946
947
948 /**
949  * We've paired up a client session with an incoming CADET request.
950  * Initiate set intersection work.
951  *
952  * @param s client session to start intersection for
953  */
954 static void
955 start_intersection (struct BobServiceSession *s)
956 {
957   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
958               "Got session with key %s and %u elements, starting intersection.\n",
959               GNUNET_h2s (&s->session_id),
960               (unsigned int) s->total);
961
962   s->intersection_op
963     = GNUNET_SET_prepare (&s->peer,
964                           &s->session_id,
965                           NULL,
966                           GNUNET_SET_RESULT_REMOVED,
967                           (struct GNUNET_SET_Option[]) { 0 },
968                           &cb_intersection_element_removed,
969                           s);
970   if (GNUNET_OK !=
971       GNUNET_SET_commit (s->intersection_op,
972                          s->intersection_set))
973   {
974     GNUNET_break (0);
975     s->status = GNUNET_SCALARPRODUCT_STATUS_FAILURE;
976     prepare_client_end_notification (s);
977     return;
978   }
979   GNUNET_SET_destroy (s->intersection_set);
980   s->intersection_set = NULL;
981 }
982
983
984 /**
985  * Handle a request from Alice to calculate a scalarproduct with us (Bob).
986  *
987  * @param cls the `struct BobServiceSession *`
988  * @param msg the actual message
989  */
990 static void
991 handle_alices_computation_request (void *cls,
992                                    const struct ServiceRequestMessage *msg)
993 {
994   struct BobServiceSession *s = cls;
995
996   s->session_id = msg->session_id; // ??
997   s->remote_pubkey = msg->public_key;
998   if (s->client_received_element_count == s->total)
999     start_intersection (s);
1000 }
1001
1002
1003 /**
1004  * Function called for inbound channels on Bob's end.  Does some
1005  * preliminary initialization, more happens after we get Alice's first
1006  * message.
1007  *
1008  * @param cls closure with the `struct BobServiceSession`
1009  * @param channel new handle to the channel
1010  * @param initiator peer that started the channel
1011  * @return session associated with the channel
1012  */
1013 static void *
1014 cb_channel_incoming (void *cls,
1015                      struct GNUNET_CADET_Channel *channel,
1016                      const struct GNUNET_PeerIdentity *initiator)
1017 {
1018   struct BobServiceSession *s = cls;
1019
1020   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1021               "New incoming channel from peer %s.\n",
1022               GNUNET_i2s (initiator));
1023   GNUNET_CADET_close_port (s->port);
1024   s->port = NULL;
1025   s->channel = channel;
1026   s->peer = *initiator;
1027   s->cadet_mq = GNUNET_CADET_get_mq (s->channel);
1028   return s;
1029 }
1030
1031
1032 /**
1033  * We're receiving additional set data. Check it is well-formed.
1034  *
1035  * @param cls identification of the client
1036  * @param msg the actual message
1037  * @return #GNUNET_OK if @a msg is well-formed
1038  */
1039 static int
1040 check_bob_client_message_multipart (void *cls,
1041                                     const struct ComputationBobCryptodataMultipartMessage *msg)
1042 {
1043   struct BobServiceSession *s = cls;
1044   uint32_t contained_count;
1045   uint16_t msize;
1046
1047   msize = ntohs (msg->header.size);
1048   contained_count = ntohl (msg->element_count_contained);
1049   if ( (msize != (sizeof (struct ComputationBobCryptodataMultipartMessage) +
1050                   contained_count * sizeof (struct GNUNET_SCALARPRODUCT_Element))) ||
1051        (0 == contained_count) ||
1052        (UINT16_MAX < contained_count) ||
1053        (s->total == s->client_received_element_count) ||
1054        (s->total < s->client_received_element_count + contained_count) )
1055   {
1056     GNUNET_break (0);
1057     return GNUNET_SYSERR;
1058   }
1059   return GNUNET_OK;
1060 }
1061
1062
1063 /**
1064  * We're receiving additional set data. Add it to our
1065  * set and if we are done, initiate the transaction.
1066  *
1067  * @param cls identification of the client
1068  * @param msg the actual message
1069  */
1070 static void
1071 handle_bob_client_message_multipart (void *cls,
1072                                      const struct ComputationBobCryptodataMultipartMessage *msg)
1073 {
1074   struct BobServiceSession *s = cls;
1075   uint32_t contained_count;
1076   const struct GNUNET_SCALARPRODUCT_Element *elements;
1077   struct GNUNET_SET_Element set_elem;
1078   struct GNUNET_SCALARPRODUCT_Element *elem;
1079
1080   contained_count = ntohl (msg->element_count_contained);
1081   elements = (const struct GNUNET_SCALARPRODUCT_Element *) &msg[1];
1082   for (uint32_t i = 0; i < contained_count; i++)
1083   {
1084     elem = GNUNET_new (struct GNUNET_SCALARPRODUCT_Element);
1085     GNUNET_memcpy (elem,
1086                    &elements[i],
1087                    sizeof (struct GNUNET_SCALARPRODUCT_Element));
1088     if (GNUNET_SYSERR ==
1089         GNUNET_CONTAINER_multihashmap_put (s->intersected_elements,
1090                                            &elem->key,
1091                                            elem,
1092                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1093     {
1094       GNUNET_break (0);
1095       GNUNET_free (elem);
1096       continue;
1097     }
1098     set_elem.data = &elem->key;
1099     set_elem.size = sizeof (elem->key);
1100     set_elem.element_type = 0;
1101     GNUNET_SET_add_element (s->intersection_set,
1102                             &set_elem,
1103                             NULL, NULL);
1104   }
1105   s->client_received_element_count += contained_count;
1106   GNUNET_SERVICE_client_continue (s->client);
1107   if (s->total != s->client_received_element_count)
1108   {
1109     /* more to come */
1110     return;
1111   }
1112   if (NULL == s->channel)
1113   {
1114     /* no Alice waiting for this request, wait for Alice */
1115     return;
1116   }
1117   start_intersection (s);
1118 }
1119
1120
1121 /**
1122  * Handler for Bob's a client request message.  Check @a msg is
1123  * well-formed.
1124  *
1125  * @param cls identification of the client
1126  * @param msg the actual message
1127  * @return #GNUNET_OK if @a msg is well-formed
1128  */
1129 static int
1130 check_bob_client_message (void *cls,
1131                           const struct BobComputationMessage *msg)
1132 {
1133   struct BobServiceSession *s = cls;
1134   uint32_t contained_count;
1135   uint32_t total_count;
1136   uint16_t msize;
1137
1138   if (GNUNET_SCALARPRODUCT_STATUS_INIT != s->status)
1139   {
1140     GNUNET_break (0);
1141     return GNUNET_SYSERR;
1142   }
1143   msize = ntohs (msg->header.size);
1144   total_count = ntohl (msg->element_count_total);
1145   contained_count = ntohl (msg->element_count_contained);
1146   if ( (0 == total_count) ||
1147        (0 == contained_count) ||
1148        (UINT16_MAX < contained_count) ||
1149        (msize != (sizeof (struct BobComputationMessage) +
1150                   contained_count * sizeof (struct GNUNET_SCALARPRODUCT_Element))) )
1151   {
1152     GNUNET_break_op (0);
1153     return GNUNET_SYSERR;
1154   }
1155   return GNUNET_OK;
1156 }
1157
1158
1159 /**
1160  * Handler for Bob's a client request message.  Bob is in the response
1161  * role, keep the values + session and waiting for a matching session
1162  * or process a waiting request from Alice.
1163  *
1164  * @param cls identification of the client
1165  * @param msg the actual message
1166  */
1167 static void
1168 handle_bob_client_message (void *cls,
1169                            const struct BobComputationMessage *msg)
1170 {
1171   struct BobServiceSession *s = cls;
1172   struct GNUNET_MQ_MessageHandler cadet_handlers[] = {
1173     GNUNET_MQ_hd_fixed_size (alices_computation_request,
1174                              GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SESSION_INITIALIZATION,
1175                              struct ServiceRequestMessage,
1176                              NULL),
1177     GNUNET_MQ_hd_var_size (alices_cryptodata_message,
1178                            GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_CRYPTODATA,
1179                            struct AliceCryptodataMessage,
1180                            NULL),
1181     GNUNET_MQ_handler_end ()
1182   };
1183   uint32_t contained_count;
1184   uint32_t total_count;
1185   const struct GNUNET_SCALARPRODUCT_Element *elements;
1186   struct GNUNET_SET_Element set_elem;
1187   struct GNUNET_SCALARPRODUCT_Element *elem;
1188
1189   total_count = ntohl (msg->element_count_total);
1190   contained_count = ntohl (msg->element_count_contained);
1191
1192   s->status = GNUNET_SCALARPRODUCT_STATUS_ACTIVE;
1193   s->total = total_count;
1194   s->client_received_element_count = contained_count;
1195   s->session_id = msg->session_key;
1196   elements = (const struct GNUNET_SCALARPRODUCT_Element *) &msg[1];
1197   s->intersected_elements
1198     = GNUNET_CONTAINER_multihashmap_create (s->total,
1199                                             GNUNET_YES);
1200   s->intersection_set
1201     = GNUNET_SET_create (cfg,
1202                          GNUNET_SET_OPERATION_INTERSECTION);
1203   for (uint32_t i = 0; i < contained_count; i++)
1204   {
1205     if (0 == GNUNET_ntohll (elements[i].value))
1206       continue;
1207     elem = GNUNET_new (struct GNUNET_SCALARPRODUCT_Element);
1208     GNUNET_memcpy (elem,
1209             &elements[i],
1210             sizeof (struct GNUNET_SCALARPRODUCT_Element));
1211     if (GNUNET_SYSERR ==
1212         GNUNET_CONTAINER_multihashmap_put (s->intersected_elements,
1213                                            &elem->key,
1214                                            elem,
1215                                            GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY))
1216     {
1217       GNUNET_break (0);
1218       GNUNET_free (elem);
1219       continue;
1220     }
1221     set_elem.data = &elem->key;
1222     set_elem.size = sizeof (elem->key);
1223     set_elem.element_type = 0;
1224     GNUNET_SET_add_element (s->intersection_set,
1225                             &set_elem,
1226                             NULL, NULL);
1227     s->used_element_count++;
1228   }
1229   GNUNET_SERVICE_client_continue (s->client);
1230   /* We're ready, open the port */
1231   s->port = GNUNET_CADET_open_porT (my_cadet,
1232                                     &msg->session_key,
1233                                     &cb_channel_incoming,
1234                                     s,
1235                                     NULL,
1236                                     &cb_channel_destruction,
1237                                     cadet_handlers);
1238   if (NULL == s->port)
1239   {
1240     GNUNET_break (0);
1241     GNUNET_SERVICE_client_drop (s->client);
1242     return;
1243   }
1244 }
1245
1246
1247 /**
1248  * Task run during shutdown.
1249  *
1250  * @param cls unused
1251  */
1252 static void
1253 shutdown_task (void *cls)
1254 {
1255   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1256               "Shutting down, initiating cleanup.\n");
1257   // FIXME: we have to cut our connections to CADET first!
1258   if (NULL != my_cadet)
1259   {
1260     GNUNET_CADET_disconnect (my_cadet);
1261     my_cadet = NULL;
1262   }
1263 }
1264
1265
1266 /**
1267  * A client connected.
1268  *
1269  * Setup the associated data structure.
1270  *
1271  * @param cls closure, NULL
1272  * @param client identification of the client
1273  * @param mq message queue to communicate with @a client
1274  * @return our `struct BobServiceSession`
1275  */
1276 static void *
1277 client_connect_cb (void *cls,
1278                    struct GNUNET_SERVICE_Client *client,
1279                    struct GNUNET_MQ_Handle *mq)
1280 {
1281   struct BobServiceSession *s;
1282
1283   s = GNUNET_new (struct BobServiceSession);
1284   s->client = client;
1285   s->client_mq = mq;
1286   return s;
1287 }
1288
1289
1290 /**
1291  * A client disconnected.
1292  *
1293  * Remove the associated session(s), release data structures
1294  * and cancel pending outgoing transmissions to the client.
1295  *
1296  * @param cls closure, NULL
1297  * @param client identification of the client
1298  * @param app_cls our `struct BobServiceSession`
1299  */
1300 static void
1301 client_disconnect_cb (void *cls,
1302                       struct GNUNET_SERVICE_Client *client,
1303                       void *app_cls)
1304 {
1305   struct BobServiceSession *s = app_cls;
1306
1307   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1308               "Client disconnected from us.\n");
1309   s->client = NULL;
1310   destroy_service_session (s);
1311 }
1312
1313
1314 /**
1315  * Initialization of the program and message handlers
1316  *
1317  * @param cls closure
1318  * @param c configuration to use
1319  * @param service the initialized service
1320  */
1321 static void
1322 run (void *cls,
1323      const struct GNUNET_CONFIGURATION_Handle *c,
1324      struct GNUNET_SERVICE_Handle *service)
1325 {
1326   cfg = c;
1327   /*
1328     offset has to be sufficiently small to allow computation of:
1329     m1+m2 mod n == (S + a) + (S + b) mod n,
1330     if we have more complex operations, this factor needs to be lowered */
1331   my_offset = gcry_mpi_new (GNUNET_CRYPTO_PAILLIER_BITS / 3);
1332   gcry_mpi_set_bit (my_offset,
1333                     GNUNET_CRYPTO_PAILLIER_BITS / 3);
1334
1335   GNUNET_CRYPTO_paillier_create (&my_pubkey,
1336                                  &my_privkey);
1337   my_cadet = GNUNET_CADET_connecT (cfg);
1338   GNUNET_SCHEDULER_add_shutdown (&shutdown_task,
1339                                  NULL);
1340   if (NULL == my_cadet)
1341   {
1342     GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1343                 _("Connect to CADET failed\n"));
1344     GNUNET_SCHEDULER_shutdown ();
1345     return;
1346   }
1347 }
1348
1349
1350 /**
1351  * Define "main" method using service macro.
1352  */
1353 GNUNET_SERVICE_MAIN
1354 ("scalarproduct-bob",
1355  GNUNET_SERVICE_OPTION_NONE,
1356  &run,
1357  &client_connect_cb,
1358  &client_disconnect_cb,
1359  NULL,
1360  GNUNET_MQ_hd_var_size (bob_client_message,
1361                         GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB,
1362                         struct BobComputationMessage,
1363                         NULL),
1364 GNUNET_MQ_hd_var_size (bob_client_message_multipart,
1365                        GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_MULTIPART_BOB,
1366                        struct ComputationBobCryptodataMultipartMessage,
1367                        NULL),
1368  GNUNET_MQ_handler_end ());
1369
1370
1371 /* end of gnunet-service-scalarproduct_bob.c */