-fix build issues
[oweals/gnunet.git] / src / secretsharing / gnunet-service-secretsharing.c
index 38dabc3a8ade234abc30f59fc6b65e15fd01cf34..1778b6ca0363f171ea391f407beae9098bfe86bb 100644 (file)
@@ -33,6 +33,9 @@
 #include <gcrypt.h>
 
 
+#define EXTRA_CHECKS 1
+
+
 /**
  * Info about a peer in a key generation session.
  */
@@ -45,8 +48,9 @@ struct KeygenPeerInfo
 
   /**
    * The peer's paillier public key.
+   * Freshly generated for each keygen session.
    */
-  gcry_mpi_t paillier_n;
+  struct GNUNET_CRYPTO_PaillierPublicKey paillier_public_key;
 
   /**
    * The peer's commitment to his presecret.
@@ -54,15 +58,15 @@ struct KeygenPeerInfo
   gcry_mpi_t presecret_commitment;
 
   /**
-   * The peer's preshare that we decrypted
-   * with out private key.
+   * Commitment to the preshare that is
+   * intended for our peer.
    */
-  gcry_mpi_t decrypted_preshare;
+  gcry_mpi_t preshare_commitment;
 
   /**
-   * Multiplicative share of the public key.
+   * Sigma (exponentiated share) for this peer.
    */
-  gcry_mpi_t public_key_share;
+  gcry_mpi_t sigma;
 
   /**
    * Did we successfully receive the round1 element
@@ -92,7 +96,7 @@ struct DecryptPeerInfo
    * Original index in the key generation round.
    * Necessary for computing the lagrange coefficients.
    */
-  unsigned int real_index;
+  unsigned int original_index;
 
   /**
    * Set to the partial decryption of
@@ -180,14 +184,9 @@ struct KeygenSession
   struct GNUNET_HashCode session_id;
 
   /**
-   * lambda-component of our peer's paillier private key.
-   */
-  gcry_mpi_t paillier_lambda;
-
-  /**
-   * mu-component of our peer's paillier private key.
+   * Paillier private key of our peer.
    */
-  gcry_mpi_t paillier_mu;
+  struct GNUNET_CRYPTO_PaillierPrivateKey paillier_private_key;
 
   /**
    * When would we like the key to be established?
@@ -205,6 +204,17 @@ struct KeygenSession
    * of peers in the session.
    */
   unsigned int local_peer_idx;
+
+  /**
+   * Share of our peer.  Once preshares from other peers are received, they
+   * will be added to 'my'share.
+   */
+  gcry_mpi_t my_share;
+
+  /**
+   * Public key, will be updated when a round2 element arrives.
+   */
+  gcry_mpi_t public_key;
 };
 
 
@@ -238,6 +248,11 @@ struct DecryptSession
    */
   struct GNUNET_MQ_Handle *client_mq;
 
