excluded test cases for SP for now, while it does not fully work yet
[oweals/gnunet.git] / src / scalarproduct / gnunet-service-scalarproduct.c
index 37b3dedf9c833eda0c3f0f37baf7123276bd796b..3494703333e04d3ea46744dea3f7eee2261a534c 100644 (file)
 #include "gnunet_applications.h"
 #include "gnunet_protocols.h"
 #include "gnunet_scalarproduct_service.h"
-#include "gnunet_scalarproduct.h"
+#include "scalarproduct.h"
+
+#define LOG(kind,...) GNUNET_log_from (kind, "scalarproduct", __VA_ARGS__)
 
 ///////////////////////////////////////////////////////////////////////////////
-//                      Global Variables
+//                     Service Structure Definitions
 ///////////////////////////////////////////////////////////////////////////////
 
 /**
- * Handle to the core service (NULL until we've connected to it).
+ * state a session can be in
+ */
+enum SessionState
+{
+    CLIENT_REQUEST_RECEIVED,
+    WAITING_FOR_BOBS_CONNECT,
+    CLIENT_RESPONSE_RECEIVED,
+    WAITING_FOR_SERVICE_REQUEST,
+    WAITING_FOR_SERVICE_RESPONSE,
+    SERVICE_REQUEST_RECEIVED,
+    SERVICE_RESPONSE_RECEIVED,
+    FINALIZED
+};
+
+/**
+ * role a peer in a session can assume
  */
-static struct GNUNET_CORE_Handle *my_core;
+enum PeerRole
+{
+    ALICE,
+    BOB
+};
+
+
+/**
+ * A scalarproduct session which tracks:
+ * 
+ * a request form the client to our final response.
+ * or
+ * a request from a service to us(service).
+ */
+struct ServiceSession
+{
+    /**
+     * the role this peer has
+     */
+    enum PeerRole role;
+
+    /**
+     * session information is kept in a DLL
+     */
+    struct ServiceSession *next;
+
+    /**
+     * session information is kept in a DLL
+     */
+    struct ServiceSession *prev;
+
+    /**
+     * (hopefully) unique transaction ID
+     */
+    struct GNUNET_HashCode key;
+
+    /** 
+     * state of the session
+     */
+    enum SessionState state;
+
+    /**
+     * Alice or Bob's peerID
+     */
+    struct GNUNET_PeerIdentity peer;
+
+    /**
+     * the client this request is related to
+     */
+    struct GNUNET_SERVER_Client * client;
+
+    /**
+     * The message to send
+     */
+    struct GNUNET_MessageHeader * msg;
+    
+    /**
+     * how many elements we were supplied with from the client
+     */
+    uint32_t element_count;
+
+    /**
+     * how many elements actually are used after applying the mask
+     */
+    uint32_t used_element_count;
+
+    /**
+     * how many bytes the mask is long. 
+     * just for convenience so we don't have to re-re-re calculate it each time
+     */
+    uint32_t mask_length;
+
+    /**
+     * all the vector elements we received
+     */
+    int32_t * vector;
+
+    /**
+     * mask of which elements to check
+     */
+    unsigned char * mask;
+
+    /**
+     * Public key of the remote service, only used by bob
+     */
+    gcry_sexp_t remote_pubkey;
+
+    /**
+     * E(ai)(Bob) or ai(Alice) after applying the mask
+     */
+    gcry_mpi_t * a;
+
+    /**
+     * The computed scalar 
+     */
+    gcry_mpi_t product;
+
+    /**
+     * My transmit handle for the current message to a alice/bob
+     */
+    struct GNUNET_MESH_TransmitHandle * service_transmit_handle;
+
+    /**
+     * My transmit handle for the current message to the client
+     */
+    struct GNUNET_SERVER_TransmitHandle * client_transmit_handle;
+
+    /**
+     * tunnel-handle associated with our mesh handle
+     */
+    struct GNUNET_MESH_Tunnel * tunnel;
+    
+    GNUNET_SCHEDULER_TaskIdentifier client_notification_task;
+    
+    GNUNET_SCHEDULER_TaskIdentifier service_request_task;
+};
+
+///////////////////////////////////////////////////////////////////////////////
+//                      Global Variables
+///////////////////////////////////////////////////////////////////////////////
+
 
 /**
  * Handle to the core service (NULL until we've connected to it).
@@ -60,7 +197,7 @@ static unsigned char * my_pubkey_external;
 /**
  * Service's own public key represented as string
  */
-static uint16_t my_pubkey_external_length = 0;
+static uint32_t my_pubkey_external_length = 0;
 
 /**
  * Service's own n
@@ -87,29 +224,34 @@ static gcry_mpi_t my_mu;
  */
 static gcry_mpi_t my_lambda;
 
+/**
+ * Service's offset for values that could possibly be negative but are plaintext for encryption.
+ */
+static gcry_mpi_t my_offset;
+
 /**
  * Head of our double linked list for client-requests sent to us. 
- * for all of these elements we calculate a vector product with a remote peer
+ * for all of these elements we calculate a scalar product with a remote peer
  * split between service->service and client->service for simplicity
  */
 static struct ServiceSession * from_client_head;
 /**
  * Tail of our double linked list for client-requests sent to us. 
- * for all of these elements we calculate a vector product with a remote peer
+ * for all of these elements we calculate a scalar product with a remote peer
  * split between service->service and client->service for simplicity
  */
 static struct ServiceSession * from_client_tail;
 
 /**
  * Head of our double linked list for service-requests sent to us. 
- * for all of these elements we help the requesting service in calculating a vector product
+ * for all of these elements we help the requesting service in calculating a scalar product
  * split between service->service and client->service for simplicity
  */
 static struct ServiceSession * from_service_head;
 
 /**
  * Tail of our double linked list for service-requests sent to us. 
- * for all of these elements we help the requesting service in calculating a vector product
+ * for all of these elements we help the requesting service in calculating a scalar product
  * split between service->service and client->service for simplicity
  */
 static struct ServiceSession * from_service_tail;
@@ -229,6 +371,12 @@ generate_keyset ()
                     my_pubkey_external_length);
 
   gcry_sexp_release (key);
+  
+  // offset has to be sufficiently small to allow computation of:
+  // m1+m2 mod n == (S + a) + (S + b) mod n, 
+  // if we have more complex operations, this factor needs to be lowered
+  my_offset = gcry_mpi_new(KEYBITS/3);
+  gcry_mpi_set_bit(my_offset, KEYBITS/3);
 
   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Generated key set with key length %d bits.\n"), KEYBITS);
 }
@@ -260,44 +408,29 @@ adjust (unsigned char *buf, size_t size, size_t target)
  * @param c ciphertext (output)
  * @param m plaintext
  * @param g the public base
- * @param r random base (optional) gets generated and if not NULL but uninitialized
  * @param n the module from which which r is chosen (Z*_n)
  * @param n_square the module for encryption, for performance reasons.
  */
 static void
