2 This file is part of GNUnet.
3 (C) 2013 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 3, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file scalarproduct/gnunet-service-scalarproduct.c
23 * @brief scalarproduct service implementation
24 * @author Christian M. Fuchs
28 #include "gnunet_util_lib.h"
29 #include "gnunet_core_service.h"
30 #include "gnunet_mesh_service.h"
31 #include "gnunet_applications.h"
32 #include "gnunet_protocols.h"
33 #include "gnunet_scalarproduct_service.h"
34 #include "gnunet_scalarproduct.h"
37 #define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct", __VA_ARGS__)
40 * Log an error message at log-level 'level' that indicates
41 * a failure of the command 'cmd' with the message given
42 * by gcry_strerror(rc).
44 #define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0)
48 ///////////////////////////////////////////////////////////////////////////////
50 ///////////////////////////////////////////////////////////////////////////////
54 * Handle to the core service (NULL until we've connected to it).
56 static struct GNUNET_MESH_Handle *my_mesh;
59 * The identity of this host.
61 static struct GNUNET_PeerIdentity me;
64 * Service's own public key represented as string
66 static unsigned char * my_pubkey_external;
69 * Service's own public key represented as string
71 static uint16_t my_pubkey_external_length = 0;
76 static gcry_mpi_t my_n;
79 * Service's own n^2 (kept for performance)
81 static gcry_mpi_t my_nsquare;
84 * Service's own public exponent
86 static gcry_mpi_t my_g;
89 * Service's own private multiplier
91 static gcry_mpi_t my_mu;
94 * Service's own private exponent
96 static gcry_mpi_t my_lambda;
99 * Head of our double linked list for client-requests sent to us.
100 * for all of these elements we calculate a vector product with a remote peer
101 * split between service->service and client->service for simplicity
103 static struct ServiceSession * from_client_head;
105 * Tail of our double linked list for client-requests sent to us.
106 * for all of these elements we calculate a vector product with a remote peer
107 * split between service->service and client->service for simplicity
109 static struct ServiceSession * from_client_tail;
112 * Head of our double linked list for service-requests sent to us.
113 * for all of these elements we help the requesting service in calculating a vector product
114 * split between service->service and client->service for simplicity
116 static struct ServiceSession * from_service_head;
119 * Tail of our double linked list for service-requests sent to us.
120 * for all of these elements we help the requesting service in calculating a vector product
121 * split between service->service and client->service for simplicity
123 static struct ServiceSession * from_service_tail;
126 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
128 static int do_shutdown;
130 ///////////////////////////////////////////////////////////////////////////////
132 ///////////////////////////////////////////////////////////////////////////////
135 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
140 gcry_sexp_t gen_parms;
142 gcry_sexp_t tmp_sexp;
151 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
152 GNUNET_assert (0 == gcry_sexp_build (&gen_parms, &erroff,
153 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
156 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_parms));
157 gcry_sexp_release (gen_parms);
159 // get n and d of our publickey as MPI
160 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
161 GNUNET_assert (tmp_sexp);
162 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
163 gcry_sexp_release (tmp_sexp);
164 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
165 GNUNET_assert (tmp_sexp);
166 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
167 gcry_sexp_release (tmp_sexp);
168 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
169 GNUNET_assert (tmp_sexp);
170 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
171 gcry_sexp_release (key);
173 tmp1 = gcry_mpi_new (0);
174 tmp2 = gcry_mpi_new (0);
175 gcd = gcry_mpi_new (0);
176 my_g = gcry_mpi_new (0);
177 my_mu = gcry_mpi_new (0);
178 my_nsquare = gcry_mpi_new (0);
179 my_lambda = gcry_mpi_new (0);
182 // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
183 gcry_mpi_sub_ui (tmp1, p, 1);
184 gcry_mpi_sub_ui (tmp2, q, 1);
185 gcry_mpi_gcd (gcd, tmp1, tmp2);
186 gcry_mpi_set (my_lambda, tmp1);
187 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
188 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
191 gcry_mpi_mul (my_nsquare, my_n, my_n);
197 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
198 // g must be smaller than n^2
199 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
202 // g must have gcd == 1 with n^2
203 gcry_mpi_gcd (gcd, my_g, my_nsquare);
205 while (gcry_mpi_cmp_ui (gcd, 1));
207 // is this a valid g?
208 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
209 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
210 gcry_mpi_sub_ui (tmp1, tmp1, 1);
211 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
212 gcry_mpi_gcd (gcd, tmp1, my_n);
214 while (gcry_mpi_cmp_ui (gcd, 1));
216 // calculate our mu based on g and n.
217 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
218 gcry_mpi_invm (my_mu, tmp1, my_n);
220 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
221 "(public-key (paillier (n %M)(g %M)))",
224 // get the length of this sexpression
225 my_pubkey_external_length = gcry_sexp_sprint (key,
230 GNUNET_assert (my_pubkey_external_length > 0);
231 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
233 // convert the sexpression to canonical format
234 gcry_sexp_sprint (key,
237 my_pubkey_external_length);
239 gcry_sexp_release (key);
241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
246 * If target != size, move target bytes to the
247 * end of the size-sized buffer and zero out the
248 * first target-size bytes.
250 * @param buf original buffer
251 * @param size number of bytes in the buffer
252 * @param target target size of the buffer
255 adjust (unsigned char *buf, size_t size, size_t target)
259 memmove (&buf[target - size], buf, size);
260 memset (buf, 0, target - size);
266 * encrypts an element using the paillier crypto system
268 * @param c ciphertext (output)
270 * @param g the public base
271 * @param r random base (optional) gets generated and if not NULL but uninitialized
272 * @param n the module from which which r is chosen (Z*_n)
273 * @param n_square the module for encryption, for performance reasons.
276 encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t r, gcry_mpi_t n, gcry_mpi_t n_square)
278 #ifndef DISABLE_CRYPTO
280 int release_r = GNUNET_NO;
282 GNUNET_assert (tmp = gcry_mpi_new (0));
285 GNUNET_assert (r = gcry_mpi_new (0));
286 release_r = GNUNET_YES;
288 while (0 <= gcry_mpi_cmp (r, n) || 0 >= gcry_mpi_cmp_ui (r, 1))
290 gcry_mpi_randomize (r, KEYBITS, GCRY_WEAK_RANDOM);
291 // r must be 1 < r < n
296 gcry_mpi_powm (c, g, m, n_square);
297 gcry_mpi_powm (tmp, r, n, n_square);
298 gcry_mpi_mulm (c, tmp, c, n_square);
300 gcry_mpi_release (tmp);
301 if (GNUNET_YES == release_r)
302 gcry_mpi_release (r);
310 * decrypts an element using the paillier crypto system
312 * @param m plaintext (output)
313 * @param c the ciphertext
314 * @param mu the modifier to correct encryption
315 * @param lambda the private exponent
316 * @param n the outer module for decryption
317 * @param n_square the inner module for decryption
320 decrypt_element (gcry_mpi_t m, gcry_mpi_t c, gcry_mpi_t mu, gcry_mpi_t lambda, gcry_mpi_t n, gcry_mpi_t n_square)
322 #ifndef DISABLE_CRYPTO
323 gcry_mpi_powm (m, c, lambda, n_square);
324 gcry_mpi_sub_ui (m, m, 1);
325 gcry_mpi_div (m, NULL, m, n, 0);
326 gcry_mpi_mulm (m, m, mu, n);
334 * computes the square sum over a vector of a given length.
336 * @param vector the vector to encrypt
337 * @param length the length of the vector
338 * @return an MPI value containing the calculated sum, never NULL
341 compute_square_sum (gcry_mpi_t * vector, uint16_t length)
347 GNUNET_assert (sum = gcry_mpi_new (0));
348 GNUNET_assert (elem = gcry_mpi_new (0));
350 // calculare E(sum (ai ^ 2), publickey)
351 for (i = 0; i < length; i++)
353 gcry_mpi_mul (elem, vector[i], vector[i]);
354 gcry_mpi_add (sum, sum, elem);
356 gcry_mpi_release (elem);
363 * Primitive callback for copying over a message, as they
364 * usually are too complex to be handled in the callback itself.
365 * clears a session-callback, if a session was handed over and the transmit handle was stored
367 * @param cls the message object
368 * @param size the size of the buffer we got
369 * @param buf the buffer to copy the message to
370 * @return 0 if we couldn't copy, else the size copied over
373 do_send_message (void *cls, size_t size, void *buf)
375 struct MessageObject * info = cls;
376 struct GNUNET_MessageHeader * msg;
379 GNUNET_assert (info);
384 if (ntohs (msg->size) == size)
386 memcpy (buf, msg, size);
390 // reset the transmit handle, if necessary
391 if (info->transmit_handle)
392 *info->transmit_handle = NULL;
394 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
395 "Sent a message of type %hu.\n",
404 * initializes a new vector with fresh MPI values (=0) of a given length
406 * @param length of the vector to create
407 * @return the initialized vector, never NULL
410 initialize_mpi_vector (uint16_t length)
413 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
415 for (i = 0; i < length; i++)
416 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
422 * permutes an MPI vector according to the given permutation vector
424 * @param vector the vector to permuted
425 * @param perm the permutation to use
426 * @param length the length of the vectors
427 * @return the permuted vector (same as input), never NULL
430 permute_vector (gcry_mpi_t * vector,
434 gcry_mpi_t tmp[length];
437 GNUNET_assert (length > 0);
440 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
442 // permute vector according to given
443 for (i = 0; i < length; i++)
444 vector[i] = tmp[perm[i]];
451 * Populate a vector with random integer values and convert them to
453 * @param length the length of the vector we must generate
454 * @return an array of MPI values with random values
457 generate_random_vector (uint16_t length)
459 gcry_mpi_t * random_vector;
463 random_vector = initialize_mpi_vector (length);
464 for (i = 0; i < length; i++)
466 value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
468 // long to gcry_mpi_t
470 gcry_mpi_sub_ui (random_vector[i],
474 random_vector[i] = gcry_mpi_set_ui (random_vector[i], value);
477 return random_vector;
482 * Finds a not terminated client/service session in the
483 * given DLL based on session key, element count and state.
485 * @param tail - the tail of the DLL
486 * @param my - the session to compare it to
487 * @return a pointer to a matching session,
490 static struct ServiceSession *
491 find_matching_session (struct ServiceSession * tail,
492 const struct GNUNET_HashCode * key,
493 uint16_t element_count,
494 enum SessionState * state,
495 const struct GNUNET_PeerIdentity * peerid)
497 struct ServiceSession * curr;
499 for (curr = tail; NULL != curr; curr = curr->prev)
501 // if the key matches, and the element_count is same
502 if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
503 && (curr->element_count == element_count))
505 // if incoming state is NULL OR is same as state of the queued request
506 if ((NULL == state) || (curr->state == *state))
508 // if peerid is NULL OR same as the peer Id in the queued request
510 || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
511 // matches and is not an already terminated session
522 destroy_tunnel (void *cls,
523 const struct GNUNET_SCHEDULER_TaskContext *tc)
525 struct ServiceSession * session = cls;
529 GNUNET_MESH_tunnel_destroy (session->tunnel);
530 session->tunnel = NULL;
532 session->service_transmit_handle = NULL;
533 // we need to set this to NULL so there is no problem with double-cancel later on.
538 free_session (struct ServiceSession * session)
542 if (FINALIZED != session->state)
546 for (i = 0; i < session->used_element_count; i++)
547 gcry_mpi_release (session->a[i]);
549 GNUNET_free (session->a);
551 if (session->product)
552 gcry_mpi_release (session->product);
554 if (session->remote_pubkey)
555 gcry_sexp_release (session->remote_pubkey);
557 GNUNET_free_non_null (session->vector);
560 GNUNET_free (session);
562 ///////////////////////////////////////////////////////////////////////////////
563 // Event and Message Handlers
564 ///////////////////////////////////////////////////////////////////////////////
568 * A client disconnected.
570 * Remove the associated session(s), release datastructures
571 * and cancel pending outgoing transmissions to the client.
572 * if the session has not yet completed, we also cancel Alice's request to Bob.
574 * @param cls closure, NULL
575 * @param client identification of the client
578 handle_client_disconnect (void *cls,
579 struct GNUNET_SERVER_Client
582 struct ServiceSession * elem;
583 struct ServiceSession * next;
585 // start from the tail, old stuff will be there...
586 for (elem = from_client_head; NULL != elem; elem = next)
589 if (elem->client != client)
592 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Client (%p) disconnected from us.\n"), client);
593 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, elem);
595 if (!(elem->role == BOB && elem->state == FINALIZED))
597 //we MUST terminate any client message underway
598 if (elem->service_transmit_handle && elem->tunnel)
599 GNUNET_MESH_notify_transmit_ready_cancel (elem->service_transmit_handle);
600 if (elem->tunnel && elem->state == WAITING_FOR_RESPONSE_FROM_SERVICE)
601 destroy_tunnel (elem, NULL);
609 * Notify the client that the session has succeeded or failed completely.
610 * This message gets sent to
611 * * alice's client if bob disconnected or to
612 * * bob's client if the operation completed or alice disconnected
614 * @param client_session the associated client session
615 * @return GNUNET_NO, if we could not notify the client
616 * GNUNET_YES if we notified it.
619 prepare_client_end_notification (void * cls,
620 const struct GNUNET_SCHEDULER_TaskContext * tc)
622 struct ServiceSession * session = cls;
623 struct GNUNET_SCALARPRODUCT_client_response * msg;
624 struct MessageObject * msg_obj;
626 msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
627 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
628 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
629 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
630 msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
631 // 0 size and the first char in the product is 0, which should never be zero if encoding is used.
632 msg->product_length = htonl (0);
634 msg_obj = GNUNET_new (struct MessageObject);
635 msg_obj->msg = &msg->header;
636 msg_obj->transmit_handle = NULL; // do not reset the transmit handle, please
638 //transmit this message to our client
639 session->client_transmit_handle =
640 GNUNET_SERVER_notify_transmit_ready (session->client,
641 sizeof (struct GNUNET_SCALARPRODUCT_client_response),
642 GNUNET_TIME_UNIT_FOREVER_REL,
647 // if we could not even queue our request, something is wrong
648 if ( ! session->client_transmit_handle)
651 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)! This is OK if it was disconnected beforehand already.\n"), session->client);
652 // usually gets freed by do_send_message
653 GNUNET_free (msg_obj);
657 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
659 free_session(session);
665 * generates the response message to be sent to alice after computing
666 * the values (1), (2), S and S'
667 * (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)})$
668 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
669 * S: $S := E_A(sum (r_i + b_i)^2)$
670 * S': $S' := E_A(sum r_i^2)$
672 * @param kp (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)})$
673 * @param kq (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
674 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
675 * @param stick S': $S' := E_A(sum r_i^2)$
676 * @param request the associated requesting session with alice
677 * @param response the associated responder session with bob's client
678 * @return GNUNET_SYSERR if the function was called with NULL parameters or if there was an error
679 * GNUNET_NO if we could not send our message
680 * GNUNET_OK if the operation succeeded
683 prepare_service_response (gcry_mpi_t * kp,
687 struct ServiceSession * request,
688 struct ServiceSession * response)
690 struct GNUNET_SCALARPRODUCT_service_response * msg;
691 uint16_t msg_length = 0;
692 unsigned char * current = NULL;
693 unsigned char * element_exported = NULL;
694 size_t element_length = 0;
697 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
698 + 2 * request->used_element_count * PAILLIER_ELEMENT_LENGTH // kp, kq
699 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
701 msg = GNUNET_malloc (msg_length);
703 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
704 msg->header.size = htons (msg_length);
705 msg->element_count = htons (request->element_count);
706 msg->used_element_count = htons (request->used_element_count);
707 memcpy (&msg->key, &request->key, sizeof (struct GNUNET_HashCode));
708 current = (unsigned char *) &msg[1];
710 // 4 times the same logics with slight variations.
711 // doesn't really justify having 2 functions for that
712 // so i put it into blocks to enhance readability
715 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
716 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
717 element_exported, PAILLIER_ELEMENT_LENGTH,
720 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
721 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
722 GNUNET_free (element_exported);
723 current += PAILLIER_ELEMENT_LENGTH;
728 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
729 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
730 element_exported, PAILLIER_ELEMENT_LENGTH,
733 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
734 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
735 GNUNET_free (element_exported);
736 current += PAILLIER_ELEMENT_LENGTH;
740 for (i = 0; i < request->used_element_count; i++)
742 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
743 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
744 element_exported, PAILLIER_ELEMENT_LENGTH,
747 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
748 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
749 GNUNET_free (element_exported);
750 current += PAILLIER_ELEMENT_LENGTH;
755 for (i = 0; i < request->used_element_count; i++)
757 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
758 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
759 element_exported, PAILLIER_ELEMENT_LENGTH,
762 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
763 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
764 GNUNET_free (element_exported);
765 current += PAILLIER_ELEMENT_LENGTH;
768 if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= msg_length)
770 struct MessageObject * msg_obj;
772 msg_obj = GNUNET_new (struct MessageObject);
773 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
774 msg_obj->transmit_handle = (void *) &request->service_transmit_handle; //and reset the transmit handle
775 request->service_transmit_handle =
776 GNUNET_MESH_notify_transmit_ready (request->tunnel,
778 GNUNET_TIME_UNIT_FOREVER_REL,
779 &request->peer, //must be specified, we are a slave/participant/non-owner
783 // we don't care if it could be send or not. either way, the session is over for us.
784 request->state = FINALIZED;
785 response->state = FINALIZED;
789 // TODO FEATURE: fallback to fragmentation, in case the message is too long
790 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!)\n"));
793 //disconnect our client
794 if ( ! request->service_transmit_handle)
796 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
797 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, response);
798 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
799 &prepare_client_end_notification,
810 * (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)})$
811 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
812 * S: $S := E_A(sum (r_i + b_i)^2)$
813 * S': $S' := E_A(sum r_i^2)$
815 * @param request the requesting session + bob's requesting peer
816 * @param response the responding session + bob's client handle
817 * @return GNUNET_SYSERR if the computation failed
818 * GNUNET_OK if everything went well.
821 compute_service_response (struct ServiceSession * request,
822 struct ServiceSession * response)
824 int i, j, ret = GNUNET_SYSERR;
828 gcry_mpi_t * r = NULL;
829 gcry_mpi_t * kp = NULL;
830 gcry_mpi_t * kq = NULL;
839 gcry_mpi_t stick = NULL;
840 gcry_mpi_t remote_n = NULL;
841 gcry_mpi_t remote_nsquare;
842 gcry_mpi_t remote_g = NULL;
846 count = request->used_element_count;
848 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
849 ap = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
850 bp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
851 aq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
852 bq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
853 rp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
854 rq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
856 // convert responder session to from long to mpi
857 for (i = 0, j = 0; i < response->element_count && j < count; i++)
859 if (request->mask[i / 8] & (1 << (i % 8)))
861 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
862 // long to gcry_mpi_t
863 if (0 > response->vector[i])
865 b[j] = gcry_mpi_new (0);
866 gcry_mpi_sub_ui (b[j], b[j], value);
870 b[j] = gcry_mpi_set_ui (NULL, value);
875 GNUNET_free (response->vector);
876 response->vector = NULL;
878 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
882 gcry_sexp_release (request->remote_pubkey);
883 request->remote_pubkey = NULL;
886 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
890 gcry_sexp_release (tmp_exp);
893 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
894 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
895 gcry_sexp_release (tmp_exp);
896 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
897 gcry_sexp_release (request->remote_pubkey);
898 request->remote_pubkey = NULL;
902 gcry_mpi_release (remote_n);
905 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
909 gcry_mpi_release (remote_n);
910 gcry_sexp_release (tmp_exp);
913 gcry_sexp_release (tmp_exp);
915 // generate r, p and q
916 r = generate_random_vector (count);
917 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
918 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
919 //initialize the result vectors
920 kp = initialize_mpi_vector (count);
921 kq = initialize_mpi_vector (count);
923 // copy the REFERNCES of a, b and r into aq and bq. we will not change
924 // those values, thus we can work with the references
925 memcpy (ap, request->a, sizeof (gcry_mpi_t) * count);
926 memcpy (aq, request->a, sizeof (gcry_mpi_t) * count);
927 memcpy (bp, b, sizeof (gcry_mpi_t) * count);
928 memcpy (bq, b, sizeof (gcry_mpi_t) * count);
929 memcpy (rp, r, sizeof (gcry_mpi_t) * count);
930 memcpy (rq, r, sizeof (gcry_mpi_t) * count);
932 // generate p and q permutations for a, b and r
933 GNUNET_assert (permute_vector (ap, p, count));
934 GNUNET_assert (permute_vector (bp, p, count));
935 GNUNET_assert (permute_vector (rp, p, count));
936 GNUNET_assert (permute_vector (aq, q, count));
937 GNUNET_assert (permute_vector (bq, q, count));
938 GNUNET_assert (permute_vector (rq, q, count));
940 // encrypt the element
941 // for the sake of readability I decided to have dedicated permutation
942 // vectors, which get rid of all the lookups in p/q.
943 // however, ap/aq are not absolutely necessary but are just abstraction
944 // Calculate Kp = E(a_pi) + E(-r_pi - b_pi)
945 for (i = 0; i < count; i++)
948 gcry_mpi_sub (kp[i], kp[i], rp[i]);
949 gcry_mpi_sub (kp[i], kp[i], bp[i]);
950 encrypt_element (kp[i], kp[i], NULL, remote_g, remote_n, remote_nsquare);
952 // E(-r_pi - b_pi) * E(a_pi) == E(a + (-r -b))
953 //gcry_mpi_mulm (kp[i], kp[i], ap[i], remote_nsquare);
954 gcry_mpi_add (kp[i], kp[i], ap[i]);
960 // Calculate Kq = E(a_qi) + E( -r_qi)
961 for (i = 0; i < count; i++)
964 gcry_mpi_sub (kq[i], kq[i], rq[i]);
965 encrypt_element (kq[i], kq[i], NULL, remote_g, remote_n, remote_nsquare);
967 // E(-r_qi) * E(a_qi) == E(aqi + (- rqi))
968 //gcry_mpi_mulm (kq[i], kq[i], aq[i], remote_nsquare);
969 gcry_mpi_add (kq[i], kq[i], aq[i]);
975 // Calculate S' = E(SUM( r_i^2 ))
976 stick = compute_square_sum (r, count);
977 encrypt_element (stick, stick, NULL, remote_g, remote_n, remote_nsquare);
979 // Calculate S = E(SUM( (r_i + b_i)^2 ))
980 for (i = 0; i < count; i++)
982 gcry_mpi_add (r[i], r[i], b[i]);
984 s = compute_square_sum (r, count);
985 encrypt_element (s, s, NULL, remote_g, remote_n, remote_nsquare);
986 gcry_mpi_release (remote_n);
987 gcry_mpi_release (remote_g);
988 gcry_mpi_release (remote_nsquare);
991 for (i = 0; i < count; i++)
992 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
993 gcry_mpi_release (r[i]);
995 // copy the Kp[], Kq[], S and Stick into a new message
996 if (GNUNET_YES != prepare_service_response (kp, kq, s, stick, request, response))
997 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Failed to communicate with `%s', scalar product calculation aborted.\n"),
998 GNUNET_i2s (&request->peer));
1002 for (i = 0; i < count; i++)
1004 gcry_mpi_release (kq[i]);
1005 gcry_mpi_release (kp[i]);
1008 gcry_mpi_release (s);
1009 gcry_mpi_release (stick);
1012 for (i = 0; i < count; i++)
1014 gcry_mpi_release (b[i]);
1015 gcry_mpi_release (request->a[i]);
1019 GNUNET_free (request->a);
1027 * Executed by Alice, fills in a service-request message and sends it to the given peer
1029 * @param session the session associated with this request, then also holds the CORE-handle
1030 * @return #GNUNET_SYSERR if we could not send the message
1031 * #GNUNET_NO if the message was too large
1032 * #GNUNET_OK if we sent it
1035 prepare_service_request (void *cls,
1036 const struct GNUNET_PeerIdentity * peer,
1037 const struct GNUNET_ATS_Information * atsi)
1039 struct ServiceSession * session = cls;
1040 unsigned char * current;
1041 struct GNUNET_SCALARPRODUCT_service_request * msg;
1042 struct MessageObject * msg_obj;
1045 uint16_t msg_length;
1046 size_t element_length = 0; //gets initialized by gcry_mpi_print, but the compiler doesn't know that
1051 GNUNET_assert (NULL != cls);
1052 GNUNET_assert (NULL != peer);
1053 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (peer));
1055 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1056 + session->used_element_count * PAILLIER_ELEMENT_LENGTH
1057 + session->mask_length
1058 + my_pubkey_external_length;
1060 if (GNUNET_SERVER_MAX_MESSAGE_SIZE < sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1061 + session->used_element_count * PAILLIER_ELEMENT_LENGTH
1062 + session->mask_length
1063 + my_pubkey_external_length)
1065 // TODO FEATURE: fallback to fragmentation, in case the message is too long
1066 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1067 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1068 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1069 &prepare_client_end_notification,
1073 msg = GNUNET_malloc (msg_length);
1075 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
1076 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1077 msg->mask_length = htons (session->mask_length);
1078 msg->pk_length = htons (my_pubkey_external_length);
1079 msg->used_element_count = htons (session->used_element_count);
1080 msg->element_count = htons (session->element_count);
1081 msg->header.size = htons (msg_length);
1083 // fill in the payload
1084 current = (unsigned char *) &msg[1];
1085 // copy over the mask
1086 memcpy (current, session->mask, session->mask_length);
1087 // copy over our public key
1088 current += session->mask_length;
1089 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1090 current += my_pubkey_external_length;
1092 // now copy over the element vector
1093 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
1094 a = gcry_mpi_new (KEYBITS * 2);
1095 r = gcry_mpi_new (KEYBITS * 2);
1096 // encrypt our vector and generate string representations
1097 for (i = 0, j = 0; i < session->element_count; i++)
1099 // if this is a used element...
1100 if (session->mask[i / 8] & 1 << (i % 8))
1102 unsigned char * element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1103 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1105 // long to gcry_mpi_t
1106 if (session->vector[i] < 0)
1108 a = gcry_mpi_set_ui (NULL, 0);
1109 gcry_mpi_sub_ui (a, a, value);
1112 a = gcry_mpi_set_ui (NULL, value);
1114 // multiply with a given factor to avoid disclosing 1
1115 session->a[j++] = gcry_mpi_set (NULL, a);
1116 encrypt_element (a, a, r, my_g, my_n, my_nsquare);
1118 // get representation as string
1119 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1120 GNUNET_assert ( ! gcry_mpi_print (GCRYMPI_FMT_USG,
1121 element_exported, PAILLIER_ELEMENT_LENGTH,
1125 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1126 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1128 // copy over to the message
1129 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1130 current += PAILLIER_ELEMENT_LENGTH;
1133 gcry_mpi_release (a);
1134 gcry_mpi_release (r);
1136 msg_obj = GNUNET_new (struct MessageObject);
1137 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
1138 msg_obj->transmit_handle = (void *) &session->service_transmit_handle; //and reset the transmit handle
1139 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transmitting service request.\n"));
1141 //transmit via mesh messaging
1142 session->state = WAITING_FOR_RESPONSE_FROM_SERVICE;
1143 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1144 GNUNET_TIME_UNIT_FOREVER_REL,
1145 peer, //multicast to all targets, maybe useful in the future
1149 if ( ! session->service_transmit_handle)
1151 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not send mutlicast message to tunnel!\n"));
1152 GNUNET_free (msg_obj);
1154 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1155 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1156 &prepare_client_end_notification,
1164 * Method called whenever a peer has disconnected from the tunnel.
1165 * Implementations of this callback must NOT call
1166 * #GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
1167 * to run in some other task later. However, calling
1168 * #GNUNET_MESH_notify_transmit_ready_cancel is allowed.
1170 * @param cls closure
1171 * @param peer peer identity the tunnel stopped working with
1174 tunnel_peer_disconnect_handler (void *cls, const struct GNUNET_PeerIdentity * peer)
1176 // as we have only one peer connected in each session, just remove the session and say good bye
1177 struct ServiceSession * session = cls;
1178 struct ServiceSession * curr;
1180 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1181 "Peer (%s) disconnected from our tunnel!\n",
1184 if ((session->role == ALICE) && (FINALIZED != session->state) && ( ! do_shutdown))
1186 for (curr = from_client_head; NULL != curr; curr = curr->next)
1187 if (curr == session)
1189 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1192 // FIXME: dangling tasks, code duplication, use-after-free, fun...
1193 GNUNET_SCHEDULER_add_now (&destroy_tunnel,
1195 // if this happened before we received the answer, we must terminate the session
1196 GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
1203 * Handler for a client request message.
1204 * Can either be type A or B
1205 * A: request-initiation to compute a scalar product with a peer
1206 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1208 * @param cls closure
1209 * @param client identification of the client
1210 * @param message the actual message
1213 handle_client_request (void *cls,
1214 struct GNUNET_SERVER_Client *client,
1215 const struct GNUNET_MessageHeader *message)
1217 const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
1218 struct ServiceSession * session;
1219 uint16_t element_count;
1220 uint16_t mask_length;
1225 GNUNET_assert (message);
1227 //we need at least a peer and one message id to compare
1228 if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size))
1230 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1231 _ ("Too short message received from client!\n"));
1232 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1236 msg_type = ntohs (msg->header.type);
1237 element_count = ntohs (msg->element_count);
1238 mask_length = ntohs (msg->mask_length);
1240 //sanity check: is the message as long as the message_count fields suggests?
1241 if (( ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) + element_count * sizeof (int32_t) + mask_length))
1242 || (0 == element_count))
1244 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1245 _ ("Invalid message received from client, session information incorrect!\n"));
1246 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1250 // do we have a duplicate session here already?
1251 if (NULL != find_matching_session (from_client_tail,
1256 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Duplicate session information received, cannot create new session with key `%s'\n"), GNUNET_h2s (&msg->key));
1257 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1261 session = GNUNET_new (struct ServiceSession);
1262 session->client = client;
1263 session->element_count = element_count;
1264 session->mask_length = mask_length;
1265 // get our transaction key
1266 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1267 //allocate memory for vector and encrypted vector
1268 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1269 vector = (int32_t *) & msg[1];
1271 if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type)
1273 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"), GNUNET_h2s (&session->key));
1275 session->role = ALICE;
1277 session->mask = GNUNET_malloc (mask_length);
1278 memcpy (session->mask, &vector[element_count], mask_length);
1280 // copy over the elements
1281 session->used_element_count = 0;
1282 for (i = 0; i < element_count; i++)
1284 session->vector[i] = ntohl (vector[i]);
1285 if (session->vector[i] == 0)
1286 session->mask[i / 8] &= ~(1 << (i % 8));
1287 if (session->mask[i / 8] & (1 << (i % 8)))
1288 session->used_element_count++;
1291 if ( ! session->used_element_count)
1293 GNUNET_break_op (0);
1294 GNUNET_free (session->vector);
1295 GNUNET_free (session->a);
1296 GNUNET_free (session);
1297 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1300 //session with ourself makes no sense!
1301 if ( ! memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1304 GNUNET_free (session->vector);
1305 GNUNET_free (session->a);
1306 GNUNET_free (session);
1307 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1311 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1312 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Creating new tunnel to for session with key %s.\n"), GNUNET_h2s (&session->key));
1313 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1314 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1315 prepare_service_request,
1316 tunnel_peer_disconnect_handler,
1318 if ( ! session->tunnel)
1321 GNUNET_free (session->vector);
1322 GNUNET_free (session->a);
1323 GNUNET_free (session);
1324 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1327 GNUNET_MESH_peer_request_connect_add (session->tunnel, &session->peer);
1328 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1329 session->state = WAITING_FOR_BOBS_CONNECT;
1333 struct ServiceSession * requesting_session;
1334 enum SessionState needed_state = REQUEST_FROM_SERVICE_RECEIVED;
1336 session->role = BOB;
1337 session->mask = NULL;
1338 // copy over the elements
1339 session->used_element_count = element_count;
1340 for (i = 0; i < element_count; i++)
1341 session->vector[i] = ntohl (vector[i]);
1342 session->state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
1344 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1345 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1346 //check if service queue contains a matching request
1347 requesting_session = find_matching_session (from_service_tail,
1349 session->element_count,
1350 &needed_state, NULL);
1351 if (NULL != requesting_session)
1353 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got client-responder-session with key %s and a matching service-request-session set, processing.\n"), GNUNET_h2s (&session->key));
1354 if (GNUNET_OK != compute_service_response (requesting_session, session))
1356 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1357 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1358 &prepare_client_end_notification,
1363 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got client-responder-session with key %s but NO matching service-request-session set, queuing element for later use.\n"), GNUNET_h2s (&session->key));
1364 // no matching session exists yet, store the response
1365 // for later processing by handle_service_request()
1371 * Function called for inbound tunnels.
1373 * @param cls closure
1374 * @param tunnel new handle to the tunnel
1375 * @param initiator peer that started the tunnel
1376 * @param atsi performance information for the tunnel
1377 * @return initial tunnel context for the tunnel
1378 * (can be NULL -- that's not an error)
1381 tunnel_incoming_handler (void *cls, struct GNUNET_MESH_Tunnel *tunnel,
1382 const struct GNUNET_PeerIdentity *initiator,
1383 const struct GNUNET_ATS_Information *atsi)
1386 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1388 memcpy (&c->peer, initiator, sizeof (struct GNUNET_PeerIdentity));
1396 * Function called whenever an inbound tunnel is destroyed. Should clean up
1397 * any associated state.
1399 * @param cls closure (set from #GNUNET_MESH_connect)
1400 * @param tunnel connection to the other end (henceforth invalid)
1401 * @param tunnel_ctx place where local state associated
1402 * with the tunnel is stored (our 'struct TunnelState')
1405 tunnel_destruction_handler (void *cls,
1406 const struct GNUNET_MESH_Tunnel *tunnel,
1409 struct ServiceSession * service_session = tunnel_ctx;
1410 struct ServiceSession * client_session;
1411 struct ServiceSession * curr;
1413 GNUNET_assert (service_session);
1414 if (!memcmp (&service_session->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1416 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Tunnel destroyed, terminating session with peer (%s)\n"), GNUNET_i2s (&service_session->peer));
1417 // remove the session, unless it has already been dequeued, but somehow still active
1418 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1419 for (curr = from_service_head; NULL != curr; curr = curr->next)
1420 if (curr == service_session)
1422 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1425 // there is a client waiting for this service session, terminate it, too!
1426 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1427 client_session = find_matching_session (from_client_tail,
1428 &service_session->key,
1429 service_session->element_count,
1431 free_session (service_session);
1433 // the client has to check if it was waiting for a result
1434 // or if it was a responder, no point in adding more statefulness
1435 if (client_session && ( ! do_shutdown))
1437 // remove the session, we just found it in the queue, so it must be there
1438 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, client_session);
1439 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1440 &prepare_client_end_notification,
1447 * Compute our scalar product, done by Alice
1449 * @param session - the session associated with this computation
1450 * @param kp - (1) from the protocol definition:
1451 * $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)})$
1452 * @param kq - (2) from the protocol definition:
1453 * $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
1454 * @param s - S from the protocol definition:
1455 * $S := E_A(sum (r_i + b_i)^2)$
1456 * @param stick - S' from the protocol definition:
1457 * $S' := E_A(sum r_i^2)$
1458 * @return product as MPI, never NULL
1461 compute_scalar_product (struct ServiceSession * session,
1462 gcry_mpi_t * kp, gcry_mpi_t * kq, gcry_mpi_t s, gcry_mpi_t stick)
1475 count = session->used_element_count;
1476 tmp = gcry_mpi_new (KEYBITS);
1477 for (i = 0; i < count; i++)
1479 decrypt_element (kp[i], kp[i], my_mu, my_lambda, my_n, my_nsquare);
1480 decrypt_element (kq[i], kq[i], my_mu, my_lambda, my_n, my_nsquare);
1483 // calculate t = E(sum(ai))
1484 t = compute_square_sum (session->a, count);
1485 encrypt_element (t, t, NULL, my_g, my_n, my_nsquare);
1488 u = gcry_mpi_new (0);
1489 tmp = compute_square_sum (kp, count);
1490 gcry_mpi_sub (u, u, tmp);
1491 encrypt_element (u, u, NULL, my_g, my_n, my_nsquare);
1492 gcry_mpi_release (tmp);
1495 utick = gcry_mpi_new (0);
1496 tmp = compute_square_sum (kq, count);
1497 gcry_mpi_sub (utick, utick, tmp);
1498 encrypt_element (utick, utick, NULL, my_g, my_n, my_nsquare);
1499 gcry_mpi_release (tmp);
1501 GNUNET_assert (p = gcry_mpi_new (0));
1502 GNUNET_assert (ptick = gcry_mpi_new (0));
1505 gcry_mpi_add (p, s, t);
1506 //gcry_mpi_mulm (p, p, u, my_nsquare);
1507 gcry_mpi_add (p, p, u);
1508 decrypt_element (p, p, my_mu, my_lambda, my_n, my_nsquare);
1511 gcry_mpi_add (ptick, stick, t);
1512 //gcry_mpi_mulm (ptick, ptick, utick, my_nsquare);
1513 gcry_mpi_add (ptick, ptick, utick);
1514 decrypt_element (ptick, ptick, my_mu, my_lambda, my_n, my_nsquare);
1516 gcry_mpi_release (t);
1517 gcry_mpi_release (u);
1518 gcry_mpi_release (utick);
1521 GNUNET_assert (product = gcry_mpi_new (0));
1522 gcry_mpi_sub (product, p, ptick);
1523 gcry_mpi_release (p);
1524 gcry_mpi_release (ptick);
1525 divider = gcry_mpi_set_ui (NULL, 2);
1526 gcry_mpi_div (product, NULL, product, divider, 0);
1528 gcry_mpi_release (divider);
1529 for (i = 0; i < count; i++)
1530 gcry_mpi_release (session->a[i]);
1531 GNUNET_free (session->a);
1539 * prepare the response we will send to alice or bobs' clients.
1540 * in Bobs case the product will be NULL.
1542 * @param session the session associated with our client.
1545 prepare_client_response (void *cls,
1546 const struct GNUNET_SCHEDULER_TaskContext *tc)
1548 struct ServiceSession * session = cls;
1549 struct GNUNET_SCALARPRODUCT_client_response * msg;
1550 unsigned char * product_exported = NULL;
1551 size_t product_length = 0;
1552 uint16_t msg_length = 0;
1553 struct MessageObject * msg_obj;
1555 if (session->product)
1557 // get representation as string // FIXME: just log (& survive!)
1558 GNUNET_assert ( ! gcry_mpi_aprint (GCRYMPI_FMT_USG,
1562 gcry_mpi_release (session->product);
1563 session->product = NULL;
1566 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) + product_length;
1567 msg = GNUNET_malloc (msg_length);
1568 memcpy (&msg[1], product_exported, product_length);
1569 GNUNET_free_non_null (product_exported);
1570 msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
1571 msg->header.size = htons (msg_length);
1572 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1573 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1574 msg->product_length = htonl (product_length);
1576 msg_obj = GNUNET_new (struct MessageObject);
1577 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
1578 msg_obj->transmit_handle = NULL; // don't reset the transmit handle
1580 //transmit this message to our client
1581 session->client_transmit_handle =
1582 GNUNET_SERVER_notify_transmit_ready (session->client, // FIXME: use after free possibility during shutdown
1584 GNUNET_TIME_UNIT_FOREVER_REL,
1587 if ( ! session->client_transmit_handle)
1589 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)! This probably is OK if the client disconnected before us.\n"), session->client);
1590 session->client = NULL;
1591 // callback was not called!
1592 GNUNET_free (msg_obj);
1596 // gracefully sent message, just terminate session structure
1597 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sent result to client (%p), this session (%s) has ended!\n"), session->client, GNUNET_h2s (&session->key));
1598 free_session (session);
1603 * Handle a request from another service to calculate a scalarproduct with us.
1605 * @param cls closure (set from #GNUNET_MESH_connect)
1606 * @param tunnel connection to the other end
1607 * @param tunnel_ctx place to store local state associated with the tunnel
1608 * @param sender who sent the message
1609 * @param message the actual message
1610 * @param atsi performance data for the connection
1611 * @return #GNUNET_OK to keep the connection open,
1612 * #GNUNET_SYSERR to close it (signal serious error)
1615 handle_service_request (void *cls,
1616 struct GNUNET_MESH_Tunnel * tunnel,
1618 const struct GNUNET_PeerIdentity * sender,
1619 const struct GNUNET_MessageHeader * message,
1620 const struct GNUNET_ATS_Information * atsi)
1622 struct ServiceSession * session;
1623 const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
1624 uint16_t mask_length;
1626 uint16_t used_elements;
1627 uint16_t element_count;
1628 uint16_t msg_length;
1629 unsigned char * current;
1630 struct ServiceSession * responder_session;
1632 enum SessionState needed_state;
1634 session = (struct ServiceSession *) * tunnel_ctx;
1635 // is this tunnel already in use?
1636 if ( (session->next) || (from_service_head == session))
1638 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Got a service request over a tunnel that is already in use, ignoring!\n"));
1639 return GNUNET_SYSERR;
1641 // Check if message was sent by me, which would be bad!
1642 if ( ! memcmp (sender, &me, sizeof (struct GNUNET_PeerIdentity)))
1645 GNUNET_free (session);
1646 return GNUNET_SYSERR;
1648 // this protocol can at best be 1:N, but never M:N!
1649 // Check if the sender is not the peer, I am connected to, which would be bad!
1650 if (memcmp (sender, &session->peer, sizeof (struct GNUNET_PeerIdentity)))
1653 GNUNET_free (session);
1654 return GNUNET_SYSERR;
1657 //we need at least a peer and one message id to compare
1658 if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request))
1660 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from peer!\n"));
1661 GNUNET_free (session);
1662 return GNUNET_SYSERR;
1664 mask_length = ntohs (msg->mask_length);
1665 pk_length = ntohs (msg->pk_length);
1666 used_elements = ntohs (msg->used_element_count);
1667 element_count = ntohs (msg->element_count);
1668 msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1669 + mask_length + pk_length + used_elements * PAILLIER_ELEMENT_LENGTH;
1671 //sanity check: is the message as long as the message_count fields suggests?
1672 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements)
1673 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
1676 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from peer, message count does not match message length!\n"));
1677 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Used elements: %hu\nElement Count: %hu\nExpected Mask Length: %hu\nCalculated Masklength: %d\n"), used_elements, element_count, mask_length, (element_count / 8 + (element_count % 8 ? 1 : 0)));
1678 GNUNET_free (session);
1679 return GNUNET_SYSERR;
1681 if (find_matching_session (from_service_tail,
1687 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
1688 GNUNET_free (session);
1689 return GNUNET_SYSERR;
1692 memcpy (&session->peer, sender, sizeof (struct GNUNET_PeerIdentity));
1693 session->state = REQUEST_FROM_SERVICE_RECEIVED;
1694 session->element_count = ntohs (msg->element_count);
1695 session->used_element_count = used_elements;
1696 session->tunnel = tunnel;
1699 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1700 current = (unsigned char *) &msg[1];
1701 //preserve the mask, we will need that later on
1702 session->mask = GNUNET_malloc (mask_length);
1703 memcpy (session->mask, current, mask_length);
1705 current += mask_length;
1707 //convert the publickey to sexp
1708 if (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))
1710 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
1711 GNUNET_free (session->mask);
1712 GNUNET_free (session);
1713 return GNUNET_SYSERR;
1716 current += pk_length;
1718 //check if service queue contains a matching request
1719 needed_state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
1720 responder_session = find_matching_session (from_client_tail,
1722 session->element_count,
1723 &needed_state, NULL);
1725 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
1727 if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= sizeof (struct GNUNET_SCALARPRODUCT_service_request)
1730 + used_elements * PAILLIER_ELEMENT_LENGTH)
1732 gcry_error_t ret = 0;
1733 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
1734 // Convert each vector element to MPI_value
1735 for (i = 0; i < used_elements; i++)
1739 ret = gcry_mpi_scan (&session->a[i],
1741 ¤t[i * PAILLIER_ELEMENT_LENGTH],
1742 PAILLIER_ELEMENT_LENGTH,
1744 if (ret) // read < GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH
1746 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
1747 i, gcry_strsource (ret), gcry_strerror (ret));
1751 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
1752 if (responder_session)
1754 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1755 if (GNUNET_OK != compute_service_response (session, responder_session))
1757 //something went wrong, remove it again...
1758 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1763 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1768 // TODO FEATURE: fallback to fragmentation, in case the message is too long
1769 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1773 for (i = 0; i < used_elements; i++)
1775 gcry_mpi_release (session->a[i]);
1776 gcry_sexp_release (session->remote_pubkey);
1777 session->remote_pubkey = NULL;
1778 GNUNET_free_non_null (session->a);
1780 free_session (session);
1781 // and notify our client-session that we could not complete the session
1782 if (responder_session)
1784 // we just found the responder session in this queue
1785 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, responder_session);
1786 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1787 &prepare_client_end_notification,
1790 return GNUNET_SYSERR;
1795 * Handle a response we got from another service we wanted to calculate a scalarproduct with.
1797 * @param cls closure (set from #GNUNET_MESH_connect)
1798 * @param tunnel connection to the other end
1799 * @param tunnel_ctx place to store local state associated with the tunnel
1800 * @param sender who sent the message
1801 * @param message the actual message
1802 * @param atsi performance data for the connection
1803 * @return #GNUNET_OK to keep the connection open,
1804 * #GNUNET_SYSERR to close it (signal serious error)
1807 handle_service_response (void *cls,
1808 struct GNUNET_MESH_Tunnel * tunnel,
1810 const struct GNUNET_PeerIdentity * sender,
1811 const struct GNUNET_MessageHeader * message,
1812 const struct GNUNET_ATS_Information * atsi)
1815 struct ServiceSession * session;
1816 struct GNUNET_SCALARPRODUCT_service_response * msg = (struct GNUNET_SCALARPRODUCT_service_response *) message;
1817 unsigned char * current;
1819 gcry_mpi_t s = NULL;
1820 gcry_mpi_t stick = NULL;
1823 uint16_t used_element_count;
1825 gcry_mpi_t * kp = NULL;
1826 gcry_mpi_t * kq = NULL;
1829 GNUNET_assert (NULL != message);
1830 GNUNET_assert (NULL != sender);
1831 GNUNET_assert (NULL != tunnel_ctx);
1832 session = (struct ServiceSession *) * tunnel_ctx;
1833 GNUNET_assert (NULL != session);
1834 count = session->used_element_count;
1835 session->product = NULL;
1837 if (memcmp (&session->peer, sender, sizeof (struct GNUNET_PeerIdentity)))
1839 GNUNET_break_op (0);
1842 //we need at least a peer and one message id to compare
1843 if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) > ntohs (msg->header.size))
1845 GNUNET_break_op (0);
1848 used_element_count = ntohs (msg->used_element_count);
1849 msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
1850 + 2 * used_element_count * PAILLIER_ELEMENT_LENGTH
1851 + 2 * PAILLIER_ELEMENT_LENGTH;
1852 //sanity check: is the message as long as the message_count fields suggests?
1853 if ((ntohs (msg->header.size) != msg_size) || (count != used_element_count))
1855 GNUNET_break_op (0);
1860 current = (unsigned char *) &msg[1];
1861 if (0 != (rc = gcry_mpi_scan (&s, GCRYMPI_FMT_USG, current,
1862 PAILLIER_ELEMENT_LENGTH, &read)))
1864 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1865 GNUNET_break_op (0);
1868 current += PAILLIER_ELEMENT_LENGTH;
1870 if (0 != (rc = gcry_mpi_scan (&stick, GCRYMPI_FMT_USG, current,
1871 PAILLIER_ELEMENT_LENGTH, &read)))
1873 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1874 GNUNET_break_op (0);
1877 current += PAILLIER_ELEMENT_LENGTH;
1879 kp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1880 // Convert each kp[] to its MPI_value
1881 for (i = 0; i < count; i++)
1883 if (0 != (rc = gcry_mpi_scan (&kp[i], GCRYMPI_FMT_USG, current,
1884 PAILLIER_ELEMENT_LENGTH, &read)))
1886 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1887 GNUNET_break_op (0);
1890 current += PAILLIER_ELEMENT_LENGTH;
1894 kq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1895 // Convert each kq[] to its MPI_value
1896 for (i = 0; i < count; i++)
1898 if (0 != (rc = gcry_mpi_scan (&kq[i], GCRYMPI_FMT_USG, current,
1899 PAILLIER_ELEMENT_LENGTH, &read)))
1901 LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
1902 GNUNET_break_op (0);
1905 current += PAILLIER_ELEMENT_LENGTH;
1908 session->product = compute_scalar_product (session, kp, kq, s, stick);
1912 gcry_mpi_release (s);
1914 gcry_mpi_release (stick);
1915 for (i = 0; kp && i < count; i++)
1916 if (kp[i]) gcry_mpi_release (kp[i]);
1917 for (i = 0; kq && i < count; i++)
1918 if (kq[i]) gcry_mpi_release (kq[i]);
1919 GNUNET_free_non_null (kp);
1920 GNUNET_free_non_null (kq);
1922 session->state = FINALIZED;
1923 // the tunnel has done its job, terminate our connection and the tunnel
1924 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
1925 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1926 GNUNET_SCHEDULER_add_now (&destroy_tunnel, session); // FIXME: use after free!
1927 // send message with product to client
1928 /* session->current_task = */ GNUNET_SCHEDULER_add_now (&prepare_client_response, session); // FIXME: dangling task!
1930 // if success: terminate the session gracefully, else terminate with error
1935 * Task run during shutdown.
1941 shutdown_task (void *cls,
1942 const struct GNUNET_SCHEDULER_TaskContext *tc)
1944 struct ServiceSession * curr;
1945 struct ServiceSession * next;
1946 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
1948 do_shutdown = GNUNET_YES;
1949 // terminate all owned open tunnels.
1950 for (curr = from_client_head; NULL != curr; curr = next)
1953 if (FINALIZED != curr->state)
1955 destroy_tunnel (curr, NULL);
1956 curr->state = FINALIZED;
1961 GNUNET_MESH_disconnect (my_mesh);
1968 * Initialization of the program and message handlers
1970 * @param cls closure
1971 * @param server the initialized server
1972 * @param c configuration to use
1976 struct GNUNET_SERVER_Handle *server,
1977 const struct GNUNET_CONFIGURATION_Handle *c)
1979 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
1980 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE, 0},
1981 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_BOB, 0},
1984 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
1985 { &handle_service_request, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB, 0},
1986 { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
1989 static GNUNET_MESH_ApplicationType mesh_types[] = {
1990 GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
1991 GNUNET_APPLICATION_TYPE_END
1994 //generate private/public key set
1995 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating rsa-key.\n"));
1997 // register server callbacks and disconnect handler
1998 GNUNET_SERVER_add_handlers (server, server_handlers);
1999 GNUNET_SERVER_disconnect_notify (server,
2000 &handle_client_disconnect,
2002 GNUNET_break (GNUNET_OK ==
2003 GNUNET_CRYPTO_get_host_identity (c,
2005 my_mesh = GNUNET_MESH_connect (c, NULL,
2006 &tunnel_incoming_handler,
2007 &tunnel_destruction_handler,
2008 mesh_handlers, mesh_types);
2011 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2012 GNUNET_SCHEDULER_shutdown ();
2015 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2016 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2023 * The main function for the scalarproduct service.
2025 * @param argc number of arguments from the command line
2026 * @param argv command line arguments
2027 * @return 0 ok, 1 on error
2030 main (int argc, char *const *argv)
2032 return (GNUNET_OK ==
2033 GNUNET_SERVICE_run (argc, argv,
2035 GNUNET_SERVICE_OPTION_NONE,
2036 &run, NULL)) ? 0 : 1;
2039 /* end of gnunet-service-ext.c */