+  /**
+   * When should we start communicating for decryption?
+   */
+  struct GNUNET_TIME_Absolute start;
+
   /**
    * When would we like the ciphertext to be
    * decrypted?
@@ -322,53 +337,12 @@ static const struct GNUNET_CONFIGURATION_Handle *cfg;
 static struct GNUNET_SERVER_Handle *srv;
 
 
-/**
- * If target != size, move @a target bytes to the end of the size-sized
- * buffer and zero out the first @a target - @a size bytes.
- *
- * @param buf original buffer
- * @param size number of bytes in @a buf
- * @param target target size of the buffer
- */
-static void
-adjust (unsigned char *buf,
-       size_t size,
-       size_t target)
-{
-  if (size < target)
-  {
-    memmove (&buf[target - size], buf, size);
-    memset (buf, 0, target - size);
-  }
-}
-
-
-/**
- * Print an MPI to a buffer, so that is contains the MPI's
- * the little endian representation of size @a size.
- *
- * @param buf buffer to write to
- * @param x mpi to be written in the buffer
- * @param size how many bytes should the little endian binary
- *             representation of @a x use?
- */
-static void
-print_mpi_fixed (void *buf, gcry_mpi_t x, size_t size)
-{
-  size_t written;
-  GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
-                                      buf, size, &written,
-                                      x));
-  adjust (buf, written, size);
-}
-
-
 /**
  * Get the peer info belonging to a peer identity in a keygen session.
  *
- * @param ks the keygen session
- * @param peer the peer identity
- * @return the keygen peer info, or NULL if the peer could not be found
+ * @param ks The keygen session.
+ * @param peer The peer identity.
+ * @return The Keygen peer info, or NULL if the peer could not be found.
  */
 static struct KeygenPeerInfo *
 get_keygen_peer_info (const struct KeygenSession *ks,
@@ -385,13 +359,13 @@ get_keygen_peer_info (const struct KeygenSession *ks,
 /**
  * Get the peer info belonging to a peer identity in a decrypt session.
  *
- * @param ks the decrypt session
- * @param peer the peer identity
- * @return the decrypt peer info, or NULL if the peer could not be found
+ * @param ds The decrypt session.
+ * @param peer The peer identity.
+ * @return The decrypt peer info, or NULL if the peer could not be found.
  */
 static struct DecryptPeerInfo *
 get_decrypt_peer_info (const struct DecryptSession *ds,
-                      const struct GNUNET_PeerIdentity *peer)
+                       const struct GNUNET_PeerIdentity *peer)
 {
   unsigned int i;
   for (i = 0; i < ds->share->num_peers; i++)
@@ -428,8 +402,8 @@ time_between (struct GNUNET_TIME_Absolute start,
 /**
  * Compare two peer identities.  Indended to be used with qsort or bsearch.
  *
- * @param p1 some peer identity
- * @param p2 some peer identity
+ * @param p1 Some peer identity.
+ * @param p2 Some peer identity.
  * @return 1 if p1 > p2, -1 if p1 < p2 and 0 if p1 == p2.
  */
 static int
@@ -442,10 +416,10 @@ peer_id_cmp (const void *p1, const void *p2)
 /**
  * Get the index of a peer in an array of peers
  *
- * @param haystack array of peers
- * @param n size of @a haystack
- * @param needle peer to find
- * @return index of @a needle in @a haystack, or -1 if peer
+ * @param haystack Array of peers.
+ * @param n Size of @a haystack.
+ * @param needle Peer to find
+ * @return Index of @a needle in @a haystack, or -1 if peer
  *         is not in the list.
  */
 static int
@@ -464,11 +438,11 @@ peer_find (const struct GNUNET_PeerIdentity *haystack, unsigned int n,
  * Normalize the given list of peers, by including the local peer
  * (if it is missing) and sorting the peers by their identity.
  *
- * @param listed peers in the unnormalized list
- * @param num_listed peers in the un-normalized list
- * @param[out] num_normalized number of peers in the normalized list
- * @param[out] my_peer_idx index of the local peer in the normalized list
- * @return normalized list, must be free'd by the caller
+ * @param listed Peers in the unnormalized list.
+ * @param num_listed Peers in the un-normalized list.
+ * @param[out] num_normalized Number of peers in the normalized list.
+ * @param[out] my_peer_idx Index of the local peer in the normalized list.
+ * @return Normalized list, must be free'd by the caller.
  */
 static struct GNUNET_PeerIdentity *
 normalize_peers (struct GNUNET_PeerIdentity *listed,
@@ -477,6 +451,7 @@ normalize_peers (struct GNUNET_PeerIdentity *listed,
                  unsigned int *my_peer_idx)
 {
   unsigned int local_peer_in_list;
+  /* number of peers in the normalized list */
   unsigned int n;
   struct GNUNET_PeerIdentity *normalized;
 
@@ -506,10 +481,10 @@ normalize_peers (struct GNUNET_PeerIdentity *listed,
 
 
 /**
- * Get a the j-th lagrage coefficient for a set of indices.
+ * Get a the j-th lagrange coefficient for a set of indices.
  *
  * @param[out] coeff the lagrange coefficient
- * @param j lagrage coefficient we want to compute
+ * @param j lagrange coefficient we want to compute
  * @param indices indices
  * @param num number of indices in @a indices
  */
@@ -518,7 +493,7 @@ compute_lagrange_coefficient (gcry_mpi_t coeff, unsigned int j,
                               unsigned int *indices,
                               unsigned int num)
 {
-  int i;
+  unsigned int i;
   /* numerator */
   gcry_mpi_t n;
   /* denominator */
@@ -535,22 +510,27 @@ compute_lagrange_coefficient (gcry_mpi_t coeff, unsigned int j,
   gcry_mpi_set_ui (n, 1);
   gcry_mpi_set_ui (d, 1);
 
-  gcry_mpi_set_ui (coeff, 0);
   for (i = 0; i < num; i++)
   {
-    int l = indices[i];
+    unsigned int l = indices[i];
     if (l == j)
       continue;
-    gcry_mpi_mul_ui (n, n, l);
+    gcry_mpi_mul_ui (n, n, l + 1);
     // d <- d * (l-j)
-    gcry_mpi_set_ui (tmp, l);
-    gcry_mpi_sub_ui (tmp, tmp, j);
+    gcry_mpi_set_ui (tmp, l + 1);
+    gcry_mpi_sub_ui (tmp, tmp, j + 1);
     gcry_mpi_mul (d, d, tmp);
   }
 
+  // gcry_mpi_invm does not like negative numbers ...
+  gcry_mpi_mod (d, d, elgamal_q);
+
+  GNUNET_assert (gcry_mpi_cmp_ui (d, 0) > 0);
+
   // now we do the actual division, with everything mod q, as we
-  // are not operating on elemets from <g>, but on exponents
-  GNUNET_assert (0 == gcry_mpi_invm (d, d, elgamal_q));
+  // are not operating on elements from <g>, but on exponents
+  GNUNET_assert (0 != gcry_mpi_invm (d, d, elgamal_q));
+
   gcry_mpi_mulm (coeff, n, d, elgamal_q);
 
   gcry_mpi_release (n);
@@ -559,107 +539,51 @@ compute_lagrange_coefficient (gcry_mpi_t coeff, unsigned int j,
 }
 
 
-/**
- * Create a key pair for the paillier crypto system.
- *
- * Uses the simplified key generation of Jonathan Katz, Yehuda Lindell,
- * "Introduction to Modern Cryptography: Principles and Protocols".
- *
- * @param n n-component of public key
- * @param lambda lambda-component of private key
- * @param mu mu-componenent of private key
- */
 static void
-paillier_create (gcry_mpi_t n, gcry_mpi_t lambda, gcry_mpi_t mu)
+decrypt_session_destroy (struct DecryptSession *ds)
 {
-  gcry_mpi_t p;
-  gcry_mpi_t q;
-  gcry_mpi_t phi;
-  gcry_mpi_t tmp;
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying decrypt session\n");
 
-  GNUNET_assert (0 != (phi = gcry_mpi_new (PAILLIER_BITS)));
-  GNUNET_assert (0 != (tmp = gcry_mpi_new (PAILLIER_BITS)));
-
-  // generate rsa modulus
-  GNUNET_assert (0 == gcry_prime_generate (&p, PAILLIER_BITS / 2, 0, NULL, NULL, NULL,
-                                           GCRY_WEAK_RANDOM, 0));
-  GNUNET_assert (0 == gcry_prime_generate (&q, PAILLIER_BITS / 2, 0, NULL, NULL, NULL,
-                                           GCRY_WEAK_RANDOM, 0));
-  gcry_mpi_mul (n, p, q);
-  // compute phi(n) = (p-1)(q-1)
-  gcry_mpi_sub_ui (phi, p, 1);
-  gcry_mpi_sub_ui (tmp, q, 1);
-  gcry_mpi_mul (phi, phi, tmp);
-  gcry_mpi_set (lambda, phi);
-  // compute mu
-  GNUNET_assert (0 != gcry_mpi_invm (mu, phi, n));
-
-  gcry_mpi_release (p);
-  gcry_mpi_release (q);
-  gcry_mpi_release (phi);
-  gcry_mpi_release (tmp);
+  GNUNET_CONTAINER_DLL_remove (decrypt_sessions_head, decrypt_sessions_tail, ds);
+
+  if (NULL != ds->client_mq)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying decrypt MQ\n");
+    GNUNET_MQ_destroy (ds->client_mq);
+    ds->client_mq = NULL;
+  }
+
+  if (NULL != ds->client)
+  {
+    GNUNET_SERVER_client_disconnect (ds->client);
+    ds->client = NULL;
+  }
+
+  GNUNET_free (ds);
 }
 
 
-/**
- * Encrypt a value using Paillier's scheme.
- *
- * @param c resulting ciphertext
- * @param m plaintext to encrypt
- * @param n n-component of public key
- */
 static void
-paillier_encrypt (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t n)
+keygen_session_destroy (struct KeygenSession *ks)
 {
-  gcry_mpi_t n_square;
-  gcry_mpi_t r;
-  gcry_mpi_t g;
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying keygen session\n");
 
-  GNUNET_assert (0 != (n_square = gcry_mpi_new (0)));
-  GNUNET_assert (0 != (r = gcry_mpi_new (0)));
-  GNUNET_assert (0 != (g = gcry_mpi_new (0)));
+  GNUNET_CONTAINER_DLL_remove (keygen_sessions_head, keygen_sessions_tail, ks);
 
-  gcry_mpi_add_ui (g, n, 1);
-
-  gcry_mpi_mul (n_square, n, n);
-
-  // generate r < n
-  do
+  if (NULL != ks->client_mq)
   {
-    gcry_mpi_randomize (r, PAILLIER_BITS, GCRY_WEAK_RANDOM);
+    GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying keygen MQ\n");
+    GNUNET_MQ_destroy (ks->client_mq);
+    ks->client_mq = NULL;
   }
-  while (gcry_mpi_cmp (r, n) > 0);
-
-  gcry_mpi_powm (c, g, m, n_square);
-  gcry_mpi_powm (r, r, n, n_square);
-  gcry_mpi_mulm (c, r, c, n_square);
-
-  gcry_mpi_release (n_square);
-  gcry_mpi_release (r);
-}
 
+  if (NULL != ks->client)
+  {
+    GNUNET_SERVER_client_disconnect (ks->client);
+    ks->client = NULL;
+  }
 
-/**
- * Decrypt a ciphertext using Paillier's scheme.
- *
- * @param[out] m resulting plaintext
- * @param c ciphertext to decrypt
- * @param lambda lambda-component of private key
- * @param mu mu-component of private key
- * @param n n-component of public key
- */
-static void
-paillier_decrypt (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;
-  GNUNET_assert (0 != (n_square = gcry_mpi_new (0)));
-  gcry_mpi_mul (n_square, n, n);
-  gcry_mpi_powm (m, c, lambda, n_square);
-  gcry_mpi_sub_ui (m, m, 1);
-  // m = m/n
-  gcry_mpi_div (m, NULL, m, n, 0);
-  gcry_mpi_mulm (m, m, mu, n);
-  gcry_mpi_release (n_square);
+  GNUNET_free (ks);
 }
 
 
@@ -672,10 +596,15 @@ paillier_decrypt (gcry_mpi_t m, gcry_mpi_t c, gcry_mpi_t mu, gcry_mpi_t lambda,
 static void
 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
 {
-  /* FIXME: do clean up here */
+  while (NULL != decrypt_sessions_head)
+    decrypt_session_destroy (decrypt_sessions_head);
+
+  while (NULL != keygen_sessions_head)
+    keygen_session_destroy (keygen_sessions_head);
 }
 
 
+
 /**
  * Generate the random coefficients of our pre-secret polynomial
  *
@@ -685,23 +614,31 @@ static void
 generate_presecret_polynomial (struct KeygenSession *ks)
 {
   int i;
+  gcry_mpi_t v;
+
   GNUNET_assert (NULL == ks->presecret_polynomial);
-  ks->presecret_polynomial = GNUNET_malloc (ks->threshold * sizeof (gcry_mpi_t));
+  ks->presecret_polynomial = GNUNET_new_array (ks->threshold, gcry_mpi_t);
   for (i = 0; i < ks->threshold; i++)
   {
-    ks->presecret_polynomial[i] = gcry_mpi_new (GNUNET_SECRETSHARING_KEY_BITS);
-    GNUNET_assert (0 != ks->presecret_polynomial[i]);
-    gcry_mpi_randomize (ks->presecret_polynomial[i], GNUNET_SECRETSHARING_KEY_BITS,
-                        GCRY_WEAK_RANDOM);
+    v = ks->presecret_polynomial[i] = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS);
+    GNUNET_assert (NULL != v);
+    // Randomize v such that 0 < v < elgamal_q.
+    // The '- 1' is necessary as bitlength(q) = bitlength(p) - 1.
+    do 
+    {
+      gcry_mpi_randomize (v, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
+    } while ((gcry_mpi_cmp_ui (v, 0) == 0) || (gcry_mpi_cmp (v, elgamal_q) >= 0));
   }
 }
 
 
 /**
  * Consensus element handler for round one.
+ * We should get one ephemeral key for each peer.
  *
- * @param cls closure (keygen session)
- * @param element the element from consensus
+ * @param cls Closure (keygen session).
+ * @param element The element from consensus, or
+ *                NULL if consensus failed.
  */
 static void
 keygen_round1_new_element (void *cls,
@@ -717,6 +654,7 @@ keygen_round1_new_element (void *cls,
     return;
   }
 
+  /* elements have fixed size */
   if (element->size != sizeof (struct GNUNET_SECRETSHARING_KeygenCommitData))
   {
     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
@@ -729,7 +667,6 @@ keygen_round1_new_element (void *cls,
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round1 element\n");
 
   d = element->data;
-
   info = get_keygen_peer_info (ks, &d->peer);
 
   if (NULL == info)
@@ -739,6 +676,7 @@ keygen_round1_new_element (void *cls,
     return;
   }
 
+  /* Check that the right amount of data has been signed. */
   if (d->purpose.size !=
       htonl (element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose)))
   {
@@ -752,11 +690,8 @@ keygen_round1_new_element (void *cls,
     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with invalid signature in consensus\n");
     return;
   }
-
-  GNUNET_assert (0 == gcry_mpi_scan (&info->paillier_n, GCRYMPI_FMT_USG,
-                                     &d->pubkey.n, sizeof d->pubkey.n, NULL));
-  GNUNET_assert (0 == gcry_mpi_scan (&info->presecret_commitment, GCRYMPI_FMT_USG,
-                                     &d->commitment, sizeof d->commitment, NULL));
+  info->paillier_public_key = d->pubkey;
+  GNUNET_CRYPTO_mpi_scan_unsigned (&info->presecret_commitment, &d->commitment, 512 / 8);
   info->round1_valid = GNUNET_YES;
 }
 
@@ -796,17 +731,9 @@ keygen_round2_conclude (void *cls)
   unsigned int i;
   unsigned int j;
   struct GNUNET_SECRETSHARING_Share *share;
-  gcry_mpi_t s;
-  gcry_mpi_t h;
 
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "round2 conclude\n");
 
-  GNUNET_assert (0 != (s = gcry_mpi_new (GNUNET_SECRETSHARING_KEY_BITS)));
-  GNUNET_assert (0 != (h = gcry_mpi_new (GNUNET_SECRETSHARING_KEY_BITS)));
-
-  // multiplicative identity
-  gcry_mpi_set_ui (s, 1);
-
   share = GNUNET_new (struct GNUNET_SECRETSHARING_Share);
 
   share->num_peers = 0;
@@ -816,32 +743,52 @@ keygen_round2_conclude (void *cls)
       share->num_peers++;
 
   share->peers = GNUNET_new_array (share->num_peers, struct GNUNET_PeerIdentity);
-  share->hom_share_commitments =
+  share->sigmas =
       GNUNET_new_array (share->num_peers, struct GNUNET_SECRETSHARING_FieldElement);
   share->original_indices = GNUNET_new_array (share->num_peers, uint16_t);
 
-  j = 0;
+  /* maybe we're not even in the list of peers? */
+  share->my_peer = share->num_peers;
+
+  j = 0; /* running index of valid peers */
   for (i = 0; i < ks->num_peers; i++)
   {
     if (GNUNET_YES == ks->info[i].round2_valid)
     {
-      gcry_mpi_addm (s, s, ks->info[i].decrypted_preshare, elgamal_p);
-      gcry_mpi_mulm (h, h, ks->info[i].public_key_share, elgamal_p);
-      share->peers[i] = ks->info[i].peer;
-      share->original_indices[i] = j++;
+      share->peers[j] = ks->info[i].peer;
+      GNUNET_CRYPTO_mpi_print_unsigned (&share->sigmas[j],
+                                        GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
+                                        ks->info[i].sigma);
+      share->original_indices[i] = j;
+      if (0 == memcmp (&share->peers[i], &my_peer, sizeof (struct GNUNET_PeerIdentity)))
+        share->my_peer = j;
+      j += 1;
     }
   }
 
-  print_mpi_fixed (&share->my_share, s, GNUNET_SECRETSHARING_KEY_BITS / 8);
-  print_mpi_fixed (&share->public_key, h, GNUNET_SECRETSHARING_KEY_BITS / 8);
+  if (share->my_peer == share->num_peers)
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: peer identity not in share\n", ks->local_peer_idx);
+  }
+
+  GNUNET_CRYPTO_mpi_print_unsigned (&share->my_share, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
+                                    ks->my_share);
+  GNUNET_CRYPTO_mpi_print_unsigned (&share->public_key, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
+                                    ks->public_key);
+
+  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "keygen completed with %u peers\n", share->num_peers);
 
-  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "keygen successful with %u peers\n", share->num_peers);
+  /* Write the share. If 0 peers completed the dkg, an empty
+   * share will be sent. */
 
   m = GNUNET_malloc (sizeof (struct GNUNET_SECRETSHARING_SecretReadyMessage) +
                      ks->num_peers * sizeof (struct GNUNET_PeerIdentity));
 
   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, NULL, 0, &share_size));
 
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "writing share of size %u\n",
+              (unsigned int) share_size);
+
   ev = GNUNET_MQ_msg_extra (m, share_size,
                             GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_SECRET_READY);
 
@@ -856,8 +803,8 @@ keygen_round2_conclude (void *cls)
  * (1) The exponentiated pre-share polynomial coefficients A_{i,l}=g^{a_{i,l}}
  * (2) The exponentiated pre-shares y_{i,j}=g^{s_{i,j}}
  * (3) The encrypted pre-shares Y_{i,j}
- * (4) The zero knowledge proof for correctness of
- *    the encryption
+ * (4) The zero knowledge proof for fairness of
+ *     the encryption
  *
  * @param ks session to use
  */
@@ -872,13 +819,19 @@ insert_round2_element (struct KeygenSession *ks)
   unsigned int i;
   gcry_mpi_t idx;
   gcry_mpi_t v;
+  gcry_mpi_t c;
 
-  GNUNET_assert (0 != (v = gcry_mpi_new (GNUNET_SECRETSHARING_KEY_BITS)));
-  GNUNET_assert (0 != (idx = gcry_mpi_new (GNUNET_SECRETSHARING_KEY_BITS)));
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting round2 element\n",
+              ks->local_peer_idx);
+
+  GNUNET_assert (NULL != (v = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
+  GNUNET_assert (NULL != (idx = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
+  GNUNET_assert (NULL != (c = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
 
   element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
-                  2 * GNUNET_SECRETSHARING_KEY_BITS / 8 * ks->num_peers +
-                  1 * GNUNET_SECRETSHARING_KEY_BITS / 8 * ks->threshold);
+                  GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers +
+                  sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers +
+                  GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->threshold);
 
   element = GNUNET_malloc (sizeof (struct GNUNET_SET_Element) + element_size);
   element->size = element_size;
@@ -887,6 +840,8 @@ insert_round2_element (struct KeygenSession *ks)
   d = (void *) element->data;
   d->peer = my_peer;
 
+  // start inserting vector elements
+  // after the fixed part of the element's data
   pos = (void *) &d[1];
   last_pos = pos + element_size;
 
@@ -895,38 +850,54 @@ insert_round2_element (struct KeygenSession *ks)
   {
     ptrdiff_t remaining = last_pos - pos;
     GNUNET_assert (remaining > 0);
-    gcry_mpi_set_ui (idx, i);
+    gcry_mpi_set_ui (idx, i + 1);
     // evaluate the polynomial
-    horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_p);
+    horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_q);
     // take g to the result
     gcry_mpi_powm (v, elgamal_g, v, elgamal_p);
-    print_mpi_fixed (pos, v, GNUNET_SECRETSHARING_KEY_BITS / 8);
-    pos += GNUNET_SECRETSHARING_KEY_BITS / 8;
+    GNUNET_CRYPTO_mpi_print_unsigned (pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
+    pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8;
   }
 
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed exp preshares\n",
+              ks->local_peer_idx);
+
   // encrypted pre-shares
   for (i = 0; i < ks->num_peers; i++)
   {
     ptrdiff_t remaining = last_pos - pos;
+    struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext;
+
     GNUNET_assert (remaining > 0);
-    if (GNUNET_NO == ks->info[i].round1_valid)
-      gcry_mpi_set_ui (v, 0);
-    else
-      paillier_encrypt (v, ks->presecret_polynomial[0], ks->info[i].paillier_n);
-    print_mpi_fixed (pos, v, GNUNET_SECRETSHARING_KEY_BITS / 8);
-    pos += GNUNET_SECRETSHARING_KEY_BITS / 8;
+    ciphertext = (void *) pos;
+    memset (ciphertext, 0, sizeof *ciphertext);
+    if (GNUNET_YES == ks->info[i].round1_valid)
+    {
+      gcry_mpi_set_ui (idx, i + 1);
+      // evaluate the polynomial
+      horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_q);
+      // encrypt the result
+      GNUNET_CRYPTO_paillier_encrypt (&ks->info[i].paillier_public_key, v, 0, ciphertext);
+    }
+    pos += sizeof *ciphertext;
   }
 
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed enc preshares\n",
+              ks->local_peer_idx);
+
   // exponentiated coefficients
   for (i = 0; i < ks->threshold; i++)
   {
     ptrdiff_t remaining = last_pos - pos;
     GNUNET_assert (remaining > 0);
     gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[i], elgamal_p);
-    print_mpi_fixed (pos, v, GNUNET_SECRETSHARING_KEY_BITS / 8);
-    pos += GNUNET_SECRETSHARING_KEY_BITS / 8;
+    GNUNET_CRYPTO_mpi_print_unsigned (pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
+    pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8;
   }
 
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed exp coefficients\n",
+              ks->local_peer_idx);
+
   d->purpose.size = htonl (element_size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose));
   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2);
   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d->purpose, &d->signature);