-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)
+encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t n_square)
 {
-#ifndef DISABLE_CRYPTO
   gcry_mpi_t tmp;
-  int release_r = GNUNET_NO;
 
   GNUNET_assert (tmp = gcry_mpi_new (0));
-  if (NULL == r)
-    {
-      GNUNET_assert (r = gcry_mpi_new (0));
-      release_r = GNUNET_YES;
 
-      while (0 <= gcry_mpi_cmp (r, n) || 0 >= gcry_mpi_cmp_ui (r, 1))
-        {
-          gcry_mpi_randomize (r, KEYBITS, GCRY_WEAK_RANDOM);
-          // r must be 1 < r < n
-        }
+  while (0 >= gcry_mpi_cmp_ui (tmp, 1))
+    {
+      gcry_mpi_randomize (tmp, KEYBITS / 3, GCRY_WEAK_RANDOM);
+      // r must be 1 < r < n
     }
 
-
   gcry_mpi_powm (c, g, m, n_square);
-  gcry_mpi_powm (tmp, r, n, n_square);
+  gcry_mpi_powm (tmp, tmp, n, n_square);
   gcry_mpi_mulm (c, tmp, c, n_square);
 
   gcry_mpi_release (tmp);
-  if (GNUNET_YES == release_r)
-    gcry_mpi_release (r);
-#else
-  gcry_mpi_set (c, m);
-#endif
 }
 
-
 /**
  * decrypts an element using the paillier crypto system
  * 
@@ -311,14 +444,10 @@ encrypt_element (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t r, gcry_mp
 static void
 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)
 {
-#ifndef DISABLE_CRYPTO
   gcry_mpi_powm (m, c, lambda, n_square);
   gcry_mpi_sub_ui (m, m, 1);
   gcry_mpi_div (m, NULL, m, n, 0);
   gcry_mpi_mulm (m, m, mu, n);
-#else
-  gcry_mpi_set (m, c);
-#endif
 }
 
 
@@ -330,7 +459,7 @@ decrypt_element (gcry_mpi_t m, gcry_mpi_t c, gcry_mpi_t mu, gcry_mpi_t lambda, g
  * @return an MPI value containing the calculated sum, never NULL
  */
 static gcry_mpi_t
-compute_square_sum (gcry_mpi_t * vector, uint16_t length)
+compute_square_sum (gcry_mpi_t * vector, uint32_t length)
 {
   gcry_mpi_t elem;
   gcry_mpi_t sum;
@@ -364,28 +493,32 @@ compute_square_sum (gcry_mpi_t * vector, uint16_t length)
 static size_t
 do_send_message (void *cls, size_t size, void *buf)
 {
-  struct MessageObject * info = cls;
-  struct GNUNET_MessageHeader * msg;
+  struct ServiceSession * session = cls;
   size_t written = 0;
 
-  GNUNET_assert (info);
-  msg = info->msg;
-  GNUNET_assert (msg);
   GNUNET_assert (buf);
 
-  if (ntohs (msg->size) == size)
+  if (ntohs (session->msg->size) == size)
     {
-      memcpy (buf, msg, size);
+      memcpy (buf, session->msg, size);
       written = size;
     }
 
-  // reset the transmit handle, if necessary
-  if (info->transmit_handle)
-    *info->transmit_handle = NULL;
-
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Sent a message of type %hu.\n"), ntohs (msg->type));
-  GNUNET_free(msg);
-  GNUNET_free(info);
+  switch (ntohs(session->msg->type)){
+    case GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT:
+      session->state = FINALIZED;
+      session->client_transmit_handle = NULL;
+      break;
+    default:
+      session->service_transmit_handle = NULL;
+  }
+    
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
+             "Sent a message of type %hu.\n", 
+             ntohs (session->msg->type));
+  GNUNET_free(session->msg);
+  session->msg = NULL;
+  
   return written;
 }
 
@@ -397,7 +530,7 @@ do_send_message (void *cls, size_t size, void *buf)
  * @return the initialized vector, never NULL
  */
 static gcry_mpi_t *
-initialize_mpi_vector (uint16_t length)
+initialize_mpi_vector (uint32_t length)
 {
   uint32_t i;
   gcry_mpi_t * output = GNUNET_malloc (sizeof (gcry_mpi_t) * length);
@@ -444,7 +577,7 @@ permute_vector (gcry_mpi_t * vector,
  * @return an array of MPI values with random values
  */
 static gcry_mpi_t *
-generate_random_vector (uint16_t length)
+generate_random_vector (uint32_t length)
 {
   gcry_mpi_t * random_vector;
   int32_t value;
@@ -479,8 +612,8 @@ generate_random_vector (uint16_t length)
  */
 static struct ServiceSession *
 find_matching_session (struct ServiceSession * tail,
-                       struct GNUNET_HashCode * key,
-                       uint16_t element_count,
+                       const struct GNUNET_HashCode * key,
+                       uint32_t element_count,
                        enum SessionState * state,
                        const struct GNUNET_PeerIdentity * peerid)
 {
@@ -508,52 +641,31 @@ find_matching_session (struct ServiceSession * tail,
 }
 
 
-static void
-destroy_tunnel (void *cls,
-                const struct GNUNET_SCHEDULER_TaskContext *tc)
-{
-  struct ServiceSession * session = cls;
-
-  if (session->tunnel)
-    {
-      GNUNET_MESH_tunnel_destroy (session->tunnel);
-      session->tunnel = NULL;
-    }
-  session->service_transmit_handle = NULL;
-  // we need to set this to NULL so there is no problem with double-cancel later on.
-}
-
-
 static void
 free_session (struct ServiceSession * session)
 {
-  int i;
-
-  if (FINALIZED != session->state)
-    {
-      if (session->a)
-        {
-          for (i = 0; i < session->used_element_count; i++)
-            gcry_mpi_release (session->a[i]);
+  unsigned int i;
 
-          GNUNET_free (session->a);
-        }
-      if (session->product)
-        gcry_mpi_release (session->product);
+  if (session->a)
+  {
+    for (i = 0; i < session->used_element_count; i++)
+      gcry_mpi_release (session->a[i]);
 
-      if (session->remote_pubkey)
-        gcry_sexp_release (session->remote_pubkey);
+    GNUNET_free (session->a);
+  }
+  if (session->product)
+    gcry_mpi_release (session->product);
 
-      GNUNET_free_non_null (session->vector);
-    }
+  if (session->remote_pubkey)
+    gcry_sexp_release (session->remote_pubkey);
 
+  GNUNET_free_non_null (session->vector);
   GNUNET_free (session);
 }
 ///////////////////////////////////////////////////////////////////////////////
 //                      Event and Message Handlers
 ///////////////////////////////////////////////////////////////////////////////
 
-
 /**
  * A client disconnected. 
  * 
@@ -566,32 +678,41 @@ free_session (struct ServiceSession * session)
  */
 static void
 handle_client_disconnect (void *cls,
-                          struct GNUNET_SERVER_Client
-                          * client)
+                          struct GNUNET_SERVER_Client *client)
 {
-  struct ServiceSession * elem;
-  struct ServiceSession * next;
-
-  // start from the tail, old stuff will be there...
-  for (elem = from_client_head; NULL != elem; elem = next)
+  struct ServiceSession *session;
+  
+  session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
+  if (NULL == session)
+    return;
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+             _ ("Client (%p) disconnected from us.\n"), client);
+  GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
+  
+  if (!(session->role == BOB && session->state == FINALIZED))
     {
-      next = elem->next;
-      if (elem->client != client)
-        continue;
-
-      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Client (%p) disconnected from us.\n"), client);
-      GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, elem);
-
-      if (!(elem->role == BOB && elem->state == FINALIZED))
-        {
-          //we MUST terminate any client message underway
-          if (elem->service_transmit_handle && elem->tunnel)
-            GNUNET_MESH_notify_transmit_ready_cancel (elem->service_transmit_handle);
-          if (elem->tunnel && elem->state == WAITING_FOR_RESPONSE_FROM_SERVICE)
-            destroy_tunnel (elem, NULL);
-        }
-      free_session (elem);
+      //we MUST terminate any client message underway
+      if (session->service_transmit_handle && session->tunnel)
+        GNUNET_MESH_notify_transmit_ready_cancel (session->service_transmit_handle);
+      if (session->tunnel && session->state == WAITING_FOR_SERVICE_RESPONSE)
+        GNUNET_MESH_tunnel_destroy (session->tunnel);
+    }
+  if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task)
+    {
+      GNUNET_SCHEDULER_cancel (session->client_notification_task);
+      session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
+    }
+  if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task)
+    {
+      GNUNET_SCHEDULER_cancel (session->service_request_task);
+      session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
     }
+  if (NULL != session->client_transmit_handle)
+    {
+      GNUNET_SERVER_notify_transmit_ready_cancel (session->client_transmit_handle);
+      session->client_transmit_handle = NULL;
+    }
+  free_session (session);
 }
 
 
@@ -611,9 +732,8 @@ prepare_client_end_notification (void * cls,
 {
   struct ServiceSession * session = cls;
   struct GNUNET_SCALARPRODUCT_client_response * msg;
-  struct MessageObject * msg_obj;
-
-  GNUNET_assert (NULL != session);
+  
+  session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
 
   msg = GNUNET_new (struct GNUNET_SCALARPRODUCT_client_response);
   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
@@ -622,10 +742,9 @@ prepare_client_end_notification (void * cls,
   msg->header.size = htons (sizeof (struct GNUNET_SCALARPRODUCT_client_response));
   // 0 size and the first char in the product is 0, which should never be zero if encoding is used.
   msg->product_length = htonl (0);
-
-  msg_obj = GNUNET_malloc (sizeof (struct MessageObject));
-  msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
-  msg_obj->transmit_handle = NULL; // do not reset the transmit handle, please
+  msg->range = 1;
+  
+  session->msg = &msg->header;
 
   //transmit this message to our client
   session->client_transmit_handle =
@@ -633,22 +752,19 @@ prepare_client_end_notification (void * cls,
                                                sizeof (struct GNUNET_SCALARPRODUCT_client_response),
                                                GNUNET_TIME_UNIT_FOREVER_REL,
                                                &do_send_message,
-                                               msg_obj);
-
+                                               session);
 
   // if we could not even queue our request, something is wrong
-  if ( ! session->client_transmit_handle)
+  if ( NULL == session->client_transmit_handle)
     {
-
-      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);
+      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not send message to client (%p)!\n"), session->client);
       // usually gets freed by do_send_message
-      GNUNET_free (msg_obj);
+      session->msg = NULL;
       GNUNET_free (msg);
     }
   else
     GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sending session-end notification to client (%p) for session %s\n"), &session->client, GNUNET_h2s (&session->key));
   
-  free_session(session);
 }
 
 
@@ -661,10 +777,10 @@ prepare_client_end_notification (void * cls,
  *      S: $S := E_A(sum (r_i + b_i)^2)$
  *     S': $S' := E_A(sum r_i^2)$
  * 
- * @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)})$
- * @param kq    (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
+ * @param r    (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)})$
+ * @param r_prime    (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
  * @param s         S: $S := E_A(sum (r_i + b_i)^2)$
- * @param stick    S': $S' := E_A(sum r_i^2)$
+ * @param s_prime    S': $S' := E_A(sum r_i^2)$
  * @param request  the associated requesting session with alice
  * @param response the associated responder session with bob's client
  * @return GNUNET_SYSERR if the function was called with NULL parameters or if there was an error
@@ -672,33 +788,30 @@ prepare_client_end_notification (void * cls,
  *         GNUNET_OK if the operation succeeded
  */
 static int
-prepare_service_response (gcry_mpi_t * kp,
-                          gcry_mpi_t * kq,
+prepare_service_response (gcry_mpi_t * r,
+                          gcry_mpi_t * r_prime,
                           gcry_mpi_t s,
-                          gcry_mpi_t stick,
+                          gcry_mpi_t s_prime,
                           struct ServiceSession * request,
                           struct ServiceSession * response)
 {
   struct GNUNET_SCALARPRODUCT_service_response * msg;
-  uint16_t msg_length = 0;
+  uint32_t msg_length = 0;
   unsigned char * current = NULL;
   unsigned char * element_exported = NULL;
   size_t element_length = 0;
   int i;
 
-  GNUNET_assert (request);
-
   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
           + 2 * request->used_element_count * PAILLIER_ELEMENT_LENGTH // kp, kq
           + 2 * PAILLIER_ELEMENT_LENGTH; // s, stick
 
   msg = GNUNET_malloc (msg_length);
-  GNUNET_assert (msg);
 
   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE);
   msg->header.size = htons (msg_length);
-  msg->element_count = htons (request->element_count);
-  msg->used_element_count = htons (request->used_element_count);
+  msg->element_count = htonl (request->element_count);
+  msg->used_element_count = htonl (request->used_element_count);
   memcpy (&msg->key, &request->key, sizeof (struct GNUNET_HashCode));
   current = (unsigned char *) &msg[1];
 
@@ -724,7 +837,7 @@ prepare_service_response (gcry_mpi_t * kp,
     GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
                                         element_exported, PAILLIER_ELEMENT_LENGTH,
                                         &element_length,
-                                        stick));
+                                        s_prime));
     adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
     memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
     GNUNET_free (element_exported);
