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 vectorproduct/gnunet-service-vectorproduct.c
23 * @brief vectorproduct 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_vectorproduct_service.h"
34 #include "gnunet_vectorproduct.h"
36 ///////////////////////////////////////////////////////////////////////////////
38 ///////////////////////////////////////////////////////////////////////////////
41 * Handle to the core service (NULL until we've connected to it).
43 static struct GNUNET_CORE_Handle *my_core;
46 * Handle to the core service (NULL until we've connected to it).
48 static struct GNUNET_MESH_Handle *my_mesh;
51 * The identity of this host.
53 static struct GNUNET_PeerIdentity me;
56 * Service's own public key represented as string
58 static unsigned char * my_pubkey_external;
61 * Service's own public key represented as string
63 static uint16_t my_pubkey_external_length = 0;
68 static gcry_mpi_t my_n;
71 * Service's own n^2 (kept for performance)
73 static gcry_mpi_t my_nsquare;
76 * Service's own public exponent
78 static gcry_mpi_t my_g;
81 * Service's own private multiplier
83 static gcry_mpi_t my_mu;
86 * Service's own private exponent
88 static gcry_mpi_t my_lambda;
91 * Head of our double linked list for client-requests sent to us.
92 * for all of these elements we calculate a vector product with a remote peer
93 * split between service->service and client->service for simplicity
95 static struct ServiceSession * from_client_head;
97 * Tail of our double linked list for client-requests sent to us.
98 * for all of these elements we calculate a vector product with a remote peer
99 * split between service->service and client->service for simplicity
101 static struct ServiceSession * from_client_tail;
104 * Head of our double linked list for service-requests sent to us.
105 * for all of these elements we help the requesting service in calculating a vector product
106 * split between service->service and client->service for simplicity
108 static struct ServiceSession * from_service_head;
111 * Tail of our double linked list for service-requests sent to us.
112 * for all of these elements we help the requesting service in calculating a vector product
113 * split between service->service and client->service for simplicity
115 static struct ServiceSession * from_service_tail;
118 * Certain events (callbacks for server & mesh operations) must not be queued after shutdown.
120 static int do_shutdown;
122 ///////////////////////////////////////////////////////////////////////////////
124 ///////////////////////////////////////////////////////////////////////////////
127 * Generates an Paillier private/public keyset and extracts the values using libgrcypt only
132 gcry_sexp_t gen_parms;
134 gcry_sexp_t tmp_sexp;
143 // we can still use the RSA keygen for generating p,q,n, but using e is pointless.
144 GNUNET_assert (0 == gcry_sexp_build (&gen_parms, &erroff,
145 "(genkey(rsa(nbits %d)(rsa-use-e 3:257)))",
148 GNUNET_assert (0 == gcry_pk_genkey (&key, gen_parms));
149 gcry_sexp_release (gen_parms);
151 // get n and d of our publickey as MPI
152 tmp_sexp = gcry_sexp_find_token (key, "n", 0);
153 GNUNET_assert (tmp_sexp);
154 my_n = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
155 gcry_sexp_release (tmp_sexp);
156 tmp_sexp = gcry_sexp_find_token (key, "p", 0);
157 GNUNET_assert (tmp_sexp);
158 p = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
159 gcry_sexp_release (tmp_sexp);
160 tmp_sexp = gcry_sexp_find_token (key, "q", 0);
161 GNUNET_assert (tmp_sexp);
162 q = gcry_sexp_nth_mpi (tmp_sexp, 1, GCRYMPI_FMT_USG);
163 gcry_sexp_release (key);
165 tmp1 = gcry_mpi_new (0);
166 tmp2 = gcry_mpi_new (0);
167 gcd = gcry_mpi_new (0);
168 my_g = gcry_mpi_new (0);
169 my_mu = gcry_mpi_new (0);
170 my_nsquare = gcry_mpi_new (0);
171 my_lambda = gcry_mpi_new (0);
174 // lambda = \frac{(p-1)*(q-1)}{gcd(p-1,q-1)}
175 gcry_mpi_sub_ui (tmp1, p, 1);
176 gcry_mpi_sub_ui (tmp2, q, 1);
177 gcry_mpi_gcd (gcd, tmp1, tmp2);
178 gcry_mpi_set (my_lambda, tmp1);
179 gcry_mpi_mul (my_lambda, my_lambda, tmp2);
180 gcry_mpi_div (my_lambda, NULL, my_lambda, gcd, 0);
183 gcry_mpi_mul (my_nsquare, my_n, my_n);
189 gcry_mpi_randomize (my_g, KEYBITS * 2, GCRY_WEAK_RANDOM);
190 // g must be smaller than n^2
191 if (0 >= gcry_mpi_cmp (my_g, my_nsquare))
194 // g must have gcd == 1 with n^2
195 gcry_mpi_gcd (gcd, my_g, my_nsquare);
197 while (gcry_mpi_cmp_ui (gcd, 1));
199 // is this a valid g?
200 // if so, gcd(((g^lambda mod n^2)-1 )/n, n) = 1
201 gcry_mpi_powm (tmp1, my_g, my_lambda, my_nsquare);
202 gcry_mpi_sub_ui (tmp1, tmp1, 1);
203 gcry_mpi_div (tmp1, NULL, tmp1, my_n, 0);
204 gcry_mpi_gcd (gcd, tmp1, my_n);
206 while (gcry_mpi_cmp_ui (gcd, 1));
208 // calculate our mu based on g and n.
209 // mu = (((g^lambda mod n^2)-1 )/n)^-1 mod n
210 gcry_mpi_invm (my_mu, tmp1, my_n);
212 GNUNET_assert (0 == gcry_sexp_build (&key, &erroff,
213 "(public-key (paillier (n %M)(g %M)))",
216 // get the length of this sexpression
217 my_pubkey_external_length = gcry_sexp_sprint (key,
222 GNUNET_assert (my_pubkey_external_length > 0);
223 my_pubkey_external = GNUNET_malloc (my_pubkey_external_length);
225 // convert the sexpression to canonical format
226 gcry_sexp_sprint (key,
229 my_pubkey_external_length);
231 gcry_sexp_release (key);
233 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
238 * If target != size, move target bytes to the
239 * end of the size-sized buffer and zero out the
240 * first target-size bytes.
242 * @param buf original buffer
243 * @param size number of bytes in the buffer
244 * @param target target size of the buffer
247 adjust (unsigned char *buf, size_t size, size_t target)
251 memmove (&buf[target - size], buf, size);
252 memset (buf, 0, target - size);
258 * encrypts an element using the paillier crypto system
260 * @param c ciphertext (output)
262 * @param g the public base
263 * @param r random base (optional) gets generated and if not NULL but uninitialized
264 * @param n the module from which which r is chosen (Z*_n)
265 * @param n_square the module for encryption, for performance reasons.
268 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)
270 #ifndef DISABLE_CRYPTO
272 int release_r = GNUNET_NO;
274 GNUNET_assert (tmp = gcry_mpi_new (0));
277 GNUNET_assert (r = gcry_mpi_new (0));
278 release_r = GNUNET_YES;
280 while (0 <= gcry_mpi_cmp (r, n) || 0 >= gcry_mpi_cmp_ui (r, 1))
282 gcry_mpi_randomize (r, KEYBITS, GCRY_WEAK_RANDOM);
283 // r must be 1 < r < n
288 gcry_mpi_powm (c, g, m, n_square);
289 gcry_mpi_powm (tmp, r, n, n_square);
290 gcry_mpi_mulm (c, tmp, c, n_square);
292 gcry_mpi_release (tmp);
293 if (GNUNET_YES == release_r)
294 gcry_mpi_release (r);
302 * decrypts an element using the paillier crypto system
304 * @param m plaintext (output)
305 * @param c the ciphertext
306 * @param mu the modifier to correct encryption
307 * @param lambda the private exponent
308 * @param n the outer module for decryption
309 * @param n_square the inner module for decryption
312 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)
314 #ifndef DISABLE_CRYPTO
315 gcry_mpi_powm (m, c, lambda, n_square);
316 gcry_mpi_sub_ui (m, m, 1);
317 gcry_mpi_div (m, NULL, m, n, 0);
318 gcry_mpi_mulm (m, m, mu, n);
326 * computes the square sum over a vector of a given length.
328 * @param vector the vector to encrypt
329 * @param length the length of the vector
330 * @return an MPI value containing the calculated sum, never NULL
333 compute_square_sum (gcry_mpi_t * vector, uint16_t length)
339 GNUNET_assert (sum = gcry_mpi_new (0));
340 GNUNET_assert (elem = gcry_mpi_new (0));
342 // calculare E(sum (ai ^ 2), publickey)
343 for (i = 0; i < length; i++)
345 gcry_mpi_mul (elem, vector[i], vector[i]);
346 gcry_mpi_add (sum, sum, elem);
348 gcry_mpi_release (elem);
355 * Primitive callback for copying over a message, as they
356 * usually are too complex to be handled in the callback itself.
357 * clears a session-callback, if a session was handed over and the transmit handle was stored
359 * @param cls the message object
360 * @param size the size of the buffer we got
361 * @param buf the buffer to copy the message to
362 * @return 0 if we couldn't copy, else the size copied over
365 do_send_message (void *cls, size_t size, void *buf)
367 struct MessageObject * info = cls;
368 struct GNUNET_MessageHeader * msg;
371 GNUNET_assert (info);
376 if (ntohs (msg->size) == size)
378 memcpy (buf, msg, size);
382 // reset the transmit handle, if necessary
383 if (info->transmit_handle)
384 *info->transmit_handle = NULL;
386 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Sent a message of type %hu.\n"), ntohs (msg->type));
394 * initializes a new vector with fresh MPI values (=0) of a given length
396 * @param length of the vector to create
397 * @return the initialized vector, never NULL
400 initialize_mpi_vector (uint16_t length)
403 gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
405 for (i = 0; i < length; i++)
406 GNUNET_assert (NULL != (output[i] = gcry_mpi_new (0)));
412 * permutes an MPI vector according to the given permutation vector
414 * @param vector the vector to permuted
415 * @param perm the permutation to use
416 * @param length the length of the vectors
417 * @return the permuted vector (same as input), never NULL
420 permute_vector (gcry_mpi_t * vector,
424 gcry_mpi_t tmp[length];
427 GNUNET_assert (length > 0);
430 memcpy (tmp, vector, length * sizeof (gcry_mpi_t));
432 // permute vector according to given
433 for (i = 0; i < length; i++)
434 vector[i] = tmp[perm[i]];
441 * Populate a vector with random integer values and convert them to
443 * @param length the length of the vector we must generate
444 * @return an array of MPI values with random values
447 generate_random_vector (uint16_t length)
449 gcry_mpi_t * random_vector;
453 random_vector = initialize_mpi_vector (length);
454 for (i = 0; i < length; i++)
456 value = (int32_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX);
458 // long to gcry_mpi_t
460 gcry_mpi_sub_ui (random_vector[i],
464 random_vector[i] = gcry_mpi_set_ui (random_vector[i], value);
467 return random_vector;
472 * Finds a not terminated client/service session in the
473 * given DLL based on session key, element count and state.
475 * @param tail - the tail of the DLL
476 * @param my - the session to compare it to
477 * @return a pointer to a matching session,
480 static struct ServiceSession *
481 find_matching_session (struct ServiceSession * tail,
482 struct GNUNET_HashCode * key,
483 uint16_t element_count,
484 enum SessionState * state,
485 const struct GNUNET_PeerIdentity * peerid)
487 struct ServiceSession * curr;
489 for (curr = tail; NULL != curr; curr = curr->prev)
491 // if the key matches, and the element_count is same
492 if ((!memcmp (&curr->key, key, sizeof (struct GNUNET_HashCode)))
493 && (curr->element_count == element_count))
495 // if incoming state is NULL OR is same as state of the queued request
496 if ((NULL == state) || (curr->state == *state))
498 // if peerid is NULL OR same as the peer Id in the queued request
500 || (!memcmp (&curr->peer, peerid, sizeof (struct GNUNET_PeerIdentity))))
501 // matches and is not an already terminated session
512 destroy_tunnel (void *cls,
513 const struct GNUNET_SCHEDULER_TaskContext *tc)
515 struct ServiceSession * session = cls;
519 GNUNET_MESH_tunnel_destroy (session->tunnel);
520 session->tunnel = NULL;
522 session->service_transmit_handle = NULL;
523 // we need to set this to NULL so there is no problem with double-cancel later on.
528 free_session (struct ServiceSession * session)
532 if (FINALIZED != session->state)
536 for (i = 0; i < session->used_element_count; i++)
537 gcry_mpi_release (session->a[i]);
539 GNUNET_free (session->a);
541 if (session->product)
542 gcry_mpi_release (session->product);
544 if (session->remote_pubkey)
545 gcry_sexp_release (session->remote_pubkey);
547 GNUNET_free_non_null (session->vector);
550 GNUNET_free (session);
552 ///////////////////////////////////////////////////////////////////////////////
553 // Event and Message Handlers
554 ///////////////////////////////////////////////////////////////////////////////
558 * A client disconnected.
560 * Remove the associated session(s), release datastructures
561 * and cancel pending outgoing transmissions to the client.
562 * if the session has not yet completed, we also cancel Alice's request to Bob.
564 * @param cls closure, NULL
565 * @param client identification of the client
568 handle_client_disconnect (void *cls,
569 struct GNUNET_SERVER_Client
572 struct ServiceSession * elem;
573 struct ServiceSession * next;
575 // start from the tail, old stuff will be there...
576 for (elem = from_client_head; NULL != elem; elem = next)
579 if (elem->client != client)
582 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Client (%p) disconnected from us.\n"), client);
583 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, elem);
585 if (!(elem->role == BOB && elem->state == FINALIZED))
587 //we MUST terminate any client message underway
588 if (elem->service_transmit_handle && elem->tunnel)
589 GNUNET_MESH_notify_transmit_ready_cancel (elem->service_transmit_handle);
590 if (elem->tunnel && elem->state == WAITING_FOR_RESPONSE_FROM_SERVICE)
591 destroy_tunnel (elem, NULL);
599 * Notify the client that the session has succeeded or failed completely.
600 * This message gets sent to
601 * * alice's client if bob disconnected or to
602 * * bob's client if the operation completed or alice disconnected
604 * @param client_session the associated client session
605 * @return GNUNET_NO, if we could not notify the client
606 * GNUNET_YES if we notified it.
609 prepare_client_end_notification (void * cls,
610 const struct GNUNET_SCHEDULER_TaskContext * tc)
612 struct ServiceSession * session = cls;
613 struct GNUNET_VECTORPRODUCT_client_response * msg;
614 struct MessageObject * msg_obj;
616 GNUNET_assert (NULL != session);
618 msg = GNUNET_new (struct GNUNET_VECTORPRODUCT_client_response);
619 msg->header.type = htons (GNUNET_MESSAGE_TYPE_VECTORPRODUCT_SERVICE_TO_CLIENT);
620 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
621 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
622 msg->header.size = htons (sizeof (struct GNUNET_VECTORPRODUCT_client_response));
623 // 0 size and the first char in the product is 0, which should never be zero if encoding is used.
624 msg->product_length = htonl (0);
626 msg_obj = GNUNET_malloc (sizeof (struct MessageObject));
627 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
628 msg_obj->transmit_handle = NULL; // do not reset the transmit handle, please
630 //transmit this message to our client
631 session->client_transmit_handle =
632 GNUNET_SERVER_notify_transmit_ready (session->client,
633 sizeof (struct GNUNET_VECTORPRODUCT_client_response),
634 GNUNET_TIME_UNIT_FOREVER_REL,
639 // if we could not even queue our request, something is wrong
640 if ( ! session->client_transmit_handle)
643 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);
644 // usually gets freed by do_send_message
645 GNUNET_free (msg_obj);
649 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
651 free_session(session);
657 * generates the response message to be sent to alice after computing
658 * the values (1), (2), S and S'
659 * (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)})$
660 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
661 * S: $S := E_A(sum (r_i + b_i)^2)$
662 * S': $S' := E_A(sum r_i^2)$
664 * @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)})$
665 * @param kq (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
666 * @param s S: $S := E_A(sum (r_i + b_i)^2)$
667 * @param stick S': $S' := E_A(sum r_i^2)$
668 * @param request the associated requesting session with alice
669 * @param response the associated responder session with bob's client
670 * @return GNUNET_SYSERR if the function was called with NULL parameters or if there was an error
671 * GNUNET_NO if we could not send our message
672 * GNUNET_OK if the operation succeeded
675 prepare_service_response (gcry_mpi_t * kp,
679 struct ServiceSession * request,
680 struct ServiceSession * response)
682 struct GNUNET_VECTORPRODUCT_service_response * msg;
683 uint16_t msg_length = 0;
684 unsigned char * current = NULL;
685 unsigned char * element_exported = NULL;
686 size_t element_length = 0;
689 GNUNET_assert (request);
691 msg_length = sizeof (struct GNUNET_VECTORPRODUCT_service_response)
692 + 2 * request->used_element_count * PAILLIER_ELEMENT_LENGTH // kp, kq
693 + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
695 msg = GNUNET_malloc (msg_length);
698 msg->header.type = htons (GNUNET_MESSAGE_TYPE_VECTORPRODUCT_BOB_TO_ALICE);
699 msg->header.size = htons (msg_length);
700 msg->element_count = htons (request->element_count);
701 msg->used_element_count = htons (request->used_element_count);
702 memcpy (&msg->key, &request->key, sizeof (struct GNUNET_HashCode));
703 current = (unsigned char *) &msg[1];
705 // 4 times the same logics with slight variations.
706 // doesn't really justify having 2 functions for that
707 // so i put it into blocks to enhance readability
710 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
711 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
712 element_exported, PAILLIER_ELEMENT_LENGTH,
715 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
716 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
717 GNUNET_free (element_exported);
718 current += PAILLIER_ELEMENT_LENGTH;
723 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
724 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
725 element_exported, PAILLIER_ELEMENT_LENGTH,
728 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
729 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
730 GNUNET_free (element_exported);
731 current += PAILLIER_ELEMENT_LENGTH;
735 for (i = 0; i < request->used_element_count; i++)
737 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
738 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
739 element_exported, PAILLIER_ELEMENT_LENGTH,
742 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
743 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
744 GNUNET_free (element_exported);
745 current += PAILLIER_ELEMENT_LENGTH;
750 for (i = 0; i < request->used_element_count; i++)
752 element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
753 GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
754 element_exported, PAILLIER_ELEMENT_LENGTH,
757 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
758 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
759 GNUNET_free (element_exported);
760 current += PAILLIER_ELEMENT_LENGTH;
763 if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= msg_length)
765 struct MessageObject * msg_obj;
767 msg_obj = GNUNET_new (struct MessageObject);
768 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
769 msg_obj->transmit_handle = (void *) &request->service_transmit_handle; //and reset the transmit handle
770 request->service_transmit_handle =
771 GNUNET_MESH_notify_transmit_ready (request->tunnel,
773 GNUNET_TIME_UNIT_FOREVER_REL,
774 &request->peer, //must be specified, we are a slave/participant/non-owner
778 // we don't care if it could be send or not. either way, the session is over for us.
779 request->state = FINALIZED;
780 response->state = FINALIZED;
784 // TODO FEATURE: fallback to fragmentation, in case the message is too long
785 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!)\n"));
788 //disconnect our client
789 if ( ! request->service_transmit_handle)
791 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
792 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, response);
793 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
794 &prepare_client_end_notification,
805 * (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)})$
806 * (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
807 * S: $S := E_A(sum (r_i + b_i)^2)$
808 * S': $S' := E_A(sum r_i^2)$
810 * @param request the requesting session + bob's requesting peer
811 * @param response the responding session + bob's client handle
812 * @return GNUNET_SYSERR if the computation failed
813 * GNUNET_OK if everything went well.
816 compute_service_response (struct ServiceSession * request,
817 struct ServiceSession * response)
819 int i, j, ret = GNUNET_SYSERR;
823 gcry_mpi_t * r = NULL;
824 gcry_mpi_t * kp = NULL;
825 gcry_mpi_t * kq = NULL;
834 gcry_mpi_t stick = NULL;
835 gcry_mpi_t remote_n = NULL;
836 gcry_mpi_t remote_nsquare;
837 gcry_mpi_t remote_g = NULL;
841 GNUNET_assert (request != NULL && response != NULL);
842 count = request->used_element_count;
844 b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
845 ap = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
846 bp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
847 aq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
848 bq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
849 rp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
850 rq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
852 // convert responder session to from long to mpi
853 for (i = 0, j = 0; i < response->element_count && j < count; i++)
855 if (request->mask[i / 8] & (1 << (i % 8)))
857 value = response->vector[i] >= 0 ? response->vector[i] : -response->vector[i];
858 // long to gcry_mpi_t
859 if (0 > response->vector[i])
861 b[j] = gcry_mpi_new (0);
862 gcry_mpi_sub_ui (b[j], b[j], value);
866 b[j] = gcry_mpi_set_ui (NULL, value);
871 GNUNET_free (response->vector);
872 response->vector = NULL;
874 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "n", 0);
878 gcry_sexp_release (request->remote_pubkey);
879 request->remote_pubkey = NULL;
882 remote_n = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
886 gcry_sexp_release (tmp_exp);
889 remote_nsquare = gcry_mpi_new (KEYBITS + 1);
890 gcry_mpi_mul (remote_nsquare, remote_n, remote_n);
891 gcry_sexp_release (tmp_exp);
892 tmp_exp = gcry_sexp_find_token (request->remote_pubkey, "g", 0);
893 gcry_sexp_release (request->remote_pubkey);
894 request->remote_pubkey = NULL;
898 gcry_mpi_release (remote_n);
901 remote_g = gcry_sexp_nth_mpi (tmp_exp, 1, GCRYMPI_FMT_USG);
905 gcry_mpi_release (remote_n);
906 gcry_sexp_release (tmp_exp);
909 gcry_sexp_release (tmp_exp);
911 // generate r, p and q
912 r = generate_random_vector (count);
913 p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
914 q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
915 //initialize the result vectors
916 kp = initialize_mpi_vector (count);
917 kq = initialize_mpi_vector (count);
919 // copy the REFERNCES of a, b and r into aq and bq. we will not change
920 // those values, thus we can work with the references
921 memcpy (ap, request->a, sizeof (gcry_mpi_t) * count);
922 memcpy (aq, request->a, sizeof (gcry_mpi_t) * count);
923 memcpy (bp, b, sizeof (gcry_mpi_t) * count);
924 memcpy (bq, b, sizeof (gcry_mpi_t) * count);
925 memcpy (rp, r, sizeof (gcry_mpi_t) * count);
926 memcpy (rq, r, sizeof (gcry_mpi_t) * count);
928 // generate p and q permutations for a, b and r
929 GNUNET_assert (permute_vector (ap, p, count));
930 GNUNET_assert (permute_vector (bp, p, count));
931 GNUNET_assert (permute_vector (rp, p, count));
932 GNUNET_assert (permute_vector (aq, q, count));
933 GNUNET_assert (permute_vector (bq, q, count));
934 GNUNET_assert (permute_vector (rq, q, count));
936 // encrypt the element
937 // for the sake of readability I decided to have dedicated permutation
938 // vectors, which get rid of all the lookups in p/q.
939 // however, ap/aq are not absolutely necessary but are just abstraction
940 // Calculate Kp = E(a_pi) + E(-r_pi - b_pi)
941 for (i = 0; i < count; i++)
944 gcry_mpi_sub (kp[i], kp[i], rp[i]);
945 gcry_mpi_sub (kp[i], kp[i], bp[i]);
946 encrypt_element (kp[i], kp[i], NULL, remote_g, remote_n, remote_nsquare);
948 // E(-r_pi - b_pi) * E(a_pi) == E(a + (-r -b))
949 //gcry_mpi_mulm (kp[i], kp[i], ap[i], remote_nsquare);
950 gcry_mpi_add (kp[i], kp[i], ap[i]);
956 // Calculate Kq = E(a_qi) + E( -r_qi)
957 for (i = 0; i < count; i++)
960 gcry_mpi_sub (kq[i], kq[i], rq[i]);
961 encrypt_element (kq[i], kq[i], NULL, remote_g, remote_n, remote_nsquare);
963 // E(-r_qi) * E(a_qi) == E(aqi + (- rqi))
964 //gcry_mpi_mulm (kq[i], kq[i], aq[i], remote_nsquare);
965 gcry_mpi_add (kq[i], kq[i], aq[i]);
971 // Calculate S' = E(SUM( r_i^2 ))
972 stick = compute_square_sum (r, count);
973 encrypt_element (stick, stick, NULL, remote_g, remote_n, remote_nsquare);
975 // Calculate S = E(SUM( (r_i + b_i)^2 ))
976 for (i = 0; i < count; i++)
978 gcry_mpi_add (r[i], r[i], b[i]);
980 s = compute_square_sum (r, count);
981 encrypt_element (s, s, NULL, remote_g, remote_n, remote_nsquare);
982 gcry_mpi_release (remote_n);
983 gcry_mpi_release (remote_g);
984 gcry_mpi_release (remote_nsquare);
987 for (i = 0; i < count; i++)
988 // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
989 gcry_mpi_release (r[i]);
991 // copy the Kp[], Kq[], S and Stick into a new message
992 if (GNUNET_YES != prepare_service_response (kp, kq, s, stick, request, response))
993 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Computation of values for alice failed!\n"));
997 for (i = 0; i < count; i++)
999 gcry_mpi_release (kq[i]);
1000 gcry_mpi_release (kp[i]);
1003 gcry_mpi_release (s);
1004 gcry_mpi_release (stick);
1007 for (i = 0; i < count; i++)
1009 gcry_mpi_release (b[i]);
1010 gcry_mpi_release (request->a[i]);
1014 GNUNET_free (request->a);
1022 * Executed by Alice, fills in a service-request message and sends it to the given peer
1024 * @param session the session associated with this request, then also holds the CORE-handle
1025 * @return GNUNET_SYSERR if we could not send the message
1026 * GNUNET_NO if the message was too large
1027 * GNUNET_OK if we sent it
1030 prepare_service_request (void *cls,
1031 const struct GNUNET_PeerIdentity * peer,
1032 const struct GNUNET_ATS_Information * atsi)
1034 struct ServiceSession * session = cls;
1035 unsigned char * current;
1036 struct GNUNET_VECTORPRODUCT_service_request * msg;
1037 struct MessageObject * msg_obj;
1040 uint16_t msg_length;
1041 size_t element_length = 0; //gets initialized by gcry_mpi_print, but the compiler doesn't know that
1046 GNUNET_assert (NULL != cls);
1047 GNUNET_assert (NULL != peer);
1048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (peer));
1050 msg_length = sizeof (struct GNUNET_VECTORPRODUCT_service_request)
1051 + session->used_element_count * PAILLIER_ELEMENT_LENGTH
1052 + session->mask_length
1053 + my_pubkey_external_length;
1055 if (GNUNET_SERVER_MAX_MESSAGE_SIZE < sizeof (struct GNUNET_VECTORPRODUCT_service_request)
1056 + session->used_element_count * PAILLIER_ELEMENT_LENGTH
1057 + session->mask_length
1058 + my_pubkey_external_length)
1060 // TODO FEATURE: fallback to fragmentation, in case the message is too long
1061 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1062 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1063 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1064 &prepare_client_end_notification,
1068 msg = GNUNET_malloc (msg_length);
1070 msg->header.type = htons (GNUNET_MESSAGE_TYPE_VECTORPRODUCT_ALICE_TO_BOB);
1071 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1072 msg->mask_length = htons (session->mask_length);
1073 msg->pk_length = htons (my_pubkey_external_length);
1074 msg->used_element_count = htons (session->used_element_count);
1075 msg->element_count = htons (session->element_count);
1076 msg->header.size = htons (msg_length);
1078 // fill in the payload
1079 current = (unsigned char *) &msg[1];
1080 // copy over the mask
1081 memcpy (current, session->mask, session->mask_length);
1082 // copy over our public key
1083 current += session->mask_length;
1084 memcpy (current, my_pubkey_external, my_pubkey_external_length);
1085 current += my_pubkey_external_length;
1087 // now copy over the element vector
1088 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
1089 a = gcry_mpi_new (KEYBITS * 2);
1090 r = gcry_mpi_new (KEYBITS * 2);
1091 // encrypt our vector and generate string representations
1092 for (i = 0, j = 0; i < session->element_count; i++)
1094 // if this is a used element...
1095 if (session->mask[i / 8] & 1 << (i % 8))
1097 unsigned char * element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
1098 value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
1100 // long to gcry_mpi_t
1101 if (session->vector[i] < 0)
1103 a = gcry_mpi_set_ui (NULL, 0);
1104 gcry_mpi_sub_ui (a, a, value);
1107 a = gcry_mpi_set_ui (NULL, value);
1109 // multiply with a given factor to avoid disclosing 1
1110 session->a[j++] = gcry_mpi_set (NULL, a);
1111 encrypt_element (a, a, r, my_g, my_n, my_nsquare);
1113 // get representation as string
1114 // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
1115 GNUNET_assert ( ! gcry_mpi_print (GCRYMPI_FMT_USG,
1116 element_exported, PAILLIER_ELEMENT_LENGTH,
1120 // move buffer content to the end of the buffer so it can easily be read by libgcrypt. also this now has fixed size
1121 adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
1123 // copy over to the message
1124 memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
1125 current += PAILLIER_ELEMENT_LENGTH;
1128 gcry_mpi_release (a);
1129 gcry_mpi_release (r);
1131 msg_obj = GNUNET_malloc (sizeof (struct MessageObject));
1132 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
1133 msg_obj->transmit_handle = (void *) &session->service_transmit_handle; //and reset the transmit handle
1134 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transmitting service request.\n"));
1136 //transmit via mesh messaging
1137 session->state = WAITING_FOR_RESPONSE_FROM_SERVICE;
1138 session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
1139 GNUNET_TIME_UNIT_FOREVER_REL,
1140 peer, //multicast to all targets, maybe useful in the future
1144 if ( ! session->service_transmit_handle)
1146 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not send mutlicast message to tunnel!\n"));
1147 GNUNET_free (msg_obj);
1149 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1150 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1151 &prepare_client_end_notification,
1159 * Method called whenever a peer has disconnected from the tunnel.
1160 * Implementations of this callback must NOT call
1161 * GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
1162 * to run in some other task later. However, calling
1163 * "GNUNET_MESH_notify_transmit_ready_cancel" is allowed.
1165 * @param cls closure
1166 * @param peer peer identity the tunnel stopped working with
1169 tunnel_peer_disconnect_handler (void *cls, const struct GNUNET_PeerIdentity * peer)
1171 // as we have only one peer connected in each session, just remove the session and say good bye
1172 struct ServiceSession * session = cls;
1173 struct ServiceSession * curr;
1175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Peer (%s) disconnected from our tunnel!\n"), GNUNET_i2s (peer));
1177 if ((session->role == ALICE) && (FINALIZED != session->state) && ( ! do_shutdown))
1179 for (curr = from_client_head; NULL != curr; curr = curr->next)
1180 if (curr == session)
1182 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1185 GNUNET_SCHEDULER_add_now (&destroy_tunnel,
1187 // if this happened before we received the answer, we must terminate the session
1188 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1189 &prepare_client_end_notification,
1196 * Handler for a client request message.
1197 * Can either be type A or B
1198 * A: request-initiation to compute a scalar product with a peer
1199 * B: response role, keep the values + session and wait for a matching session or process a waiting request
1201 * @param cls closure
1202 * @param client identification of the client
1203 * @param message the actual message
1206 handle_client_request (void *cls,
1207 struct GNUNET_SERVER_Client *client,
1208 const struct GNUNET_MessageHeader *message)
1210 struct GNUNET_VECTORPRODUCT_client_request * msg = (struct GNUNET_VECTORPRODUCT_client_request *) message;
1211 struct ServiceSession * session;
1212 uint16_t element_count;
1213 uint16_t mask_length;
1218 GNUNET_assert (message);
1220 //we need at least a peer and one message id to compare
1221 if (sizeof (struct GNUNET_VECTORPRODUCT_client_request) > ntohs (msg->header.size))
1223 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from client!\n"));
1224 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1228 msg_type = ntohs (msg->header.type);
1229 element_count = ntohs (msg->element_count);
1230 mask_length = ntohs (msg->mask_length);
1232 //sanity check: is the message as long as the message_count fields suggests?
1233 if (( ntohs (msg->header.size) != (sizeof (struct GNUNET_VECTORPRODUCT_client_request) + element_count * sizeof (int32_t) + mask_length))
1234 || (0 == element_count))
1236 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from client, session information incorrect!\n"));
1237 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1241 // do we have a duplicate session here already?
1242 if (NULL != find_matching_session (from_client_tail,
1247 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Duplicate session information received, cannot create new session with key `%s'\n"), GNUNET_h2s (&msg->key));
1248 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1252 session = GNUNET_malloc (sizeof (struct ServiceSession));
1253 session->client = client;
1254 session->element_count = element_count;
1255 session->mask_length = mask_length;
1256 // get our transaction key
1257 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1258 //allocate memory for vector and encrypted vector
1259 session->vector = GNUNET_malloc (sizeof (int32_t) * element_count);
1260 vector = (int32_t *) & msg[1];
1262 if (GNUNET_MESSAGE_TYPE_VECTORPRODUCT_CLIENT_TO_ALICE == msg_type)
1264 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"), GNUNET_h2s (&session->key));
1266 session->role = ALICE;
1268 session->mask = GNUNET_malloc (mask_length);
1269 memcpy (session->mask, &vector[element_count], mask_length);
1271 // copy over the elements
1272 session->used_element_count = 0;
1273 for (i = 0; i < element_count; i++)
1275 session->vector[i] = ntohl (vector[i]);
1276 if (session->vector[i] == 0)
1277 session->mask[i / 8] &= ~(1 << (i % 8));
1278 if (session->mask[i / 8] & (1 << (i % 8)))
1279 session->used_element_count++;
1282 if ( ! session->used_element_count)
1284 GNUNET_break_op (0);
1285 GNUNET_free (session->vector);
1286 GNUNET_free (session->a);
1287 GNUNET_free (session);
1288 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1291 //session with ourself makes no sense!
1292 if ( ! memcmp (&msg->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1295 GNUNET_free (session->vector);
1296 GNUNET_free (session->a);
1297 GNUNET_free (session);
1298 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1302 memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
1303 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Creating new tunnel to for session with key %s.\n"), GNUNET_h2s (&session->key));
1304 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1305 session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
1306 prepare_service_request,
1307 tunnel_peer_disconnect_handler,
1309 if ( ! session->tunnel)
1312 GNUNET_free (session->vector);
1313 GNUNET_free (session->a);
1314 GNUNET_free (session);
1315 GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
1318 GNUNET_MESH_peer_request_connect_add (session->tunnel, &session->peer);
1319 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1320 session->state = WAITING_FOR_BOBS_CONNECT;
1324 struct ServiceSession * requesting_session;
1325 enum SessionState needed_state = REQUEST_FROM_SERVICE_RECEIVED;
1327 session->role = BOB;
1328 session->mask = NULL;
1329 // copy over the elements
1330 session->used_element_count = element_count;
1331 for (i = 0; i < element_count; i++)
1332 session->vector[i] = ntohl (vector[i]);
1333 session->state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
1335 GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
1336 GNUNET_SERVER_receive_done (client, GNUNET_YES);
1337 //check if service queue contains a matching request
1338 requesting_session = find_matching_session (from_service_tail,
1340 session->element_count,
1341 &needed_state, NULL);
1342 if (NULL != requesting_session)
1344 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));
1345 if (GNUNET_OK != compute_service_response (requesting_session, session))
1347 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1348 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1349 &prepare_client_end_notification,
1354 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));
1355 // no matching session exists yet, store the response
1356 // for later processing by handle_service_request()
1362 * Function called for inbound tunnels.
1364 * @param cls closure
1365 * @param tunnel new handle to the tunnel
1366 * @param initiator peer that started the tunnel
1367 * @param atsi performance information for the tunnel
1368 * @return initial tunnel context for the tunnel
1369 * (can be NULL -- that's not an error)
1372 tunnel_incoming_handler (void *cls, struct GNUNET_MESH_Tunnel *tunnel,
1373 const struct GNUNET_PeerIdentity *initiator,
1374 const struct GNUNET_ATS_Information *atsi)
1377 struct ServiceSession * c = GNUNET_new (struct ServiceSession);
1379 memcpy (&c->peer, initiator, sizeof (struct GNUNET_PeerIdentity));
1387 * Function called whenever an inbound tunnel is destroyed. Should clean up
1388 * any associated state.
1390 * @param cls closure (set from GNUNET_MESH_connect)
1391 * @param tunnel connection to the other end (henceforth invalid)
1392 * @param tunnel_ctx place where local state associated
1393 * with the tunnel is stored (our 'struct TunnelState')
1396 tunnel_destruction_handler (void *cls,
1397 const struct GNUNET_MESH_Tunnel *tunnel,
1400 struct ServiceSession * service_session = tunnel_ctx;
1401 struct ServiceSession * client_session;
1402 struct ServiceSession * curr;
1404 GNUNET_assert (service_session);
1405 if (!memcmp (&service_session->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
1407 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Tunnel destroyed, terminating session with peer (%s)\n"), GNUNET_i2s (&service_session->peer));
1408 // remove the session, unless it has already been dequeued, but somehow still active
1409 // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
1410 for (curr = from_service_head; NULL != curr; curr = curr->next)
1411 if (curr == service_session)
1413 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
1416 // there is a client waiting for this service session, terminate it, too!
1417 // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
1418 client_session = find_matching_session (from_client_tail,
1419 &service_session->key,
1420 service_session->element_count,
1422 free_session (service_session);
1424 // the client has to check if it was waiting for a result
1425 // or if it was a responder, no point in adding more statefulness
1426 if (client_session && ( ! do_shutdown))
1428 // remove the session, we just found it in the queue, so it must be there
1429 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, client_session);
1430 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1431 &prepare_client_end_notification,
1438 * Compute our scalar product, done by Alice
1440 * @param session - the session associated with this computation
1441 * @param kp - (1) from the protocol definition:
1442 * $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)})$
1443 * @param kq - (2) from the protocol definition:
1444 * $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
1445 * @param s - S from the protocol definition:
1446 * $S := E_A(sum (r_i + b_i)^2)$
1447 * @param stick - S' from the protocol definition:
1448 * $S' := E_A(sum r_i^2)$
1449 * @return product as MPI, never NULL
1452 compute_scalar_product (struct ServiceSession * session,
1453 gcry_mpi_t * kp, gcry_mpi_t * kq, gcry_mpi_t s, gcry_mpi_t stick)
1466 count = session->used_element_count;
1467 tmp = gcry_mpi_new (KEYBITS);
1468 for (i = 0; i < count; i++)
1470 decrypt_element (kp[i], kp[i], my_mu, my_lambda, my_n, my_nsquare);
1471 decrypt_element (kq[i], kq[i], my_mu, my_lambda, my_n, my_nsquare);
1474 // calculate t = E(sum(ai))
1475 t = compute_square_sum (session->a, count);
1476 encrypt_element (t, t, NULL, my_g, my_n, my_nsquare);
1479 u = gcry_mpi_new (0);
1480 tmp = compute_square_sum (kp, count);
1481 gcry_mpi_sub (u, u, tmp);
1482 encrypt_element (u, u, NULL, my_g, my_n, my_nsquare);
1483 gcry_mpi_release (tmp);
1486 utick = gcry_mpi_new (0);
1487 tmp = compute_square_sum (kq, count);
1488 gcry_mpi_sub (utick, utick, tmp);
1489 encrypt_element (utick, utick, NULL, my_g, my_n, my_nsquare);
1490 gcry_mpi_release (tmp);
1492 GNUNET_assert (p = gcry_mpi_new (0));
1493 GNUNET_assert (ptick = gcry_mpi_new (0));
1496 gcry_mpi_add (p, s, t);
1497 //gcry_mpi_mulm (p, p, u, my_nsquare);
1498 gcry_mpi_add (p, p, u);
1499 decrypt_element (p, p, my_mu, my_lambda, my_n, my_nsquare);
1502 gcry_mpi_add (ptick, stick, t);
1503 //gcry_mpi_mulm (ptick, ptick, utick, my_nsquare);
1504 gcry_mpi_add (ptick, ptick, utick);
1505 decrypt_element (ptick, ptick, my_mu, my_lambda, my_n, my_nsquare);
1507 gcry_mpi_release (t);
1508 gcry_mpi_release (u);
1509 gcry_mpi_release (utick);
1512 GNUNET_assert (product = gcry_mpi_new (0));
1513 gcry_mpi_sub (product, p, ptick);
1514 gcry_mpi_release (p);
1515 gcry_mpi_release (ptick);
1516 divider = gcry_mpi_set_ui (NULL, 2);
1517 gcry_mpi_div (product, NULL, product, divider, 0);
1519 gcry_mpi_release (divider);
1520 for (i = 0; i < count; i++)
1521 gcry_mpi_release (session->a[i]);
1522 GNUNET_free (session->a);
1530 * prepare the response we will send to alice or bobs' clients.
1531 * in Bobs case the product will be NULL.
1533 * @param session the session associated with our client.
1536 prepare_client_response (void *cls,
1537 const struct GNUNET_SCHEDULER_TaskContext *tc)
1539 struct ServiceSession * session = cls;
1540 struct GNUNET_VECTORPRODUCT_client_response * msg;
1541 unsigned char * product_exported = NULL;
1542 size_t product_length = 0;
1543 uint16_t msg_length = 0;
1544 struct MessageObject * msg_obj;
1546 GNUNET_assert (session);
1548 if (session->product)
1550 // get representation as string
1551 GNUNET_assert ( ! gcry_mpi_aprint (GCRYMPI_FMT_USG,
1555 gcry_mpi_release (session->product);
1556 session->product = NULL;
1559 msg_length = sizeof (struct GNUNET_VECTORPRODUCT_client_response) +product_length;
1560 msg = GNUNET_malloc (msg_length);
1561 memcpy (&msg[1], product_exported, product_length);
1562 GNUNET_free_non_null (product_exported);
1563 msg->header.type = htons (GNUNET_MESSAGE_TYPE_VECTORPRODUCT_SERVICE_TO_CLIENT);
1564 msg->header.size = htons (msg_length);
1565 memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
1566 memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
1567 msg->product_length = htonl (product_length);
1569 msg_obj = GNUNET_malloc (sizeof (struct MessageObject));
1570 msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
1571 msg_obj->transmit_handle = NULL; // don't reset the transmit handle
1573 //transmit this message to our client
1574 session->client_transmit_handle =
1575 GNUNET_SERVER_notify_transmit_ready (session->client,
1577 GNUNET_TIME_UNIT_FOREVER_REL,
1580 if ( ! session->client_transmit_handle)
1582 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);
1583 session->client = NULL;
1584 // callback was not called!
1585 GNUNET_free (msg_obj);
1589 // gracefully sent message, just terminate session structure
1590 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sent result to client (%p), this session (%s) has ended!\n"), session->client, GNUNET_h2s (&session->key));
1591 free_session (session);
1596 * Handle a request from another service to calculate a vectorproduct with us.
1598 * @param cls closure (set from GNUNET_MESH_connect)
1599 * @param tunnel connection to the other end
1600 * @param tunnel_ctx place to store local state associated with the tunnel
1601 * @param sender who sent the message
1602 * @param message the actual message
1603 * @param atsi performance data for the connection
1604 * @return GNUNET_OK to keep the connection open,
1605 * GNUNET_SYSERR to close it (signal serious error)
1608 handle_service_request (void *cls,
1609 struct GNUNET_MESH_Tunnel * tunnel,
1611 const struct GNUNET_PeerIdentity * sender,
1612 const struct GNUNET_MessageHeader * message,
1613 const struct GNUNET_ATS_Information * atsi)
1615 struct ServiceSession * session;
1616 struct GNUNET_VECTORPRODUCT_service_request * msg = (struct GNUNET_VECTORPRODUCT_service_request *) message;
1617 uint16_t mask_length;
1619 uint16_t used_elements;
1620 uint16_t element_count;
1621 uint16_t msg_length;
1622 unsigned char * current;
1623 struct ServiceSession * responder_session;
1625 enum SessionState needed_state;
1627 GNUNET_assert (NULL != message);
1628 GNUNET_assert (NULL != sender);
1629 GNUNET_assert (NULL != tunnel_ctx);
1630 session = (struct ServiceSession *) * tunnel_ctx;
1631 // is this tunnel already in use?
1632 if ( (session->next) || (from_service_head == session))
1634 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Got a service request over a tunnel that is already in use, ignoring!\n"));
1635 return GNUNET_SYSERR;
1637 // Check if message was sent by me, which would be bad!
1638 if ( ! memcmp (sender, &me, sizeof (struct GNUNET_PeerIdentity)))
1641 GNUNET_free (session);
1642 return GNUNET_SYSERR;
1644 // this protocol can at best be 1:N, but never M:N!
1645 // Check if the sender is not the peer, I am connected to, which would be bad!
1646 if (memcmp (sender, &session->peer, sizeof (struct GNUNET_PeerIdentity)))
1649 GNUNET_free (session);
1650 return GNUNET_SYSERR;
1653 //we need at least a peer and one message id to compare
1654 if (ntohs (msg->header.size) < sizeof (struct GNUNET_VECTORPRODUCT_service_request))
1656 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from peer!\n"));
1657 GNUNET_free (session);
1658 return GNUNET_SYSERR;
1660 mask_length = ntohs (msg->mask_length);
1661 pk_length = ntohs (msg->pk_length);
1662 used_elements = ntohs (msg->used_element_count);
1663 element_count = ntohs (msg->element_count);
1664 msg_length = sizeof (struct GNUNET_VECTORPRODUCT_service_request)
1665 + mask_length + pk_length + used_elements * PAILLIER_ELEMENT_LENGTH;
1667 //sanity check: is the message as long as the message_count fields suggests?
1668 if ((ntohs (msg->header.size) != msg_length) || (element_count < used_elements)
1669 || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
1672 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from peer, message count does not match message length!\n"));
1673 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)));
1674 GNUNET_free (session);
1675 return GNUNET_SYSERR;
1677 if (find_matching_session (from_service_tail,
1683 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
1684 GNUNET_free (session);
1685 return GNUNET_SYSERR;
1688 memcpy (&session->peer, sender, sizeof (struct GNUNET_PeerIdentity));
1689 session->state = REQUEST_FROM_SERVICE_RECEIVED;
1690 session->element_count = ntohs (msg->element_count);
1691 session->used_element_count = used_elements;
1692 session->tunnel = tunnel;
1695 memcpy (&session->key, &msg->key, sizeof (struct GNUNET_HashCode));
1696 current = (unsigned char *) &msg[1];
1697 //preserve the mask, we will need that later on
1698 session->mask = GNUNET_malloc (mask_length);
1699 memcpy (session->mask, current, mask_length);
1701 current += mask_length;
1703 //convert the publickey to sexp
1704 if (gcry_sexp_new (&session->remote_pubkey, current, pk_length, 1))
1706 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate remote public key to sexpression!\n"));
1707 GNUNET_free (session->mask);
1708 GNUNET_free (session);
1709 return GNUNET_SYSERR;
1712 current += pk_length;
1714 //check if service queue contains a matching request
1715 needed_state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
1716 responder_session = find_matching_session (from_client_tail,
1718 session->element_count,
1719 &needed_state, NULL);
1721 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
1723 if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= sizeof (struct GNUNET_VECTORPRODUCT_service_request)
1726 + used_elements * PAILLIER_ELEMENT_LENGTH)
1728 gcry_error_t ret = 0;
1729 session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * used_elements);
1730 // Convert each vector element to MPI_value
1731 for (i = 0; i < used_elements; i++)
1735 ret = gcry_mpi_scan (&session->a[i],
1737 ¤t[i * PAILLIER_ELEMENT_LENGTH],
1738 PAILLIER_ELEMENT_LENGTH,
1740 if (ret) // read < GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH
1742 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
1743 i, gcry_strsource (ret), gcry_strerror (ret));
1747 GNUNET_CONTAINER_DLL_insert (from_service_head, from_service_tail, session);
1748 if (responder_session)
1750 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s and a matching element set, processing.\n"), GNUNET_h2s (&session->key));
1751 if (GNUNET_OK != compute_service_response (session, responder_session))
1753 //something went wrong, remove it again...
1754 GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, session);
1759 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
1764 // TODO FEATURE: fallback to fragmentation, in case the message is too long
1765 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1769 for (i = 0; i < used_elements; i++)
1771 gcry_mpi_release (session->a[i]);
1772 gcry_sexp_release (session->remote_pubkey);
1773 session->remote_pubkey = NULL;
1774 GNUNET_free_non_null (session->a);
1776 free_session (session);
1777 // and notify our client-session that we could not complete the session
1778 if (responder_session)
1780 // we just found the responder session in this queue
1781 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, responder_session);
1782 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1783 &prepare_client_end_notification,
1786 return GNUNET_SYSERR;
1791 * Handle a response we got from another service we wanted to calculate a vectorproduct with.
1793 * @param cls closure (set from GNUNET_MESH_connect)
1794 * @param tunnel connection to the other end
1795 * @param tunnel_ctx place to store local state associated with the tunnel
1796 * @param sender who sent the message
1797 * @param message the actual message
1798 * @param atsi performance data for the connection
1799 * @return GNUNET_OK to keep the connection open,
1800 * GNUNET_SYSERR to close it (signal serious error)
1803 handle_service_response (void *cls,
1804 struct GNUNET_MESH_Tunnel * tunnel,
1806 const struct GNUNET_PeerIdentity * sender,
1807 const struct GNUNET_MessageHeader * message,
1808 const struct GNUNET_ATS_Information * atsi)
1811 struct ServiceSession * session;
1812 struct GNUNET_VECTORPRODUCT_service_response * msg = (struct GNUNET_VECTORPRODUCT_service_response *) message;
1813 unsigned char * current;
1815 gcry_mpi_t s = NULL;
1816 gcry_mpi_t stick = NULL;
1819 uint16_t used_element_count;
1821 gcry_mpi_t * kp = NULL;
1822 gcry_mpi_t * kq = NULL;
1824 GNUNET_assert (NULL != message);
1825 GNUNET_assert (NULL != sender);
1826 GNUNET_assert (NULL != tunnel_ctx);
1827 session = (struct ServiceSession *) * tunnel_ctx;
1828 GNUNET_assert (NULL != session);
1829 count = session->used_element_count;
1830 session->product = NULL;
1832 if (memcmp (&session->peer, sender, sizeof (struct GNUNET_PeerIdentity)))
1834 GNUNET_break_op (0);
1837 //we need at least a peer and one message id to compare
1838 if (sizeof (struct GNUNET_VECTORPRODUCT_service_response) > ntohs (msg->header.size))
1840 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from peer!\n"));
1843 used_element_count = ntohs (msg->used_element_count);
1844 msg_size = sizeof (struct GNUNET_VECTORPRODUCT_service_response)
1845 + 2 * used_element_count * PAILLIER_ELEMENT_LENGTH
1846 + 2 * PAILLIER_ELEMENT_LENGTH;
1847 //sanity check: is the message as long as the message_count fields suggests?
1848 if ((ntohs (msg->header.size) != msg_size) || (count != used_element_count))
1850 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from peer!\n"));
1853 if (GNUNET_SERVER_MAX_MESSAGE_SIZE < msg_size)
1855 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
1860 current = (unsigned char *) &msg[1];
1861 if (gcry_mpi_scan (&s, GCRYMPI_FMT_USG, current,
1862 PAILLIER_ELEMENT_LENGTH, &read))
1864 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate s to an MPI value!\n"));
1867 current += PAILLIER_ELEMENT_LENGTH;
1869 if (gcry_mpi_scan (&stick, GCRYMPI_FMT_USG, current,
1870 PAILLIER_ELEMENT_LENGTH, &read))
1872 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate s' to an MPI value!\n"));
1875 current += PAILLIER_ELEMENT_LENGTH;
1877 kp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1878 // Convert each kp[] to its MPI_value
1879 for (i = 0; i < count; i++)
1881 if (gcry_mpi_scan (&kp[i], GCRYMPI_FMT_USG, current,
1882 PAILLIER_ELEMENT_LENGTH, &read))
1884 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate Kp[%d]to an MPI value!\n"), i);
1887 current += PAILLIER_ELEMENT_LENGTH;
1891 kq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
1892 // Convert each kq[] to its MPI_value
1893 for (i = 0; i < count; i++)
1895 if (gcry_mpi_scan (&kq[i], GCRYMPI_FMT_USG, current,
1896 PAILLIER_ELEMENT_LENGTH, &read))
1898 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate Kq[%d]to an MPI value!\n"), i);
1901 current += PAILLIER_ELEMENT_LENGTH;
1904 session->product = compute_scalar_product (session, kp, kq, s, stick);
1908 gcry_mpi_release (s);
1910 gcry_mpi_release (stick);
1911 for (i = 0; kp && i < count; i++)
1912 if (kp[i]) gcry_mpi_release (kp[i]);
1913 for (i = 0; kq && i < count; i++)
1914 if (kq[i]) gcry_mpi_release (kq[i]);
1915 GNUNET_free_non_null (kp);
1916 GNUNET_free_non_null (kq);
1918 session->state = FINALIZED;
1919 // the tunnel has done its job, terminate our connection and the tunnel
1920 // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
1921 GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
1922 GNUNET_SCHEDULER_add_now (&destroy_tunnel, session);
1923 // send message with product to client
1924 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
1925 &prepare_client_response, session);
1927 // if success: terminate the session gracefully, else terminate with error
1932 * Task run during shutdown.
1938 shutdown_task (void *cls,
1939 const struct GNUNET_SCHEDULER_TaskContext *tc)
1941 struct ServiceSession * curr;
1942 struct ServiceSession * next;
1943 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
1945 do_shutdown = GNUNET_YES;
1946 // terminate all owned open tunnels.
1947 for (curr = from_client_head; NULL != curr; curr = next)
1950 if (FINALIZED != curr->state)
1952 destroy_tunnel (curr, NULL);
1953 curr->state = FINALIZED;
1959 GNUNET_CORE_disconnect (my_core);
1965 GNUNET_MESH_disconnect (my_mesh);
1972 * To be called on core init/fail.
1974 * @param cls closure, NULL
1975 * @param server handle to the server for this service
1976 * @param my_identity the public identity of this peer
1979 core_init (void *cls, struct GNUNET_CORE_Handle *server,
1980 const struct GNUNET_PeerIdentity *my_identity)
1982 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Core initialized\n"));
1988 * Initialization of the program and message handlers
1990 * @param cls closure
1991 * @param server the initialized server
1992 * @param c configuration to use
1996 struct GNUNET_SERVER_Handle *server,
1997 const struct GNUNET_CONFIGURATION_Handle *c)
1999 static const struct GNUNET_SERVER_MessageHandler server_handlers[] = {
2000 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_VECTORPRODUCT_CLIENT_TO_ALICE, 0},
2001 {&handle_client_request, NULL, GNUNET_MESSAGE_TYPE_VECTORPRODUCT_CLIENT_TO_BOB, 0},
2004 static const struct GNUNET_MESH_MessageHandler mesh_handlers[] = {
2005 { &handle_service_request, GNUNET_MESSAGE_TYPE_VECTORPRODUCT_ALICE_TO_BOB, 0},
2006 { &handle_service_response, GNUNET_MESSAGE_TYPE_VECTORPRODUCT_BOB_TO_ALICE, 0},
2009 static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
2012 static GNUNET_MESH_ApplicationType mesh_types[] = {
2013 GNUNET_APPLICATION_TYPE_VECTORPRODUCT,
2014 GNUNET_APPLICATION_TYPE_END
2017 //generate private/public key set
2018 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating rsa-key.\n"));
2020 // register server callbacks and disconnect handler
2021 GNUNET_SERVER_add_handlers (server, server_handlers);
2022 GNUNET_SERVER_disconnect_notify (server,
2023 &handle_client_disconnect,
2026 my_core = GNUNET_CORE_connect (c, NULL, &core_init, NULL, NULL, NULL,
2027 GNUNET_NO, NULL, GNUNET_NO, core_handlers);
2030 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to CORE failed\n"));
2033 my_mesh = GNUNET_MESH_connect (c, NULL,
2034 &tunnel_incoming_handler,
2035 &tunnel_destruction_handler,
2036 mesh_handlers, mesh_types);
2039 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));
2040 GNUNET_SCHEDULER_shutdown ();
2043 GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Mesh initialized\n"));
2044 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL,
2051 * The main function for the vectorproduct service.
2053 * @param argc number of arguments from the command line
2054 * @param argv command line arguments
2055 * @return 0 ok, 1 on error
2058 main (int argc, char *const *argv)
2060 return (GNUNET_OK ==
2061 GNUNET_SERVICE_run (argc, argv,
2063 GNUNET_SERVICE_OPTION_NONE,
2064 &run, NULL)) ? 0 : 1;
2067 /* end of gnunet-service-ext.c */