@@ -939,6 +910,67 @@ insert_round2_element (struct KeygenSession *ks)
 }
 
 
+static gcry_mpi_t
+keygen_reveal_get_exp_preshare (struct KeygenSession *ks,
+                                const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
+                                unsigned int idx)
+{
+  unsigned char *pos;
+  gcry_mpi_t exp_preshare;
+
+  GNUNET_assert (idx < ks->num_peers);
+
+  GNUNET_assert (NULL != (exp_preshare = gcry_mpi_new (0)));
+
+  pos = (void *) &d[1];
+  // skip exponentiated pre-shares we don't want
+  pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * idx;
+  GNUNET_CRYPTO_mpi_scan_unsigned (&exp_preshare, pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
+  return exp_preshare;
+}
+
+static gcry_mpi_t
+keygen_reveal_get_exp_coeff (struct KeygenSession *ks,
+                             const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
+                             unsigned int idx)
+{
+  unsigned char *pos;
+  gcry_mpi_t exp_coeff;
+
+  GNUNET_assert (idx < ks->threshold);
+  GNUNET_assert (NULL != (exp_coeff = gcry_mpi_new (0)));
+
+  pos = (void *) &d[1];
+  // skip exponentiated pre-shares
+  pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers;
+  // skip encrypted pre-shares
+  pos += sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers;
+  // skip exp. coeffs we are not interested in
+  pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * idx;
+  // the first exponentiated coefficient is the public key share
+  GNUNET_CRYPTO_mpi_scan_unsigned (&exp_coeff, pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
+  return exp_coeff;
+}
+
+
+static struct GNUNET_CRYPTO_PaillierCiphertext *
+keygen_reveal_get_enc_preshare (struct KeygenSession *ks,
+                                const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
+                                unsigned int idx)
+{
+  unsigned char *pos;
+
+  GNUNET_assert (idx < ks->num_peers);
+
+  pos = (void *) &d[1];
+  // skip exponentiated pre-shares
+  pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers;
+  // skip encrypted pre-shares we're not interested in
+  pos += sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * idx;
+  return (struct GNUNET_CRYPTO_PaillierCiphertext *) pos;
+}
+
+
 static void
 keygen_round2_new_element (void *cls,
                            const struct GNUNET_SET_Element *element)
@@ -946,9 +978,11 @@ keygen_round2_new_element (void *cls,
   struct KeygenSession *ks = cls;
   const struct GNUNET_SECRETSHARING_KeygenRevealData *d;
   struct KeygenPeerInfo *info;
-  unsigned char *pos;
-  gcry_mpi_t c;
   size_t expected_element_size;
+  unsigned int j;
+  gcry_mpi_t tmp;
+  gcry_mpi_t public_key_share;
+  gcry_mpi_t preshare;
 
   if (NULL == element)
   {
@@ -957,8 +991,9 @@ keygen_round2_new_element (void *cls,
   }
 
   expected_element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
-                  2 * GNUNET_SECRETSHARING_KEY_BITS / 8 * ks->num_peers +
-                  1 * GNUNET_SECRETSHARING_KEY_BITS / 8 * ks->threshold);
+                  GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers +
+                  sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers +
+                  GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->threshold);
 
   if (element->size != expected_element_size)
   {
@@ -998,45 +1033,97 @@ keygen_round2_new_element (void *cls,
 
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round2 element\n");
 
+  if (ntohl (d->purpose.size) !=
+      element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with wrong signature purpose size in consensus\n");
+    return;
+  }
 
-  pos = (void *) &d[1];
-  // skip exponentiated pre-shares
-  pos += GNUNET_SECRETSHARING_KEY_BITS / 8 * ks->num_peers;
-  // skip encrypted pre-shares
-  pos += PAILLIER_BITS / 8 * ks->num_peers;
-  // the first exponentiated coefficient is the public key share
-  GNUNET_assert (0 == gcry_mpi_scan (&info->public_key_share, GCRYMPI_FMT_USG,
-                                     pos, GNUNET_SECRETSHARING_KEY_BITS / 8, NULL));
-
-  pos = (void *) &d[1];
-  // skip exp. pre-shares
-  pos += GNUNET_SECRETSHARING_KEY_BITS / 8 * ks->num_peers;
-  // skip to the encrypted value for our peer
-  pos += PAILLIER_BITS / 8 * ks->local_peer_idx;
+  if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2,
+                                               &d->purpose, &d->signature, &d->peer.public_key))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with invalid signature in consensus\n");
+    return;
+  }
 
-  GNUNET_assert (0 == gcry_mpi_scan (&c, GCRYMPI_FMT_USG,
-                                     pos, PAILLIER_BITS / 8, NULL));
+  public_key_share = keygen_reveal_get_exp_coeff (ks, d, 0);
+  info->preshare_commitment = keygen_reveal_get_exp_preshare (ks, d, ks->local_peer_idx);
 
-  GNUNET_assert (0 != (info->decrypted_preshare = mpi_new (0)));
+  if (NULL == ks->public_key)
+  {
+    GNUNET_assert (NULL != (ks->public_key = gcry_mpi_new (0)));
+    gcry_mpi_set_ui (ks->public_key, 1);
+  }
+  gcry_mpi_mulm (ks->public_key, ks->public_key, public_key_share, elgamal_p);
 
-  paillier_decrypt (info->decrypted_preshare, c, ks->paillier_lambda, ks->paillier_mu,
-                    ks->info[ks->local_peer_idx].paillier_n);
+  GNUNET_assert (NULL != (preshare = gcry_mpi_new (0)));
+  GNUNET_CRYPTO_paillier_decrypt (&ks->paillier_private_key,
+                                  &ks->info[ks->local_peer_idx].paillier_public_key,
+                                  keygen_reveal_get_enc_preshare (ks, d, ks->local_peer_idx),
+                                  preshare);
 
-  // TODO: validate zero knowledge proofs
+  GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
+  gcry_mpi_powm (tmp, elgamal_g, preshare, elgamal_p);
 
-  if (d->purpose.size !=
-      htons (element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose)))
+  // TODO: restore a valid secret from the decryption (the hard part, solving SVP with gauss)
+  if (0 != gcry_mpi_cmp (tmp, info->preshare_commitment))
   {
-    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with wrong signature purpose size in consensus\n");
+    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Got invalid presecret from P%u\n",
+                (unsigned int) ks->local_peer_idx, (unsigned int) (info - ks->info));
     return;
   }
 