@@ -738,7 +851,7 @@ prepare_service_response (gcry_mpi_t * kp,
       GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
                                           element_exported, PAILLIER_ELEMENT_LENGTH,
                                           &element_length,
-                                          kp[i]));
+                                          r[i]));
       adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
       memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
       GNUNET_free (element_exported);
@@ -753,7 +866,7 @@ prepare_service_response (gcry_mpi_t * kp,
       GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
                                           element_exported, PAILLIER_ELEMENT_LENGTH,
                                           &element_length,
-                                          kq[i]));
+                                          r_prime[i]));
       adjust (element_exported, element_length, PAILLIER_ELEMENT_LENGTH);
       memcpy (current, element_exported, PAILLIER_ELEMENT_LENGTH);
       GNUNET_free (element_exported);
@@ -762,37 +875,28 @@ prepare_service_response (gcry_mpi_t * kp,
 
   if (GNUNET_SERVER_MAX_MESSAGE_SIZE >= msg_length)
     {
-      struct MessageObject * msg_obj;
-
-      msg_obj = GNUNET_new (struct MessageObject);
-      msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
-      msg_obj->transmit_handle = (void *) &request->service_transmit_handle; //and reset the transmit handle
+      request->msg = (struct GNUNET_MessageHeader *) msg;
       request->service_transmit_handle =
               GNUNET_MESH_notify_transmit_ready (request->tunnel,
                                                  GNUNET_YES,
                                                  GNUNET_TIME_UNIT_FOREVER_REL,
-                                                 &request->peer, //must be specified, we are a slave/participant/non-owner
                                                  msg_length,
                                                  &do_send_message,
-                                                 msg_obj);
+                                                 request);
       // we don't care if it could be send or not. either way, the session is over for us.
       request->state = FINALIZED;
-      response->state = FINALIZED;
     }
   else
-    {
-      // TODO FEATURE: fallback to fragmentation, in case the message is too long
       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!)\n"));
-    }
 
   //disconnect our client
-  if ( ! request->service_transmit_handle)
+  if ( NULL == request->service_transmit_handle)
     {
       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Could not send service-response message via mesh!)\n"));
-      GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, response);
-      GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                    &prepare_client_end_notification,
-                                    response);
+      
+      response->client_notification_task = 
+              GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
+                                        response);
       return GNUNET_NO;
     }
   return GNUNET_OK;
@@ -802,10 +906,10 @@ prepare_service_response (gcry_mpi_t * kp,
 /**
  * executed by bob: 
  * compute the values 
- *  (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)})$
- *  (2)[]: $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
- *      S: $S := E_A(sum (r_i + b_i)^2)$
- *     S': $S' := E_A(sum r_i^2)$
+ *  (1)[]: $E_A(a_{\pi(i)}) \otimes E_A(- r_{\pi(i)} - b_{\pi(i)}) &= E_A(a_{\pi(i)} - r_{\pi(i)} - b_{\pi(i)})$
+ *  (2)[]: $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
+ *      S: $S := E_A(\sum (r_i + b_i)^2)$
+ *     S': $S' := E_A(\sum r_i^2)$
  * 
  * @param request the requesting session + bob's requesting peer
  * @param response the responding session + bob's client handle
@@ -816,38 +920,37 @@ static int
 compute_service_response (struct ServiceSession * request,
                           struct ServiceSession * response)
 {
-  int i, j, ret = GNUNET_SYSERR;
+  int i;
+  int j;
+  int ret = GNUNET_SYSERR;
   unsigned int * p;
   unsigned int * q;
-  uint16_t count;
+  uint32_t count;
+  gcry_mpi_t * rand = NULL;
   gcry_mpi_t * r = NULL;
-  gcry_mpi_t * kp = NULL;
-  gcry_mpi_t * kq = NULL;
+  gcry_mpi_t * r_prime = NULL;
   gcry_mpi_t * b;
-  gcry_mpi_t * ap;
-  gcry_mpi_t * aq;
-  gcry_mpi_t * bp;
-  gcry_mpi_t * bq;
-  gcry_mpi_t * rp;
-  gcry_mpi_t * rq;
+  gcry_mpi_t * a_pi;
+  gcry_mpi_t * a_pi_prime;
+  gcry_mpi_t * b_pi;
+  gcry_mpi_t * rand_pi;
+  gcry_mpi_t * rand_pi_prime;
   gcry_mpi_t s = NULL;
-  gcry_mpi_t stick = NULL;
+  gcry_mpi_t s_prime = NULL;
   gcry_mpi_t remote_n = NULL;
   gcry_mpi_t remote_nsquare;
   gcry_mpi_t remote_g = NULL;
   gcry_sexp_t tmp_exp;
   uint32_t value;
 
-  GNUNET_assert (request != NULL && response != NULL);
   count = request->used_element_count;
 
   b = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
-  ap = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
-  bp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
-  aq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
-  bq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
-  rp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
-  rq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
+  a_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
+  b_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
+  a_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
+  rand_pi = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
+  rand_pi_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
 
   // convert responder session to from long to mpi
   for (i = 0, j = 0; i < response->element_count && j < count; i++)
@@ -909,76 +1012,71 @@ compute_service_response (struct ServiceSession * request,
   gcry_sexp_release (tmp_exp);
 
   // generate r, p and q
-  r = generate_random_vector (count);
+  rand = generate_random_vector (count);
   p = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
   q = GNUNET_CRYPTO_random_permute (GNUNET_CRYPTO_QUALITY_WEAK, count);
   //initialize the result vectors
-  kp = initialize_mpi_vector (count);
-  kq = initialize_mpi_vector (count);
+  r = initialize_mpi_vector (count);
+  r_prime = initialize_mpi_vector (count);
 
   // copy the REFERNCES of a, b and r into aq and bq. we will not change 
   // those values, thus we can work with the references
-  memcpy (ap, request->a, sizeof (gcry_mpi_t) * count);
-  memcpy (aq, request->a, sizeof (gcry_mpi_t) * count);
-  memcpy (bp, b, sizeof (gcry_mpi_t) * count);
-  memcpy (bq, b, sizeof (gcry_mpi_t) * count);
-  memcpy (rp, r, sizeof (gcry_mpi_t) * count);
-  memcpy (rq, r, sizeof (gcry_mpi_t) * count);
+  memcpy (a_pi, request->a, sizeof (gcry_mpi_t) * count);
+  memcpy (a_pi_prime, request->a, sizeof (gcry_mpi_t) * count);
+  memcpy (b_pi, b, sizeof (gcry_mpi_t) * count);
+  memcpy (rand_pi, rand, sizeof (gcry_mpi_t) * count);
+  memcpy (rand_pi_prime, rand, sizeof (gcry_mpi_t) * count);
 
   // generate p and q permutations for a, b and r
-  GNUNET_assert (permute_vector (ap, p, count));
-  GNUNET_assert (permute_vector (bp, p, count));
-  GNUNET_assert (permute_vector (rp, p, count));
-  GNUNET_assert (permute_vector (aq, q, count));
-  GNUNET_assert (permute_vector (bq, q, count));
-  GNUNET_assert (permute_vector (rq, q, count));
+  GNUNET_assert (permute_vector (a_pi, p, count));
+  GNUNET_assert (permute_vector (b_pi, p, count));
+  GNUNET_assert (permute_vector (rand_pi, p, count));
+  GNUNET_assert (permute_vector (a_pi_prime, q, count));
+  GNUNET_assert (permute_vector (rand_pi_prime, q, count));
 
   // encrypt the element
   // for the sake of readability I decided to have dedicated permutation
   // vectors, which get rid of all the lookups in p/q. 
   // however, ap/aq are not absolutely necessary but are just abstraction
-  // Calculate Kp = E(a_pi) + E(-r_pi - b_pi)
+  // Calculate Kp = E(S + a_pi) (+) E(S - r_pi - b_pi)
   for (i = 0; i < count; i++)
     {
-      // E(-r_pi - b_pi)
-      gcry_mpi_sub (kp[i], kp[i], rp[i]);
-      gcry_mpi_sub (kp[i], kp[i], bp[i]);
-      encrypt_element (kp[i], kp[i], NULL, remote_g, remote_n, remote_nsquare);
-
-      // E(-r_pi - b_pi) * E(a_pi) ==  E(a + (-r -b))
-      //gcry_mpi_mulm (kp[i], kp[i], ap[i], remote_nsquare);
-      gcry_mpi_add (kp[i], kp[i], ap[i]);
+      // E(S - r_pi - b_pi)
+      gcry_mpi_sub (r[i], my_offset, rand_pi[i]);
+      gcry_mpi_sub (r[i], r[i], b_pi[i]);
+      encrypt_element (r[i], r[i], remote_g, remote_n, remote_nsquare);
+
+      // E(S - r_pi - b_pi) * E(S + a_pi) ==  E(2*S + a - r - b)
+      gcry_mpi_mulm (r[i], r[i], a_pi[i], remote_nsquare);
     }
-  GNUNET_free (ap);
-  GNUNET_free (bp);
-  GNUNET_free (rp);
+  GNUNET_free (a_pi);
+  GNUNET_free (b_pi);
+  GNUNET_free (rand_pi);
 
-  // Calculate Kq = E(a_qi) + E( -r_qi)
+  // Calculate Kq = E(S + a_qi) (+) E(S - r_qi)
   for (i = 0; i < count; i++)
     {
-      // E(-r_qi)
-      gcry_mpi_sub (kq[i], kq[i], rq[i]);
-      encrypt_element (kq[i], kq[i], NULL, remote_g, remote_n, remote_nsquare);
+      // E(S - r_qi)
+      gcry_mpi_sub (r_prime[i], my_offset, rand_pi_prime[i]);
+      encrypt_element (r_prime[i], r_prime[i], remote_g, remote_n, remote_nsquare);
 
-      // E(-r_qi) * E(a_qi) == E(aqi + (- rqi))
-      //gcry_mpi_mulm (kq[i], kq[i], aq[i], remote_nsquare);
-      gcry_mpi_add (kq[i], kq[i], aq[i]);
+      // E(S - r_qi) * E(S + a_qi) == E(2*S + a_qi - r_qi)
+      gcry_mpi_mulm (r_prime[i], r_prime[i], a_pi_prime[i], remote_nsquare);
     }
-  GNUNET_free (aq);
-  GNUNET_free (bq);
-  GNUNET_free (rq);
+  GNUNET_free (a_pi_prime);
+  GNUNET_free (rand_pi_prime);
 
   // Calculate S' =  E(SUM( r_i^2 ))
-  stick = compute_square_sum (r, count);
-  encrypt_element (stick, stick, NULL, remote_g, remote_n, remote_nsquare);
+  s_prime = compute_square_sum (rand, count);
+  encrypt_element (s_prime, s_prime, remote_g, remote_n, remote_nsquare);
 
   // Calculate S = E(SUM( (r_i + b_i)^2 ))
   for (i = 0; i < count; i++)
     {
-      gcry_mpi_add (r[i], r[i], b[i]);
+      gcry_mpi_add (rand[i], rand[i], b[i]);
     }
-  s = compute_square_sum (r, count);
-  encrypt_element (s, s, NULL, remote_g, remote_n, remote_nsquare);
+  s = compute_square_sum (rand, count);
+  encrypt_element (s, s, remote_g, remote_n, remote_nsquare);
   gcry_mpi_release (remote_n);
   gcry_mpi_release (remote_g);
   gcry_mpi_release (remote_nsquare);
@@ -986,22 +1084,23 @@ compute_service_response (struct ServiceSession * request,
   // release r and tmp
   for (i = 0; i < count; i++)
     // rp, rq, aq, ap, bp, bq are released along with a, r, b respectively, (a and b are handled at except:)
-    gcry_mpi_release (r[i]);
+    gcry_mpi_release (rand[i]);
 
   // copy the Kp[], Kq[], S and Stick into a new message
-  if (GNUNET_YES != prepare_service_response (kp, kq, s, stick, request, response))
-    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Computation of values for alice failed!\n"));
+  if (GNUNET_YES != prepare_service_response (r, r_prime, s, s_prime, request, response))
+    GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Failed to communicate with `%s', scalar product calculation aborted.\n"),
+               GNUNET_i2s (&request->peer));
   else
     ret = GNUNET_OK;
 
   for (i = 0; i < count; i++)
     {
-      gcry_mpi_release (kq[i]);
-      gcry_mpi_release (kp[i]);
+      gcry_mpi_release (r_prime[i]);
+      gcry_mpi_release (r[i]);
     }
 
   gcry_mpi_release (s);
-  gcry_mpi_release (stick);
+  gcry_mpi_release (s_prime);
 
 except:
   for (i = 0; i < count; i++)
@@ -1022,30 +1121,27 @@ except:
  * Executed by Alice, fills in a service-request message and sends it to the given peer
  * 
  * @param session the session associated with this request, then also holds the CORE-handle
- * @return GNUNET_SYSERR if we could not send the message
- *         GNUNET_NO if the message was too large
- *         GNUNET_OK if we sent it
+ * @return #GNUNET_SYSERR if we could not send the message
+ *         #GNUNET_NO if the message was too large
+ *         #GNUNET_OK if we sent it
  */
 static void
 prepare_service_request (void *cls,
-                         const struct GNUNET_PeerIdentity * peer,
-                         const struct GNUNET_ATS_Information * atsi)
+                         const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
   struct ServiceSession * session = cls;
   unsigned char * current;
   struct GNUNET_SCALARPRODUCT_service_request * msg;
-  struct MessageObject * msg_obj;
   unsigned int i;
   unsigned int j;
-  uint16_t msg_length;
-  size_t element_length = 0; //gets initialized by gcry_mpi_print, but the compiler doesn't know that
+  uint32_t msg_length;
+  size_t element_length = 0; // initialized by gcry_mpi_print, but the compiler doesn't know that
   gcry_mpi_t a;
-  gcry_mpi_t r;
   uint32_t value;
+  
+  session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
 
-  GNUNET_assert (NULL != cls);
-  GNUNET_assert (NULL != peer);
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (peer));
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Successfully created new tunnel to peer (%s)!\n"), GNUNET_i2s (&session->peer));
 
   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
           + session->used_element_count * PAILLIER_ELEMENT_LENGTH
@@ -1057,22 +1153,20 @@ prepare_service_request (void *cls,
       + session->mask_length
       + my_pubkey_external_length)
     {
-      // TODO FEATURE: fallback to fragmentation, in case the message is too long
       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
-      GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
-      GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                    &prepare_client_end_notification,
-                                    session);
+      session->client_notification_task = 
+              GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
+                                        session);
       return;
     }
+  
   msg = GNUNET_malloc (msg_length);
-
   msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_ALICE_TO_BOB);
   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
-  msg->mask_length = htons (session->mask_length);
-  msg->pk_length = htons (my_pubkey_external_length);
-  msg->used_element_count = htons (session->used_element_count);
-  msg->element_count = htons (session->element_count);
+  msg->mask_length = htonl (session->mask_length);
+  msg->pk_length = htonl (my_pubkey_external_length);
+  msg->used_element_count = htonl (session->used_element_count);
+  msg->element_count = htonl (session->element_count);
   msg->header.size = htons (msg_length);
 
   // fill in the payload
@@ -1087,7 +1181,6 @@ prepare_service_request (void *cls,
   // now copy over the element vector
   session->a = GNUNET_malloc (sizeof (gcry_mpi_t) * session->used_element_count);
   a = gcry_mpi_new (KEYBITS * 2);
-  r = gcry_mpi_new (KEYBITS * 2);
   // encrypt our vector and generate string representations
   for (i = 0, j = 0; i < session->element_count; i++)
     {
@@ -1097,18 +1190,16 @@ prepare_service_request (void *cls,
           unsigned char * element_exported = GNUNET_malloc (PAILLIER_ELEMENT_LENGTH);
           value = session->vector[i] >= 0 ? session->vector[i] : -session->vector[i];
 
+          a = gcry_mpi_set_ui (a, 0);
           // long to gcry_mpi_t
           if (session->vector[i] < 0)
-            {
-              a = gcry_mpi_set_ui (NULL, 0);
-              gcry_mpi_sub_ui (a, a, value);
-            }
+            gcry_mpi_sub_ui (a, a, value);
           else
-            a = gcry_mpi_set_ui (NULL, value);
+            gcry_mpi_add_ui (a, a, value);
 
-          // multiply with a given factor to avoid disclosing 1
           session->a[j++] = gcry_mpi_set (NULL, a);
-          encrypt_element (a, a, r, my_g, my_n, my_nsquare);
+          gcry_mpi_add (a, a, my_offset);
+          encrypt_element (a, a, my_g, my_n, my_nsquare);
 
           // get representation as string
           // we always supply some value, so gcry_mpi_print fails only if it can't reserve memory
@@ -1126,72 +1217,29 @@ prepare_service_request (void *cls,
         }
     }
   gcry_mpi_release (a);
-  gcry_mpi_release (r);
 
-  msg_obj = GNUNET_malloc (sizeof (struct MessageObject));
-  msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
-  msg_obj->transmit_handle = (void *) &session->service_transmit_handle; //and reset the transmit handle
+  session->msg = (struct GNUNET_MessageHeader *) msg;
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Transmitting service request.\n"));
 
   //transmit via mesh messaging
-  session->state = WAITING_FOR_RESPONSE_FROM_SERVICE;
   session->service_transmit_handle = GNUNET_MESH_notify_transmit_ready (session->tunnel, GNUNET_YES,
                                                                         GNUNET_TIME_UNIT_FOREVER_REL,
-                                                                        peer, //multicast to all targets, maybe useful in the future
                                                                         msg_length,
                                                                         &do_send_message,
-                                                                        msg_obj);
+                                                                        session);
   if ( ! session->service_transmit_handle)
     {
       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _("Could not send mutlicast message to tunnel!\n"));
-      GNUNET_free (msg_obj);
       GNUNET_free (msg);
-      GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
-      GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                    &prepare_client_end_notification,
-                                    session);
+      session->msg = NULL;
+      session->client_notification_task = 
+              GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
+                                        session);
       return;
     }
+  session->state = WAITING_FOR_SERVICE_RESPONSE;
 }
 