-  if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2,
-                                               &d->purpose, &d->signature, &d->peer.public_key))
+  if (NULL == ks->my_share)
   {
-    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with invalid signature in consensus\n");
-    return;
+    GNUNET_assert (NULL != (ks->my_share = gcry_mpi_new (0)));
+  }
+  gcry_mpi_addm (ks->my_share, ks->my_share, preshare, elgamal_q);
+
+  for (j = 0; j < ks->num_peers; j++)
+  {
+    gcry_mpi_t presigma;
+    if (NULL == ks->info[j].sigma)
+    {
+      GNUNET_assert (NULL != (ks->info[j].sigma = gcry_mpi_new (0)));
+      gcry_mpi_set_ui (ks->info[j].sigma, 1);
+    }
+    presigma = keygen_reveal_get_exp_preshare (ks, d, j);
+    gcry_mpi_mulm (ks->info[j].sigma, ks->info[j].sigma, presigma, elgamal_p);
+  }
+
+  gcry_mpi_t prod;
+  GNUNET_assert (NULL != (prod = gcry_mpi_new (0)));
+  gcry_mpi_t j_to_k;
+  GNUNET_assert (NULL != (j_to_k = gcry_mpi_new (0)));
+  // validate that the polynomial sharing matches the additive sharing
+  for (j = 0; j < ks->num_peers; j++)
+  {
+    unsigned int k;
+    gcry_mpi_t tmp;
+    gcry_mpi_t exp_preshare;
+    gcry_mpi_set_ui (prod, 1);
+    for (k = 0; k < ks->threshold; k++)
+    {
+      // Using pow(double,double) is a bit sketchy.
+      // We count players from 1, but shares from 0.
+      gcry_mpi_set_ui (j_to_k, (unsigned int) pow(j+1, k)); 
+      tmp = keygen_reveal_get_exp_coeff (ks, d, k);
+      gcry_mpi_powm (tmp, tmp, j_to_k, elgamal_p);
+      gcry_mpi_mulm (prod, prod, tmp, elgamal_p);
+    }
+    exp_preshare = keygen_reveal_get_exp_preshare (ks, d, j);
+    gcry_mpi_mod (exp_preshare, exp_preshare, elgamal_p);
+    if (0 != gcry_mpi_cmp (prod, exp_preshare))
+    {
+      GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: reveal data from P%u incorrect\n",
+                  ks->local_peer_idx, j);
+      /* no need for further verification, round2 stays invalid ... */
+      return;
+    }
   }
+
+  // TODO: verify proof of fair encryption (once implemented)
   
   info->round2_valid = GNUNET_YES;
 }
@@ -1056,13 +1143,13 @@ keygen_round1_conclude (void *cls)
   GNUNET_CONSENSUS_destroy (ks->consensus);
 
   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &ks->session_id,
+                                           time_between (ks->start_time, ks->deadline, 1, 2),
+                                           ks->deadline,
                                            keygen_round2_new_element, ks);
 
   insert_round2_element (ks);
 
   GNUNET_CONSENSUS_conclude (ks->consensus,
-                             /* last round, thus conclude at DKG deadline */
-                             ks->deadline,
                              keygen_round2_conclude,
                              ks);
 }
@@ -1082,29 +1169,24 @@ insert_round1_element (struct KeygenSession *ks)
   // g^a_{i,0}
   gcry_mpi_t v;
   // big-endian representation of 'v'
-  unsigned char v_data[GNUNET_SECRETSHARING_KEY_BITS / 8];
+  unsigned char v_data[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8];
 
   element = GNUNET_malloc (sizeof *element + sizeof *d);
   d = (void *) &element[1];
   element->data = d;
   element->size = sizeof *d;
 
-  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "alloc'd size %u\n", sizeof *element + sizeof *d);
-  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "element size %u\n", element->size);
-
-
   d->peer = my_peer;
 