-
-/**
- * Method called whenever a peer has disconnected from the tunnel.
- * Implementations of this callback must NOT call
- * GNUNET_MESH_tunnel_destroy immediately, but instead schedule those
- * to run in some other task later.  However, calling 
- * "GNUNET_MESH_notify_transmit_ready_cancel" is allowed.
- *
- * @param cls closure
- * @param peer peer identity the tunnel stopped working with
- */
-static void
-tunnel_peer_disconnect_handler (void *cls, const struct GNUNET_PeerIdentity * peer)
-{
-  // as we have only one peer connected in each session, just remove the session and say good bye
-  struct ServiceSession * session = cls;
-  struct ServiceSession * curr;
-  GNUNET_assert(cls);
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Peer (%s) disconnected from our tunnel!\n"), GNUNET_i2s (peer));
-
-  if ((session->role == ALICE) && (FINALIZED != session->state) && ( ! do_shutdown))
-    {
-      for (curr = from_client_head; NULL != curr; curr = curr->next)
-        if (curr == session)
-          {
-            GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
-            break;
-          }
-      GNUNET_SCHEDULER_add_now (&destroy_tunnel,
-                                session);
-      // if this happened before we received the answer, we must terminate the session
-      GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                    &prepare_client_end_notification,
-                                    session);
-    }
-}
-
-
 /**
  * Handler for a client request message. 
  * Can either be type A or B
@@ -1207,33 +1255,45 @@ handle_client_request (void *cls,
                        struct GNUNET_SERVER_Client *client,
                        const struct GNUNET_MessageHeader *message)
 {
-  struct GNUNET_SCALARPRODUCT_client_request * msg = (struct GNUNET_SCALARPRODUCT_client_request *) message;
+  const struct GNUNET_SCALARPRODUCT_client_request * msg = (const struct GNUNET_SCALARPRODUCT_client_request *) message;
   struct ServiceSession * session;
-  uint16_t element_count;
-  uint16_t mask_length;
-  uint16_t msg_type;
+  uint32_t element_count;
+  uint32_t mask_length;
+  uint32_t msg_type;
   int32_t * vector;
   uint32_t i;
 
-  GNUNET_assert (message);
+  // only one concurrent session per client connection allowed, simplifies logics a lot...
+  session = GNUNET_SERVER_client_get_user_context (client, struct ServiceSession);
+  if ((NULL != session) && (session->state != FINALIZED)){
+    GNUNET_SERVER_receive_done (client, GNUNET_OK);
+    return;
+  }
+  else if(NULL != session){
+    // old session is already completed, clean it up
+    GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
+    free_session(session);
+  }
 
   //we need at least a peer and one message id to compare
   if (sizeof (struct GNUNET_SCALARPRODUCT_client_request) > ntohs (msg->header.size))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from client!\n"));
+      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
+                 _ ("Too short message received from client!\n"));
       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
       return;
     }
 
   msg_type = ntohs (msg->header.type);
-  element_count = ntohs (msg->element_count);
-  mask_length = ntohs (msg->mask_length);
+  element_count = ntohl (msg->element_count);
+  mask_length = ntohl (msg->mask_length);
 
   //sanity check: is the message as long as the message_count fields suggests?
   if (( ntohs (msg->header.size) != (sizeof (struct GNUNET_SCALARPRODUCT_client_request) + element_count * sizeof (int32_t) + mask_length))
       || (0 == element_count))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from client, session information incorrect!\n"));
+      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
+                 _ ("Invalid message received from client, session information incorrect!\n"));
       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
       return;
     }
@@ -1244,12 +1304,16 @@ handle_client_request (void *cls,
                                      element_count,
                                      NULL, NULL))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Duplicate session information received, cannot create new session with key `%s'\n"), GNUNET_h2s (&msg->key));
+      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 
+                 _ ("Duplicate session information received, cannot create new session with key `%s'\n"), 
+                 GNUNET_h2s (&msg->key));
       GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
       return;
     }
 
-  session = GNUNET_malloc (sizeof (struct ServiceSession));
+  session = GNUNET_new (struct ServiceSession);
+  session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
+  session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
   session->client = client;
   session->element_count = element_count;
   session->mask_length = mask_length;
@@ -1261,7 +1325,9 @@ handle_client_request (void *cls,
 
   if (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_CLIENT_TO_ALICE == msg_type)
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"), GNUNET_h2s (&session->key));
+      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 
+                 _ ("Got client-request-session with key %s, preparing tunnel to remote service.\n"), 
+                 GNUNET_h2s (&session->key));
 
       session->role = ALICE;
       // fill in the mask
@@ -1279,11 +1345,10 @@ handle_client_request (void *cls,
             session->used_element_count++;
         }
 
-      if ( ! session->used_element_count)
+      if ( 0 == session->used_element_count)
         {
           GNUNET_break_op (0);
           GNUNET_free (session->vector);
-          GNUNET_free (session->a);
           GNUNET_free (session);
           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
           return;
@@ -1293,47 +1358,54 @@ handle_client_request (void *cls,
         {
           GNUNET_break (0);
           GNUNET_free (session->vector);
-          GNUNET_free (session->a);
           GNUNET_free (session);
           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
           return;
         }
       // get our peer ID
       memcpy (&session->peer, &msg->peer, sizeof (struct GNUNET_PeerIdentity));
-      GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Creating new tunnel to for session with key %s.\n"), GNUNET_h2s (&session->key));
-      GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
+      GNUNET_log (GNUNET_ERROR_TYPE_INFO, 
+                 _ ("Creating new tunnel to for session with key %s.\n"), 
+                 GNUNET_h2s (&session->key));
       session->tunnel = GNUNET_MESH_tunnel_create (my_mesh, session,
-                                                   prepare_service_request,
-                                                   tunnel_peer_disconnect_handler,
-                                                   session);
+                                                   &session->peer,
+                                                   GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
+                                                   GNUNET_NO,
+                                                   GNUNET_YES);
+      //prepare_service_request, tunnel_peer_disconnect_handler,
       if ( ! session->tunnel)
         {
           GNUNET_break (0);
           GNUNET_free (session->vector);
-          GNUNET_free (session->a);
           GNUNET_free (session);
           GNUNET_SERVER_receive_done (client, GNUNET_SYSERR);
           return;
         }
-      GNUNET_MESH_peer_request_connect_add (session->tunnel, &session->peer);
-      GNUNET_SERVER_receive_done (client, GNUNET_YES);
-      session->state = WAITING_FOR_BOBS_CONNECT;
+      GNUNET_SERVER_client_set_user_context (client, session);
+      GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
+      
+      session->state = CLIENT_REQUEST_RECEIVED;
+      session->service_request_task = 
+              GNUNET_SCHEDULER_add_now (&prepare_service_request, 
+                                        session);
+      
     }
   else
     {
       struct ServiceSession * requesting_session;
-      enum SessionState needed_state = REQUEST_FROM_SERVICE_RECEIVED;
-
+      enum SessionState needed_state = SERVICE_REQUEST_RECEIVED;
+      
       session->role = BOB;
       session->mask = NULL;
       // copy over the elements
       session->used_element_count = element_count;
       for (i = 0; i < element_count; i++)
         session->vector[i] = ntohl (vector[i]);
-      session->state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
+      session->state = CLIENT_RESPONSE_RECEIVED;
       
+      GNUNET_SERVER_client_set_user_context (client, session);
       GNUNET_CONTAINER_DLL_insert (from_client_head, from_client_tail, session);
-      GNUNET_SERVER_receive_done (client, GNUNET_YES);
+      
       //check if service queue contains a matching request 
       requesting_session = find_matching_session (from_service_tail,
                                                   &session->key,
@@ -1343,18 +1415,18 @@ handle_client_request (void *cls,
         {
           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));
           if (GNUNET_OK != compute_service_response (requesting_session, session))
-            {
-              GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
-              GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                            &prepare_client_end_notification,
-                                            session);
-            }
+              session->client_notification_task = 
+                      GNUNET_SCHEDULER_add_now (&prepare_client_end_notification, 
+                                                session);
+              
         }
-      else
+      else{
         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));
         // no matching session exists yet, store the response
         // for later processing by handle_service_request()
+      }
     }
+  GNUNET_SERVER_receive_done (client, GNUNET_YES);
 }
 
 
@@ -1369,68 +1441,85 @@ handle_client_request (void *cls,
  *         (can be NULL -- that's not an error)
  */
 static void *
-tunnel_incoming_handler (void *cls, struct GNUNET_MESH_Tunnel *tunnel,
+tunnel_incoming_handler (void *cls, 
+                         struct GNUNET_MESH_Tunnel *tunnel,
                          const struct GNUNET_PeerIdentity *initiator,
-                         const struct GNUNET_ATS_Information *atsi)
+                         uint32_t port)
 {
-
   struct ServiceSession * c = GNUNET_new (struct ServiceSession);
 
-  memcpy (&c->peer, initiator, sizeof (struct GNUNET_PeerIdentity));
+  c->peer = *initiator;
   c->tunnel = tunnel;
   c->role = BOB;
+  c->state = WAITING_FOR_SERVICE_REQUEST;
   return c;
 }
 
 
 /**
- * Function called whenever an inbound tunnel is destroyed.  Should clean up
- * any associated state.
+ * Function called whenever a tunnel is destroyed.  Should clean up
+ * any associated state. 
+ * 
+ * It must NOT call GNUNET_MESH_tunnel_destroy on the tunnel.
  *
  * @param cls closure (set from GNUNET_MESH_connect)
  * @param tunnel connection to the other end (henceforth invalid)
  * @param tunnel_ctx place where local state associated
- *                   with the tunnel is stored (our 'struct TunnelState')
+ *                   with the tunnel is stored
  */
 static void
 tunnel_destruction_handler (void *cls,
                             const struct GNUNET_MESH_Tunnel *tunnel,
                             void *tunnel_ctx)
 {
-  struct ServiceSession * service_session = tunnel_ctx;
+  struct ServiceSession * session = tunnel_ctx;
   struct ServiceSession * client_session;
   struct ServiceSession * curr;
-
-  GNUNET_assert (service_session);
-  if (!memcmp (&service_session->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
-    return;
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Tunnel destroyed, terminating session with peer (%s)\n"), GNUNET_i2s (&service_session->peer));
-  // remove the session, unless it has already been dequeued, but somehow still active
-  // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
-  for (curr = from_service_head; NULL != curr; curr = curr->next)
-        if (curr == service_session)
-          {
-            GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
-            break;
-          }
-  // there is a client waiting for this service session, terminate it, too!
-  // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
-  client_session = find_matching_session (from_client_tail,
-                                          &service_session->key,
-                                          service_session->element_count,
-                                          NULL, NULL);
-  free_session (service_session);
-
-  // the client has to check if it was waiting for a result 
-  // or if it was a responder, no point in adding more statefulness
-  if (client_session && ( ! do_shutdown))
+  
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
+             _("Peer disconnected, terminating session %s with peer (%s)\n"), 
+             GNUNET_h2s (&session->key), 
+             GNUNET_i2s (&session->peer));
+  if (ALICE == session->role) {
+    // as we have only one peer connected in each session, just remove the session
+
+    if ((SERVICE_RESPONSE_RECEIVED > session->state) && (!do_shutdown))
     {
-      // remove the session, we just found it in the queue, so it must be there
-      GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, client_session);
-      GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                    &prepare_client_end_notification,
-                                    client_session);
+      session->tunnel = NULL;
+      // if this happened before we received the answer, we must terminate the session
+      session->client_notification_task = 
+              GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
+                                        session);
     }
+  }
+  else { //(BOB == session->role) service session
+            
+    // remove the session, unless it has already been dequeued, but somehow still active
+    // this could bug without the IF in case the queue is empty and the service session was the only one know to the service
+    // scenario: disconnect before alice can send her message to bob.
+    for (curr = from_service_head; NULL != curr; curr = curr->next)
+      if (curr == session)
+      {
+        GNUNET_CONTAINER_DLL_remove (from_service_head, from_service_tail, curr);
+        break;
+      }
+    // there is a client waiting for this service session, terminate it, too!
+    // i assume the tupel of key and element count is unique. if it was not the rest of the code would not work either.
+    client_session = find_matching_session (from_client_tail,
+                                            &session->key,
+                                            session->element_count,
+                                            NULL, NULL);
+    free_session (session);
+
+    // the client has to check if it was waiting for a result 
+    // or if it was a responder, no point in adding more statefulness
+    if (client_session && (!do_shutdown))
+    {
+      client_session->client_notification_task = 
+              GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
+                                        client_session);
+    }
+  }
 }
 
 
@@ -1439,90 +1528,89 @@ tunnel_destruction_handler (void *cls,
  * 
  * @param session - the session associated with this computation
  * @param kp - (1) from the protocol definition: 
- *             $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)})$
+ *             $E_A(a_{\pi(i)}) \otimes E_A(- r_{\pi(i)} - b_{\pi(i)}) &= E_A(a_{\pi(i)} - r_{\pi(i)} - b_{\pi(i)})$
  * @param kq - (2) from the protocol definition: 
- *             $E_A(a_{pi'(i)}) times E_A(- r_{pi'(i)}) &= E_A(a_{pi'(i)} - r_{pi'(i)})$
+ *             $E_A(a_{\pi'(i)}) \otimes E_A(- r_{\pi'(i)}) &= E_A(a_{\pi'(i)} - r_{\pi'(i)})$
  * @param s - S from the protocol definition: 
- *            $S := E_A(sum (r_i + b_i)^2)$
+ *            $S := E_A(\sum (r_i + b_i)^2)$
  * @param stick - S' from the protocol definition: 
- *                $S' := E_A(sum r_i^2)$
+ *                $S' := E_A(\sum r_i^2)$
  * @return product as MPI, never NULL
  */
 static gcry_mpi_t
 compute_scalar_product (struct ServiceSession * session,
-                        gcry_mpi_t * kp, gcry_mpi_t * kq, gcry_mpi_t s, gcry_mpi_t stick)
+                        gcry_mpi_t * r, gcry_mpi_t * r_prime, gcry_mpi_t s, gcry_mpi_t s_prime)
 {
-  uint16_t count;
-  gcry_mpi_t divider;
+  uint32_t count;
   gcry_mpi_t t;
   gcry_mpi_t u;
   gcry_mpi_t utick;
   gcry_mpi_t p;
   gcry_mpi_t ptick;
-  gcry_mpi_t product;
   gcry_mpi_t tmp;
   unsigned int i;
 
   count = session->used_element_count;
   tmp = gcry_mpi_new (KEYBITS);
+  // due to the introduced static offset S, we now also have to remove this
+  // from the E(a_pi)(+)E(-b_pi-r_pi) and E(a_qi)(+)E(-r_qi) twice each,
+  // the result is E((S + a_pi) + (S -b_pi-r_pi)) and E(S + a_qi + S - r_qi)
   for (i = 0; i < count; i++)
     {
-      decrypt_element (kp[i], kp[i], my_mu, my_lambda, my_n, my_nsquare);
-      decrypt_element (kq[i], kq[i], my_mu, my_lambda, my_n, my_nsquare);
+      decrypt_element (r[i], r[i], my_mu, my_lambda, my_n, my_nsquare);
+      gcry_mpi_sub(r[i],r[i],my_offset);
+      gcry_mpi_sub(r[i],r[i],my_offset);
+      decrypt_element (r_prime[i], r_prime[i], my_mu, my_lambda, my_n, my_nsquare);
+      gcry_mpi_sub(r_prime[i],r_prime[i],my_offset);
+      gcry_mpi_sub(r_prime[i],r_prime[i],my_offset);
     }
 
-  // calculate t = E(sum(ai))
+  // calculate t = sum(ai)
   t = compute_square_sum (session->a, count);
-  encrypt_element (t, t, NULL, my_g, my_n, my_nsquare);
 
   // calculate U
   u = gcry_mpi_new (0);
-  tmp = compute_square_sum (kp, count);
+  tmp = compute_square_sum (r, count);
   gcry_mpi_sub (u, u, tmp);
-  encrypt_element (u, u, NULL, my_g, my_n, my_nsquare);
   gcry_mpi_release (tmp);
 
   //calculate U'
   utick = gcry_mpi_new (0);
-  tmp = compute_square_sum (kq, count);
+  tmp = compute_square_sum (r_prime, count);
   gcry_mpi_sub (utick, utick, tmp);
-  encrypt_element (utick, utick, NULL, my_g, my_n, my_nsquare);
-  gcry_mpi_release (tmp);
 
   GNUNET_assert (p = gcry_mpi_new (0));
   GNUNET_assert (ptick = gcry_mpi_new (0));
 
+  // compute P
+  decrypt_element (s, s, my_mu, my_lambda, my_n, my_nsquare);
+  decrypt_element (s_prime, s_prime, my_mu, my_lambda, my_n, my_nsquare);
+  
   // compute P
   gcry_mpi_add (p, s, t);
-  //gcry_mpi_mulm (p, p, u, my_nsquare);
   gcry_mpi_add (p, p, u);
-  decrypt_element (p, p, my_mu, my_lambda, my_n, my_nsquare);
 
   // compute P'
-  gcry_mpi_add (ptick, stick, t);
-  //gcry_mpi_mulm (ptick, ptick, utick, my_nsquare);
+  gcry_mpi_add (ptick, s_prime, t);
   gcry_mpi_add (ptick, ptick, utick);
-  decrypt_element (ptick, ptick, my_mu, my_lambda, my_n, my_nsquare);
 
   gcry_mpi_release (t);
   gcry_mpi_release (u);
   gcry_mpi_release (utick);
 
   // compute product
-  GNUNET_assert (product = gcry_mpi_new (0));
-  gcry_mpi_sub (product, p, ptick);
-  gcry_mpi_release (p);
+  gcry_mpi_sub (p, p, ptick);
   gcry_mpi_release (ptick);
-  divider = gcry_mpi_set_ui (NULL, 2);
-  gcry_mpi_div (product, NULL, product, divider, 0);
+  tmp = gcry_mpi_set_ui (tmp, 2);
+  gcry_mpi_div (p, NULL, p, tmp, 0);
 
-  gcry_mpi_release (divider);
+  gcry_mpi_release (tmp);
   for (i = 0; i < count; i++)
     gcry_mpi_release (session->a[i]);
   GNUNET_free (session->a);
   session->a = NULL;
   
-  return product;
+  return p;
 }
 
 
@@ -1540,127 +1628,146 @@ prepare_client_response (void *cls,
   struct GNUNET_SCALARPRODUCT_client_response * msg;
   unsigned char * product_exported = NULL;
   size_t product_length = 0;
-  uint16_t msg_length = 0;
-  struct MessageObject * msg_obj;
-
-  GNUNET_assert (session);
+  uint32_t msg_length = 0;
+  int8_t range = -1;
+  gcry_error_t rc;
+  int sign;
   
+  session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
+
   if (session->product)
     {
-      // get representation as string
-      GNUNET_assert ( ! gcry_mpi_aprint (GCRYMPI_FMT_USG,
-                                           &product_exported,
-                                           &product_length,
-                                           session->product));
+      gcry_mpi_t value = gcry_mpi_new(0);
+      
+      sign = gcry_mpi_cmp_ui(session->product, 0);
+      // libgcrypt can not handle a print of a negative number
+      // if (a->sign) return gcry_error (GPG_ERR_INTERNAL); /* Can't handle it yet. */
+      if (0 > sign){
+          gcry_mpi_sub(value, value, session->product);
+      }
+      else if(0 < sign){
+          range = 1;
+          gcry_mpi_add(value, value, session->product);
+      }
+      else
+        range = 0;
+      
       gcry_mpi_release (session->product);
       session->product = NULL;
+      
+      // get representation as string
+      if (range
+          && (0 != (rc =  gcry_mpi_aprint (GCRYMPI_FMT_USG,
+                                             &product_exported,
+                                             &product_length,
+                                             value)))){
+        LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_mpi_scan", rc);
+        product_length = 0;
+        range = -1; // signal error with product-length = 0 and range = -1
+      }
+      gcry_mpi_release (value);
     }
 
-  msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) +product_length;
+  msg_length = sizeof (struct GNUNET_SCALARPRODUCT_client_response) + product_length;
   msg = GNUNET_malloc (msg_length);
-  memcpy (&msg[1], product_exported, product_length);
-  GNUNET_free_non_null (product_exported);
-  msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
-  msg->header.size = htons (msg_length);
   memcpy (&msg->key, &session->key, sizeof (struct GNUNET_HashCode));
   memcpy (&msg->peer, &session->peer, sizeof ( struct GNUNET_PeerIdentity));
+  if (product_exported != NULL){
+    memcpy (&msg[1], product_exported, product_length);
+    GNUNET_free(product_exported);
+  }
+  msg->header.type = htons (GNUNET_MESSAGE_TYPE_SCALARPRODUCT_SERVICE_TO_CLIENT);
+  msg->header.size = htons (msg_length);
+  msg->range = range;
   msg->product_length = htonl (product_length);
   
-  msg_obj = GNUNET_malloc (sizeof (struct MessageObject));
-  msg_obj->msg = (struct GNUNET_MessageHeader *) msg;
-  msg_obj->transmit_handle = NULL; // don't reset the transmit handle
-
+  session->msg = (struct GNUNET_MessageHeader *) msg;
   //transmit this message to our client