-  GNUNET_assert (0 != (v = gcry_mpi_new (GNUNET_SECRETSHARING_KEY_BITS)));
+  GNUNET_assert (0 != (v = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
 
   gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[0], elgamal_p);
 
-  print_mpi_fixed (v_data, v, GNUNET_SECRETSHARING_KEY_BITS);
+  GNUNET_CRYPTO_mpi_print_unsigned (v_data, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
 
-  GNUNET_CRYPTO_hash (v_data, GNUNET_SECRETSHARING_KEY_BITS / 8, &d->commitment);
+  GNUNET_CRYPTO_hash (v_data, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, &d->commitment);
 
-  print_mpi_fixed (d->pubkey.n, ks->info[ks->local_peer_idx].paillier_n,
-                   PAILLIER_BITS / 8);
+  d->pubkey = ks->info[ks->local_peer_idx].paillier_public_key;
 
   d->purpose.size = htonl ((sizeof *d) - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose));
   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG1);
@@ -1156,35 +1238,35 @@ static void handle_client_keygen (void *cls,
 
   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "first round of consensus with %u peers\n", ks->num_peers);
   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &msg->session_id,
+                                           GNUNET_TIME_absolute_ntoh (msg->start),
+                                           GNUNET_TIME_absolute_ntoh (msg->deadline),
                                            keygen_round1_new_element, ks);
 
-  ks->info = GNUNET_malloc (ks->num_peers * sizeof (struct KeygenPeerInfo));
+  ks->info = GNUNET_new_array (ks->num_peers, struct KeygenPeerInfo);
 
   for (i = 0; i < ks->num_peers; i++)
     ks->info[i].peer = ks->peers[i];
 
-  GNUNET_assert (0 != (ks->info[ks->local_peer_idx].paillier_n = mpi_new (0)));
-  GNUNET_assert (0 != (ks->paillier_lambda = mpi_new (0)));
-  GNUNET_assert (0 != (ks->paillier_mu = mpi_new (0)));
-
-  paillier_create (ks->info[ks->local_peer_idx].paillier_n,
-                   ks->paillier_lambda,
-                   ks->paillier_mu);
+  GNUNET_CRYPTO_paillier_create (&ks->info[ks->local_peer_idx].paillier_public_key,
+                                 &ks->paillier_private_key);
 
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Generated paillier key pair\n", ks->local_peer_idx);
 
   generate_presecret_polynomial (ks);
 
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Generated presecret polynomial\n", ks->local_peer_idx);
+
   insert_round1_element (ks);
 
-  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "starting conclude of round 1\n");
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Concluding for round 1\n", ks->local_peer_idx);
 
   GNUNET_CONSENSUS_conclude (ks->consensus,
-                             /* half the overall time */
-                             time_between (ks->start_time, ks->deadline, 1, 2),
                              keygen_round1_conclude,
                              ks);
 
   GNUNET_SERVER_receive_done (client, GNUNET_OK);
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Waiting for round 1 elements ...\n", ks->local_peer_idx);
 }
 
 
@@ -1201,6 +1283,7 @@ decrypt_conclude (void *cls)
   gcry_mpi_t m;
   gcry_mpi_t tmp;
   gcry_mpi_t c_2;
+  gcry_mpi_t prod;
   unsigned int *indices;
   unsigned int num;
   unsigned int i;
@@ -1209,6 +1292,7 @@ decrypt_conclude (void *cls)
   GNUNET_assert (0 != (lagrange = gcry_mpi_new (0)));
   GNUNET_assert (0 != (m = gcry_mpi_new (0)));
   GNUNET_assert (0 != (tmp = gcry_mpi_new (0)));
+  GNUNET_assert (0 != (prod = gcry_mpi_new (0)));
 
   num = 0;
   for (i = 0; i < ds->share->num_peers; i++)
@@ -1219,34 +1303,57 @@ decrypt_conclude (void *cls)
   j = 0;
   for (i = 0; i < ds->share->num_peers; i++)
     if (NULL != ds->info[i].partial_decryption)
-      indices[j++] = ds->info[i].real_index;
+      indices[j++] = ds->info[i].original_index;
 
-  gcry_mpi_set_ui (m, 1);
+  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: decrypt conclude, with %u peers\n",
+              ds->share->my_peer, num);
 
+  gcry_mpi_set_ui (prod, 1);
   for (i = 0; i < num; i++)
   {
+
+    GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: index of %u: %u\n",
+                ds->share->my_peer, i, indices[i]);
     compute_lagrange_coefficient (lagrange, indices[i], indices, num);
-    // w_j^{\lambda_j}
+    // w_i^{\lambda_i}
     gcry_mpi_powm (tmp, ds->info[indices[i]].partial_decryption, lagrange, elgamal_p);
-    gcry_mpi_mulm (m, m, tmp, elgamal_p);
-  }
 
-  GNUNET_assert (0 == gcry_mpi_scan (&c_2, GCRYMPI_FMT_USG, ds->ciphertext.c2_bits,
-                                     GNUNET_SECRETSHARING_KEY_BITS / 8, NULL));
+    // product of all exponentiated partiel decryptions ...
+    gcry_mpi_mulm (prod, prod, tmp, elgamal_p);
+  }
 
-  // m <- c_2 / m
-  gcry_mpi_invm (m, m, elgamal_p);
-  gcry_mpi_mulm (m, c_2, m, elgamal_p);
+  GNUNET_CRYPTO_mpi_scan_unsigned (&c_2, ds->ciphertext.c2_bits, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
 
+  GNUNET_assert (0 != gcry_mpi_invm (prod, prod, elgamal_p));
+  gcry_mpi_mulm (m, c_2, prod, elgamal_p);
   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT_DONE);
-  print_mpi_fixed (&msg->plaintext, m, GNUNET_SECRETSHARING_KEY_BITS / 8);
+  GNUNET_CRYPTO_mpi_print_unsigned (&msg->plaintext, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, m);
   msg->success = htonl (1);
   GNUNET_MQ_send (ds->client_mq, ev);
 
+  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "sent decrypt done to client\n");
+
   // FIXME: what if not enough peers participated?
 }
 
 
+/**
+ * Get a string representation of an MPI.
+ * The caller must free the returned string.
+ *
+ * @param mpi mpi to convert to a string
+ * @return string representation of @a mpi, must be free'd by the caller
+ */
+static char *
+mpi_to_str (gcry_mpi_t mpi)
+{
+  unsigned char *buf;
+
+  GNUNET_assert (0 == gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buf, NULL, mpi));
+  return (char *) buf;
+}
+
+
 /**
  * Called when a new partial decryption arrives.
  */