-  session->client_transmit_handle =
+  session->client_transmit_handle = 
           GNUNET_SERVER_notify_transmit_ready (session->client,
                                                msg_length,
                                                GNUNET_TIME_UNIT_FOREVER_REL,
                                                &do_send_message,
-                                               msg_obj);
-  if ( ! session->client_transmit_handle)
+                                               session);
+  if ( NULL == session->client_transmit_handle)
     {
-      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);
+      GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
+                 _ ("Could not send message to client (%p)!\n"), 
+                 session->client);
       session->client = NULL;
       // callback was not called!
-      GNUNET_free (msg_obj);
       GNUNET_free (msg);
+      session->msg = NULL;
     }
   else
       // gracefully sent message, just terminate session structure
-      GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Sent result to client (%p), this session (%s) has ended!\n"), session->client, GNUNET_h2s (&session->key));
-  free_session (session);
+      GNUNET_log (GNUNET_ERROR_TYPE_INFO, 
+                 _ ("Sent result to client (%p), this session (%s) has ended!\n"), 
+                 session->client, 
+                 GNUNET_h2s (&session->key));
 }
 
 
 /**
  * Handle a request from another service to calculate a scalarproduct with us.
  *
- * @param cls closure (set from GNUNET_MESH_connect)
+ * @param cls closure (set from #GNUNET_MESH_connect)
  * @param tunnel connection to the other end
  * @param tunnel_ctx place to store local state associated with the tunnel
  * @param sender who sent the message
  * @param message the actual message
  * @param atsi performance data for the connection
- * @return GNUNET_OK to keep the connection open,
- *         GNUNET_SYSERR to close it (signal serious error)
+ * @return #GNUNET_OK to keep the connection open,
+ *         #GNUNET_SYSERR to close it (signal serious error)
  */
 static int
 handle_service_request (void *cls,
                         struct GNUNET_MESH_Tunnel * tunnel,
                         void **tunnel_ctx,
-                        const struct GNUNET_PeerIdentity * sender,
-                        const struct GNUNET_MessageHeader * message,
-                        const struct GNUNET_ATS_Information * atsi)
+                        const struct GNUNET_MessageHeader * message)
 {
   struct ServiceSession * session;
-  struct GNUNET_SCALARPRODUCT_service_request * msg = (struct GNUNET_SCALARPRODUCT_service_request *) message;
-  uint16_t mask_length;
-  uint16_t pk_length;
-  uint16_t used_elements;
-  uint16_t element_count;
-  uint16_t msg_length;
+  const struct GNUNET_SCALARPRODUCT_service_request * msg = (const struct GNUNET_SCALARPRODUCT_service_request *) message;
+  uint32_t mask_length;
+  uint32_t pk_length;
+  uint32_t used_elements;
+  uint32_t element_count;
+  uint32_t msg_length;
   unsigned char * current;
   struct ServiceSession * responder_session;
   int32_t i = -1;
   enum SessionState needed_state;
 
-  GNUNET_assert (NULL != message);
-  GNUNET_assert (NULL != sender);
-  GNUNET_assert (NULL != tunnel_ctx);
   session = (struct ServiceSession *) * tunnel_ctx;
+  if (BOB != session->role){
+    GNUNET_break_op(0);
+    return GNUNET_SYSERR;
+  }
   // is this tunnel already in use?
   if ( (session->next) || (from_service_head == session))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Got a service request over a tunnel that is already in use, ignoring!\n"));
+      GNUNET_break_op(0);
       return GNUNET_SYSERR;
     }
   // Check if message was sent by me, which would be bad!
-  if ( ! memcmp (sender, &me, sizeof (struct GNUNET_PeerIdentity)))
+  if ( ! memcmp (&session->peer, &me, sizeof (struct GNUNET_PeerIdentity)))
     {
-      GNUNET_break (0);
       GNUNET_free (session);
-      return GNUNET_SYSERR;
-    }
-  // this protocol can at best be 1:N, but never M:N!
-  // Check if the sender is not the peer, I am connected to, which would be bad!
-  if (memcmp (sender, &session->peer, sizeof (struct GNUNET_PeerIdentity)))
-    {
       GNUNET_break (0);
-      GNUNET_free (session);
       return GNUNET_SYSERR;
     }
 
   //we need at least a peer and one message id to compare
   if (ntohs (msg->header.size) < sizeof (struct GNUNET_SCALARPRODUCT_service_request))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from peer!\n"));
       GNUNET_free (session);
+      GNUNET_break_op(0);
       return GNUNET_SYSERR;
     }
-  mask_length = ntohs (msg->mask_length);
-  pk_length = ntohs (msg->pk_length);
-  used_elements = ntohs (msg->used_element_count);
-  element_count = ntohs (msg->element_count);
+  mask_length = ntohl (msg->mask_length);
+  pk_length = ntohl (msg->pk_length);
+  used_elements = ntohl (msg->used_element_count);
+  element_count = ntohl (msg->element_count);
   msg_length = sizeof (struct GNUNET_SCALARPRODUCT_service_request)
                + mask_length + pk_length + used_elements * PAILLIER_ELEMENT_LENGTH;
 
@@ -1669,25 +1776,24 @@ handle_service_request (void *cls,
       || (used_elements == 0) || (mask_length != (element_count / 8 + (element_count % 8 ? 1 : 0)))
       )
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from peer, message count does not match message length!\n"));
-      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)));
       GNUNET_free (session);
+      GNUNET_break_op(0);
       return GNUNET_SYSERR;
     }
   if (find_matching_session (from_service_tail,
                              &msg->key,
                              element_count,
                              NULL,
-                             sender))
+                             NULL))
     {
       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Got message with duplicate session key (`%s'), ignoring service request.\n"), (const char *) &(msg->key));
       GNUNET_free (session);
       return GNUNET_SYSERR;
     }
   
-  memcpy (&session->peer, sender, sizeof (struct GNUNET_PeerIdentity));
-  session->state = REQUEST_FROM_SERVICE_RECEIVED;
-  session->element_count = ntohs (msg->element_count);
+  memcpy (&session->peer, &session->peer, sizeof (struct GNUNET_PeerIdentity));
+  session->state = SERVICE_REQUEST_RECEIVED;
+  session->element_count = ntohl (msg->element_count);
   session->used_element_count = used_elements;
   session->tunnel = tunnel;
 
@@ -1712,7 +1818,7 @@ handle_service_request (void *cls,
   current += pk_length;
 
   //check if service queue contains a matching request 
-  needed_state = MESSAGE_FROM_RESPONDING_CLIENT_RECEIVED;
+  needed_state = CLIENT_RESPONSE_RECEIVED;
   responder_session = find_matching_session (from_client_tail,
                                              &session->key,
                                              session->element_count,
@@ -1737,7 +1843,7 @@ handle_service_request (void *cls,
                                &current[i * PAILLIER_ELEMENT_LENGTH],
                                PAILLIER_ELEMENT_LENGTH,
                                &read);
-          if (ret) // read < GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH
+          if (ret)
             {
               GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate E[a%d] to MPI!\n%s/%s\n"),
                           i, gcry_strsource (ret), gcry_strerror (ret));
@@ -1757,6 +1863,7 @@ handle_service_request (void *cls,
         }
       else
           GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Got session with key %s without a matching element set, queueing.\n"), GNUNET_h2s (&session->key));
+      
       return GNUNET_OK;
     }
   else
@@ -1776,13 +1883,10 @@ except:
   free_session (session);
   // and notify our client-session that we could not complete the session
   if (responder_session)
-    {
       // we just found the responder session in this queue
-      GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, responder_session);
-      GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                    &prepare_client_end_notification,
-                                    responder_session);
-    }
+      responder_session->client_notification_task = 
+              GNUNET_SCHEDULER_add_now (&prepare_client_end_notification,
+                                        responder_session);
   return GNUNET_SYSERR;
 }
 
@@ -1790,144 +1894,136 @@ except:
 /**
  * Handle a response we got from another service we wanted to calculate a scalarproduct with.
  *
- * @param cls closure (set from GNUNET_MESH_connect)
+ * @param cls closure (set from #GNUNET_MESH_connect)
  * @param tunnel connection to the other end
  * @param tunnel_ctx place to store local state associated with the tunnel
  * @param sender who sent the message
  * @param message the actual message
  * @param atsi performance data for the connection
- * @return GNUNET_OK to keep the connection open,
- *         GNUNET_SYSERR to close it (signal serious error)
+ * @return #GNUNET_OK to keep the connection open,
+ *         #GNUNET_SYSERR to close it (we are done)
  */
 static int
 handle_service_response (void *cls,
                          struct GNUNET_MESH_Tunnel * tunnel,
                          void **tunnel_ctx,
-                         const struct GNUNET_PeerIdentity * sender,
-                         const struct GNUNET_MessageHeader * message,
-                         const struct GNUNET_ATS_Information * atsi)
+                         const struct GNUNET_MessageHeader * message)
 {
-
   struct ServiceSession * session;
-  struct GNUNET_SCALARPRODUCT_service_response * msg = (struct GNUNET_SCALARPRODUCT_service_response *) message;
+  const struct GNUNET_SCALARPRODUCT_service_response * msg = (const struct GNUNET_SCALARPRODUCT_service_response *) message;
   unsigned char * current;
-  uint16_t count;
+  uint32_t count;
   gcry_mpi_t s = NULL;
-  gcry_mpi_t stick = NULL;
+  gcry_mpi_t s_prime = NULL;
   size_t read;
   size_t i;
-  uint16_t used_element_count;
+  uint32_t used_element_count;
   size_t msg_size;
-  gcry_mpi_t * kp = NULL;
-  gcry_mpi_t * kq = NULL;
+  gcry_mpi_t * r = NULL;
+  gcry_mpi_t * r_prime = NULL;
+  int rc;
 
   GNUNET_assert (NULL != message);
-  GNUNET_assert (NULL != sender);
-  GNUNET_assert (NULL != tunnel_ctx);
   session = (struct ServiceSession *) * tunnel_ctx;
-  GNUNET_assert (NULL != session);
+  if (ALICE != session->role){
+    GNUNET_break_op(0);
+    return GNUNET_SYSERR;
+  }
+  
   count = session->used_element_count;
   session->product = NULL;
+  session->state = SERVICE_RESPONSE_RECEIVED;
 
-  if (memcmp (&session->peer, sender, sizeof (struct GNUNET_PeerIdentity)))
-    {
-      GNUNET_break_op (0);
-      goto invalid_msg;
-    }
   //we need at least a peer and one message id to compare
   if (sizeof (struct GNUNET_SCALARPRODUCT_service_response) > ntohs (msg->header.size))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Too short message received from peer!\n"));
+      GNUNET_break_op (0);
       goto invalid_msg;
     }
-  used_element_count = ntohs (msg->used_element_count);
+  used_element_count = ntohl (msg->used_element_count);
   msg_size = sizeof (struct GNUNET_SCALARPRODUCT_service_response)
           + 2 * used_element_count * PAILLIER_ELEMENT_LENGTH
           + 2 * PAILLIER_ELEMENT_LENGTH;
   //sanity check: is the message as long as the message_count fields suggests?
   if ((ntohs (msg->header.size) != msg_size) || (count != used_element_count))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Invalid message received from peer!\n"));
-      goto invalid_msg;
-    }
-  if (GNUNET_SERVER_MAX_MESSAGE_SIZE < msg_size)
-    {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Message too large, fragmentation is currently not supported!\n"));
+      GNUNET_break_op (0);
       goto invalid_msg;
     }
 
   //convert s
   current = (unsigned char *) &msg[1];
-  if (gcry_mpi_scan (&s, GCRYMPI_FMT_USG, current, 
-                     PAILLIER_ELEMENT_LENGTH, &read))
+  if (0 != (rc = gcry_mpi_scan (&s, GCRYMPI_FMT_USG, current, 
+                     PAILLIER_ELEMENT_LENGTH, &read)))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate s to an MPI value!\n"));
+      LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
+      GNUNET_break_op (0);
       goto invalid_msg;
     }
   current += PAILLIER_ELEMENT_LENGTH;
   //convert stick
-  if (gcry_mpi_scan (&stick, GCRYMPI_FMT_USG, current,
-                       PAILLIER_ELEMENT_LENGTH, &read))
+  if (0 != (rc = gcry_mpi_scan (&s_prime, GCRYMPI_FMT_USG, current,
+                       PAILLIER_ELEMENT_LENGTH, &read)))
     {
-      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate s' to an MPI value!\n"));
+      LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
+      GNUNET_break_op (0);
       goto invalid_msg;
     }
   current += PAILLIER_ELEMENT_LENGTH;
 
-  kp = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
+  r = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
   // Convert each kp[] to its MPI_value
   for (i = 0; i < count; i++)
     {
-      if (gcry_mpi_scan (&kp[i], GCRYMPI_FMT_USG, current,
-                           PAILLIER_ELEMENT_LENGTH, &read))
+      if (0 != (rc = gcry_mpi_scan (&r[i], GCRYMPI_FMT_USG, current,
+                           PAILLIER_ELEMENT_LENGTH, &read)))
         {
-          GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate Kp[%d]to an MPI value!\n"), i);
+          LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
+          GNUNET_break_op (0);
           goto invalid_msg;
         }
       current += PAILLIER_ELEMENT_LENGTH;
     }
 
 
-  kq = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
+  r_prime = GNUNET_malloc (sizeof (gcry_mpi_t) * count);
   // Convert each kq[] to its MPI_value
   for (i = 0; i < count; i++)
     {
-      if (gcry_mpi_scan (&kq[i], GCRYMPI_FMT_USG, current,
-                           PAILLIER_ELEMENT_LENGTH, &read))
+      if (0 != (rc = gcry_mpi_scan (&r_prime[i], GCRYMPI_FMT_USG, current,
+                           PAILLIER_ELEMENT_LENGTH, &read)))
         {
-          GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Could not translate Kq[%d]to an MPI value!\n"), i);
+          LOG_GCRY (GNUNET_ERROR_TYPE_DEBUG, "gcry_mpi_scan", rc);
+          GNUNET_break_op (0);
           goto invalid_msg;
         }
       current += PAILLIER_ELEMENT_LENGTH;
     }
-  
-  session->product = compute_scalar_product (session, kp, kq, s, stick);
+  session->product = compute_scalar_product (session, r, r_prime, s, s_prime);
   
 invalid_msg:
   if (s)
     gcry_mpi_release (s);
-  if (stick)
-    gcry_mpi_release (stick);
-  for (i = 0; kp && i < count; i++)
-    if (kp[i]) gcry_mpi_release (kp[i]);
-  for (i = 0; kq && i < count; i++)
-    if (kq[i]) gcry_mpi_release (kq[i]);
-  GNUNET_free_non_null (kp);
-  GNUNET_free_non_null (kq);
+  if (s_prime)
+    gcry_mpi_release (s_prime);
+  for (i = 0; r && i < count; i++)
+    if (r[i]) gcry_mpi_release (r[i]);
+  for (i = 0; r_prime && i < count; i++)
+    if (r_prime[i]) gcry_mpi_release (r_prime[i]);
+  GNUNET_free_non_null (r);
+  GNUNET_free_non_null (r_prime);
   
-  session->state = FINALIZED;
+  session->tunnel = NULL;
+  // send message with product to client
+  session->client_notification_task = 
+             GNUNET_SCHEDULER_add_now (&prepare_client_response, 
+                                        session);
   // the tunnel has done its job, terminate our connection and the tunnel
   // the peer will be notified that the tunnel was destroyed via tunnel_destruction_handler
-  GNUNET_CONTAINER_DLL_remove (from_client_head, from_client_tail, session);
-  GNUNET_SCHEDULER_add_now (&destroy_tunnel, session);
-  // send message with product to client
-  GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS,
-                                &prepare_client_response, session);
-  return GNUNET_OK;
-  // if success: terminate the session gracefully, else terminate with error
+  // just close the connection, as recommended by Christian
+  return GNUNET_SYSERR;
 }
 
-
 /**
  * Task run during shutdown.
  *
@@ -1938,29 +2034,30 @@ static void
 shutdown_task (void *cls,
                const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
-  struct ServiceSession * curr;
-  struct ServiceSession * next;
+  struct ServiceSession * session;
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Shutting down, initiating cleanup.\n"));
 
   do_shutdown = GNUNET_YES;
+
   // terminate all owned open tunnels.
-  for (curr = from_client_head; NULL != curr; curr = next)
+  for (session = from_client_head; NULL != session; session = session->next)
+  {
+    if (FINALIZED != session->state)
+      GNUNET_MESH_tunnel_destroy (session->tunnel);
+    if (GNUNET_SCHEDULER_NO_TASK != session->client_notification_task)
     {
-      next = curr->next;
-      if (FINALIZED != curr->state)
-        {
-          destroy_tunnel (curr, NULL);
-          curr->state = FINALIZED;
-        }
+      GNUNET_SCHEDULER_cancel (session->client_notification_task);
+      session->client_notification_task = GNUNET_SCHEDULER_NO_TASK;
     }
-
-  if (my_core)
+    if (GNUNET_SCHEDULER_NO_TASK != session->service_request_task)
     {
-      GNUNET_CORE_disconnect (my_core);
-      my_core = NULL;
+      GNUNET_SCHEDULER_cancel (session->service_request_task);
+      session->service_request_task = GNUNET_SCHEDULER_NO_TASK;
     }
+  }
+  for (session = from_service_head; NULL != session; session = session->next)
 
-  if (my_mesh)
+    if (my_mesh)
     {
       GNUNET_MESH_disconnect (my_mesh);
       my_mesh = NULL;
@@ -1968,22 +2065,6 @@ shutdown_task (void *cls,
 }
 
 
-/**
- * To be called on core init/fail.
- *
- * @param cls closure, NULL
- * @param server handle to the server for this service
- * @param my_identity the public identity of this peer
- */
-static void
-core_init (void *cls, struct GNUNET_CORE_Handle *server,
-           const struct GNUNET_PeerIdentity *my_identity)
-{
-  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, _ ("Core initialized\n"));
-  me = *my_identity;
-}
-
-
 /**
  * Initialization of the program and message handlers
  *
@@ -2006,34 +2087,25 @@ run (void *cls,
     { &handle_service_response, GNUNET_MESSAGE_TYPE_SCALARPRODUCT_BOB_TO_ALICE, 0},
     {NULL, 0, 0}
   };
-  static const struct GNUNET_CORE_MessageHandler core_handlers[] = {
-    {NULL, 0, 0}
-  };
-  static GNUNET_MESH_ApplicationType mesh_types[] = {
+  static const uint32_t ports[] = {
     GNUNET_APPLICATION_TYPE_SCALARPRODUCT,
-    GNUNET_APPLICATION_TYPE_END
+    0
   };
-
   //generate private/public key set
-  GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating rsa-key.\n"));
+  GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("Generating Paillier-Keyset.\n"));
   generate_keyset ();
   // register server callbacks and disconnect handler
   GNUNET_SERVER_add_handlers (server, server_handlers);
   GNUNET_SERVER_disconnect_notify (server,
                                    &handle_client_disconnect,
                                    NULL);
-
-  my_core = GNUNET_CORE_connect (c, NULL, &core_init, NULL, NULL, NULL,
-                                 GNUNET_NO, NULL, GNUNET_NO, core_handlers);
-  if (!my_core)
-    {
-      GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to CORE failed\n"));
-      return;
-    }
+  GNUNET_break (GNUNET_OK ==
+               GNUNET_CRYPTO_get_host_identity (c,
+                                                &me));
   my_mesh = GNUNET_MESH_connect (c, NULL,
                                  &tunnel_incoming_handler,
                                  &tunnel_destruction_handler,
-                                 mesh_handlers, mesh_types);
+                                 mesh_handlers, ports);
   if (!my_mesh)
     {
       GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Connect to MESH failed\n"));