@@ -1257,6 +1364,27 @@ decrypt_new_element (void *cls,
   struct DecryptSession *session = cls;
   const struct GNUNET_SECRETSHARING_DecryptData *d;
   struct DecryptPeerInfo *info;
+  struct GNUNET_HashCode challenge_hash;
+
+  /* nizk response */
+  gcry_mpi_t r;
+  /* nizk challenge */
+  gcry_mpi_t challenge;
+  /* nizk commit1, g^\beta */
+  gcry_mpi_t commit1;
+  /* nizk commit2, c_1^\beta */
+  gcry_mpi_t commit2;
+  /* homomorphic commitment to the peer's share,
+   * public key share */
+  gcry_mpi_t sigma;
+  /* partial decryption we received */
+  gcry_mpi_t w;
+  /* ciphertext component #1 */
+  gcry_mpi_t c1;
+  /* temporary variable (for comparision) #1 */
+  gcry_mpi_t tmp1;
+  /* temporary variable (for comparision) #2 */
+  gcry_mpi_t tmp2;
 
   if (NULL == element)
   {
@@ -1289,36 +1417,184 @@ decrypt_new_element (void *cls,
     return;
   }
 
-  // FIXME: check NIZP first
+  if (0 != memcmp (&d->ciphertext, &session->ciphertext, sizeof (struct GNUNET_SECRETSHARING_Ciphertext)))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: got decrypt element with non-matching ciphertext from P%u\n",
+                (unsigned int) session->share->my_peer, (unsigned int) (info - session->info));
+
+    return;
+  }
+
+
+  GNUNET_CRYPTO_hash (offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext) + (char *) d,
+                      offsetof (struct GNUNET_SECRETSHARING_DecryptData, nizk_response) - 
+                          offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext),
+                      &challenge_hash);
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&challenge, &challenge_hash,
+                                   sizeof (struct GNUNET_HashCode));
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&sigma, &session->share->sigmas[info - session->info],
+                                   sizeof (struct GNUNET_SECRETSHARING_FieldElement));
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&c1, session->ciphertext.c1_bits,
+                                   sizeof (struct GNUNET_SECRETSHARING_FieldElement));
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&commit1, &d->nizk_commit1,
+                                   sizeof (struct GNUNET_SECRETSHARING_FieldElement));
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&commit2, &d->nizk_commit2,
+                                   sizeof (struct GNUNET_SECRETSHARING_FieldElement));
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&r, &d->nizk_response,
+                                   sizeof (struct GNUNET_SECRETSHARING_FieldElement));
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&w, &d->partial_decryption,
+                                   sizeof (struct GNUNET_SECRETSHARING_FieldElement));
+
+  GNUNET_assert (NULL != (tmp1 = gcry_mpi_new (0)));
+  GNUNET_assert (NULL != (tmp2 = gcry_mpi_new (0)));
+
+  // tmp1 = g^r
+  gcry_mpi_powm (tmp1, elgamal_g, r, elgamal_p);
+
+  // tmp2 = g^\beta * \sigma^challenge
+  gcry_mpi_powm (tmp2, sigma, challenge, elgamal_p);
+  gcry_mpi_mulm (tmp2, tmp2, commit1, elgamal_p);
+
+  if (0 != gcry_mpi_cmp (tmp1, tmp2))
+  {
+    char *tmp1_str;
+    char *tmp2_str;
+    tmp1_str = mpi_to_str (tmp1);
+    tmp2_str = mpi_to_str (tmp2);
+    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Received invalid partial decryption from P%u (eqn 1), expected %s got %s\n",
+                session->share->my_peer, info - session->info, tmp1_str, tmp2_str);
+    GNUNET_free (tmp1_str);
+    GNUNET_free (tmp2_str);
+    // return;
+  }
+
+
+  gcry_mpi_powm (tmp1, c1, r, elgamal_p);
+
+  gcry_mpi_powm (tmp2, w, challenge, elgamal_p);
+  gcry_mpi_mulm (tmp2, tmp2, commit2, elgamal_p);
+
+
+  if (0 != gcry_mpi_cmp (tmp1, tmp2))
+  {
+    GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Received invalid partial decryption from P%u (eqn 2)\n",
+                session->share->my_peer, info - session->info);
+    // return;
+  }
+
 
-  GNUNET_assert (0 == gcry_mpi_scan (&info->partial_decryption,
-                                     GCRYMPI_FMT_USG, &d->partial_decryption, GNUNET_SECRETSHARING_KEY_BITS / 8, NULL));
+  GNUNET_CRYPTO_mpi_scan_unsigned (&info->partial_decryption, &d->partial_decryption,
+                                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
 }
 
+
 static void
 insert_decrypt_element (struct DecryptSession *ds)
 {
   struct GNUNET_SECRETSHARING_DecryptData d;
   struct GNUNET_SET_Element element;
-  gcry_mpi_t x;
+  /* our share */
   gcry_mpi_t s;
+  /* partial decryption with our share */
+  gcry_mpi_t w;
+  /* first component of the elgamal ciphertext */
+  gcry_mpi_t c1;
+  /* nonce for dlog zkp */
+  gcry_mpi_t beta;
+  gcry_mpi_t tmp;
+  gcry_mpi_t challenge;
+  gcry_mpi_t sigma;
+  struct GNUNET_HashCode challenge_hash;
+
+  /* make vagrind happy until we implement the real deal ... */
+  memset (&d, 0, sizeof d);
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting decrypt element\n",
+              ds->share->my_peer);
+
+  GNUNET_assert (ds->share->my_peer < ds->share->num_peers);
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&c1, &ds->ciphertext.c1_bits,
+                                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
+  GNUNET_CRYPTO_mpi_scan_unsigned (&s, &ds->share->my_share,
+                                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
+  GNUNET_CRYPTO_mpi_scan_unsigned (&sigma, &ds->share->sigmas[ds->share->my_peer],
+                                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
+
+  GNUNET_assert (NULL != (w = gcry_mpi_new (0)));
+  GNUNET_assert (NULL != (beta = gcry_mpi_new (0)));
+  GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
 
-  GNUNET_assert (0 == gcry_mpi_scan (&x, GCRYMPI_FMT_USG, ds->ciphertext.c1_bits, GNUNET_SECRETSHARING_KEY_BITS / 8, NULL));
-  GNUNET_assert (0 == gcry_mpi_scan (&s, GCRYMPI_FMT_USG, &ds->share->my_share, GNUNET_SECRETSHARING_KEY_BITS / 8, NULL));
+  // FIXME: unnecessary, remove once crypto works
+  gcry_mpi_powm (tmp, elgamal_g, s, elgamal_p);
+  if (0 != gcry_mpi_cmp (tmp, sigma))
+  {
+    char *sigma_str = mpi_to_str (sigma);
+    char *tmp_str = mpi_to_str (tmp);
+    char *s_str = mpi_to_str (s);
+    GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Share of P%u is invalid, ref sigma %s, "
+                "computed sigma %s, s %s\n",
+                ds->share->my_peer,
+                sigma_str, tmp_str, s_str);
+    GNUNET_free (sigma_str);
+    GNUNET_free (tmp_str);
+    GNUNET_free (s_str);
+  }
 
-  gcry_mpi_powm (x, x, s, elgamal_p);
+  gcry_mpi_powm (w, c1, s, elgamal_p);
 
   element.data = (void *) &d;
   element.size = sizeof (struct GNUNET_SECRETSHARING_DecryptData);
+  element.type = 0;
 
+  d.ciphertext = ds->ciphertext;
   d.peer = my_peer;
-  d.purpose.size = htonl (element.size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose));
+  GNUNET_CRYPTO_mpi_print_unsigned (&d.partial_decryption, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, w);
+
+  // create the zero knowledge proof
+  // randomly choose beta such that 0 < beta < q
+  do 
+  {
+    gcry_mpi_randomize (beta, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
+  } while ((gcry_mpi_cmp_ui (beta, 0) == 0) || (gcry_mpi_cmp (beta, elgamal_q) >= 0));
+  // tmp = g^beta
+  gcry_mpi_powm (tmp, elgamal_g, beta, elgamal_p);
+  GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_commit1, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
+  // tmp = (c_1)^beta
+  gcry_mpi_powm (tmp, c1, beta, elgamal_p);
+  GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_commit2, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
+
+  // the challenge is the hash of everything up to the response
+  GNUNET_CRYPTO_hash (offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext) + (char *) &d,
+                      offsetof (struct GNUNET_SECRETSHARING_DecryptData, nizk_response) - 
+                          offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext),
+                      &challenge_hash);
+
+  GNUNET_CRYPTO_mpi_scan_unsigned (&challenge, &challenge_hash,
+                                   sizeof (struct GNUNET_HashCode));
+
+  // compute the response in tmp,
+  // tmp = (c * s + beta) mod q
+  gcry_mpi_mulm (tmp, challenge, s, elgamal_q);
+  gcry_mpi_addm (tmp, tmp, beta, elgamal_q);
+
+  GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_response, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
+
+  d.purpose.size = htonl (element.size - offsetof (struct GNUNET_SECRETSHARING_DecryptData, purpose));
   d.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DECRYPTION);
+  
   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d.purpose, &d.signature);
 
-  print_mpi_fixed (&d.partial_decryption, x, GNUNET_SECRETSHARING_KEY_BITS / 8);
-
   GNUNET_CONSENSUS_insert (ds->consensus, &element, NULL, NULL);
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting decrypt element done!\n",
+              ds->share->my_peer);
 }
 
 
@@ -1339,12 +1615,14 @@ static void handle_client_decrypt (void *cls,
       (const void *) message;
   struct DecryptSession *ds;
   struct GNUNET_HashCode session_id;
+  unsigned int i;
 
   ds = GNUNET_new (struct DecryptSession);
   // FIXME: check if session already exists
   GNUNET_CONTAINER_DLL_insert (decrypt_sessions_head, decrypt_sessions_tail, ds);
   ds->client = client;
   ds->client_mq = GNUNET_MQ_queue_for_server_client (client);
+  ds->start = GNUNET_TIME_absolute_ntoh (msg->start);
   ds->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
   ds->ciphertext = msg->ciphertext;
 
@@ -1359,52 +1637,84 @@ static void handle_client_decrypt (void *cls,
                                            ds->share->num_peers,
                                            ds->share->peers,
                                            &session_id,
-                                           decrypt_new_element,
+                                           ds->start,
+                                           ds->deadline,
+                                           &decrypt_new_element,
                                            ds);
 
+
+  ds->info = GNUNET_new_array (ds->share->num_peers, struct DecryptPeerInfo);
+  for (i = 0; i < ds->share->num_peers; i++)
+  {
+    ds->info[i].peer = ds->share->peers[i];
+    ds->info[i].original_index = ds->share->original_indices[i];
+  }
+
   insert_decrypt_element (ds);
 
-  GNUNET_CONSENSUS_conclude (ds->consensus, ds->deadline, decrypt_conclude, ds);
+  GNUNET_CONSENSUS_conclude (ds->consensus, decrypt_conclude, ds);
+
+  GNUNET_SERVER_receive_done (client, GNUNET_OK);
+
+  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "decrypting with %u peers\n",
+              ds->share->num_peers);
 }
 
 
 static void
 init_crypto_constants (void)
 {
-  /* 1024-bit safe prime */
-  const char *elgamal_p_hex =
-      "0x08a347d3d69e8b2dd7d1b12a08dfbccbebf4ca"
-      "6f4269a0814e158a34312964d946b3ef22882317"
-      "2bcf30fc08f772774cb404f9bc002a6f66b09a79"
-      "d810d67c4f8cb3bedc6060e3c8ef874b1b64df71"
-      "6c7d2b002da880e269438d5a776e6b5f253c8df5"
-      "6a16b1c7ce58def07c03db48238aadfc52a354a2"
-      "7ed285b0c1675cad3f3";
-  /* 1023-bit Sophie Germain prime, q = (p-1)/2 */
-  const char *elgamal_q_hex =
-      "0x0451a3e9eb4f4596ebe8d895046fde65f5fa65"
-      "37a134d040a70ac51a1894b26ca359f79144118b"
-      "95e7987e047bb93ba65a027cde001537b3584d3c"
-      "ec086b3e27c659df6e303071e477c3a58db26fb8"
-      "b63e958016d4407134a1c6ad3bb735af929e46fa"
-      "b50b58e3e72c6f783e01eda411c556fe2951aa51"
-      "3f6942d860b3ae569f9";
-  /* generator of the unique size q subgroup of Z_p^* */
-  const char *elgamal_g_hex =
-      "0x05c00c36d2e822950087ef09d8252994adc4e4"
-      "8fe3ec70269f035b46063aff0c99b633fd64df43"
-      "02442e1914c829a41505a275438871f365e91c12"
-      "3d5303ef9e90f4b8cb89bf86cc9b513e74a72634"
-      "9cfd9f953674fab5d511e1c078fc72d72b34086f"
-      "c82b4b951989eb85325cb203ff98df76bc366bba"
-      "1d7024c3650f60d0da";
-
   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_q, GCRYMPI_FMT_HEX,
-                                     elgamal_q_hex, 0, NULL));
+                                     GNUNET_SECRETSHARING_ELGAMAL_Q_HEX, 0, NULL));
   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_p, GCRYMPI_FMT_HEX,
-                                     elgamal_p_hex, 0, NULL));
+                                     GNUNET_SECRETSHARING_ELGAMAL_P_HEX, 0, NULL));
   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_g, GCRYMPI_FMT_HEX,
-                                     elgamal_g_hex, 0, NULL));
+                                     GNUNET_SECRETSHARING_ELGAMAL_G_HEX, 0, NULL));
+}
+
+
+static struct KeygenSession *
+keygen_session_get (struct GNUNET_SERVER_Client *client)
+{
+  struct KeygenSession *ks;
+  for (ks = keygen_sessions_head; NULL != ks; ks = ks->next)
+    if (ks->client == client)
+      return ks;
+  return NULL;
+}
+
+static struct DecryptSession *
+decrypt_session_get (struct GNUNET_SERVER_Client *client)
+{
+  struct DecryptSession *ds;
+  for (ds = decrypt_sessions_head; NULL != ds; ds = ds->next)
+    if (ds->client == client)
+      return ds;
+  return NULL;
+}
+
+
+/**
+ * Clean up after a client has disconnected
+ *
+ * @param cls closure, unused
+ * @param client the client to clean up after
+ */
+static void
+handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
+{
+  struct KeygenSession *ks;
+  struct DecryptSession *ds;
+
+  GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handling client disconnect\n");
+
+  ks = keygen_session_get (client);
+  if (NULL != ks)
+    keygen_session_destroy (ks);
+
+  ds = decrypt_session_get (client);
+  if (NULL != ds)
+    decrypt_session_destroy (ds);
 }
 
 
@@ -1443,6 +1753,7 @@ run (void *cls, struct GNUNET_SERVER_Handle *server,
     return;
   }
   GNUNET_SERVER_add_handlers (server, handlers);
+  GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
                                 NULL);
 }