fix lots of memory leaks in secretsharing key generation
[oweals/gnunet.git] / src / secretsharing / gnunet-service-secretsharing.c
1 /*
2      This file is part of GNUnet.
3      (C) 2013 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 3, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file secretsharing/gnunet-service-secretsharing.c
23  * @brief secret sharing service
24  * @author Florian Dold
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_time_lib.h"
29 #include "gnunet_signatures.h"
30 #include "gnunet_consensus_service.h"
31 #include "secretsharing.h"
32 #include "secretsharing_protocol.h"
33 #include <gcrypt.h>
34
35
36 #define EXTRA_CHECKS 1
37
38
39 /**
40  * Info about a peer in a key generation session.
41  */
42 struct KeygenPeerInfo
43 {
44   /**
45    * Peer identity of the peer.
46    */
47   struct GNUNET_PeerIdentity peer;
48
49   /**
50    * The peer's paillier public key.
51    * Freshly generated for each keygen session.
52    */
53   struct GNUNET_CRYPTO_PaillierPublicKey paillier_public_key;
54
55   /**
56    * The peer's commitment to his presecret.
57    */
58   gcry_mpi_t presecret_commitment;
59
60   /**
61    * Commitment to the preshare that is
62    * intended for our peer.
63    */
64   gcry_mpi_t preshare_commitment;
65
66   /**
67    * Sigma (exponentiated share) for this peer.
68    */
69   gcry_mpi_t sigma;
70
71   /**
72    * Did we successfully receive the round1 element
73    * of the peer?
74    */
75   int round1_valid;
76
77   /**
78    * Did we successfully receive the round2 element
79    * of the peer?
80    */
81   int round2_valid;
82 };
83
84
85 /**
86  * Information about a peer in a decrypt session.
87  */
88 struct DecryptPeerInfo
89 {
90   /**
91    * Identity of the peer.
92    */
93   struct GNUNET_PeerIdentity peer;
94
95   /**
96    * Original index in the key generation round.
97    * Necessary for computing the lagrange coefficients.
98    */
99   unsigned int original_index;
100
101   /**
102    * Set to the partial decryption of
103    * this peer, or NULL if we did not
104    * receive a partial decryption from this
105    * peer or the zero knowledge proof failed.
106    */
107   gcry_mpi_t partial_decryption;
108 };
109
110
111 /**
112  * Session to establish a threshold-shared secret.
113  */
114 struct KeygenSession
115 {
116   /**
117    * Keygen sessions are held in a linked list.
118    */
119   struct KeygenSession *next;
120
121   /**
122    * Keygen sessions are held in a linked list.
123    */
124   struct KeygenSession *prev;
125
126   /**
127    * Current consensus, used for both DKG rounds.
128    */
129   struct GNUNET_CONSENSUS_Handle *consensus;
130
131   /**
132    * Client that is interested in the result
133    * of this key generation session.
134    */
135   struct GNUNET_SERVER_Client *client;
136
137   /**
138    * Message queue for 'client'
139    */
140   struct GNUNET_MQ_Handle *client_mq;
141
142   /**
143    * Randomly generated coefficients of the polynomial for sharing our
144    * pre-secret, where 'preshares[0]' is our pre-secret.  Contains 'threshold'
145    * elements, thus represents a polynomial of degree 'threshold-1', which can
146    * be interpolated with 'threshold' data points.
147    *
148    * The pre-secret-shares 'i=1,...,num_peers' are given by evaluating this
149    * polyomial at 'i' for share i.
150    */
151   gcry_mpi_t *presecret_polynomial;
152
153   /**
154    * Minimum number of shares required to restore the secret.
155    * Also the number of coefficients for the polynomial representing
156    * the sharing.  Obviously, the polynomial then has degree threshold-1.
157    */
158   unsigned int threshold;
159
160   /**
161    * Total number of peers.
162    */
163   unsigned int num_peers;
164
165   /**
166    * Index of the local peer.
167    */
168   unsigned int local_peer;
169
170   /**
171    * Information about all participating peers.
172    * Array of size 'num_peers'.
173    */
174   struct KeygenPeerInfo *info;
175
176   /**
177    * List of all peers involved in the secret sharing session.
178    */
179   struct GNUNET_PeerIdentity *peers;
180
181   /**
182    * Identifier for this session.
183    */
184   struct GNUNET_HashCode session_id;
185
186   /**
187    * Paillier private key of our peer.
188    */
189   struct GNUNET_CRYPTO_PaillierPrivateKey paillier_private_key;
190
191   /**
192    * When would we like the key to be established?
193    */
194   struct GNUNET_TIME_Absolute deadline;
195
196   /**
197    * When does the DKG start?  Necessary to compute fractions of the
198    * operation's desired time interval.
199    */
200   struct GNUNET_TIME_Absolute start_time;
201
202   /**
203    * Index of the local peer in the ordered list
204    * of peers in the session.
205    */
206   unsigned int local_peer_idx;
207
208   /**
209    * Share of our peer.  Once preshares from other peers are received, they
210    * will be added to 'my'share.
211    */
212   gcry_mpi_t my_share;
213
214   /**
215    * Public key, will be updated when a round2 element arrives.
216    */
217   gcry_mpi_t public_key;
218 };
219
220
221 /**
222  * Session to cooperatively decrypt a value.
223  */
224 struct DecryptSession
225 {
226   /**
227    * Decrypt sessions are stored in a linked list.
228    */
229   struct DecryptSession *next;
230
231   /**
232    * Decrypt sessions are stored in a linked list.
233    */
234   struct DecryptSession *prev;
235
236   /**
237    * Handle to the consensus over partial decryptions.
238    */
239   struct GNUNET_CONSENSUS_Handle *consensus;
240
241   /**
242    * Client connected to us.
243    */
244   struct GNUNET_SERVER_Client *client;
245
246   /**
247    * Message queue for 'client'.
248    */
249   struct GNUNET_MQ_Handle *client_mq;
250
251   /**
252    * When should we start communicating for decryption?
253    */
254   struct GNUNET_TIME_Absolute start;
255
256   /**
257    * When would we like the ciphertext to be
258    * decrypted?
259    */
260   struct GNUNET_TIME_Absolute deadline;
261
262   /**
263    * Ciphertext we want to decrypt.
264    */
265   struct GNUNET_SECRETSHARING_Ciphertext ciphertext;
266
267   /**
268    * Share of the local peer.
269    * Containts other important information, such as
270    * the list of other peers.
271    */
272   struct GNUNET_SECRETSHARING_Share *share;
273
274   /**
275    * State information about other peers.
276    */
277   struct DecryptPeerInfo *info;
278 };
279
280
281 /**
282  * Decrypt sessions are held in a linked list.
283  */
284 static struct DecryptSession *decrypt_sessions_head;
285
286 /**
287  * Decrypt sessions are held in a linked list.
288  */
289 static struct DecryptSession *decrypt_sessions_tail;
290
291 /**
292  * Decrypt sessions are held in a linked list.
293  */
294 static struct KeygenSession *keygen_sessions_head;
295
296 /**
297  * Decrypt sessions are held in a linked list.
298  */
299 static struct KeygenSession *keygen_sessions_tail;
300
301 /**
302  * The ElGamal prime field order as libgcrypt mpi.
303  * Initialized in #init_crypto_constants.
304  */
305 static gcry_mpi_t elgamal_q;
306
307 /**
308  * Modulus of the prime field used for ElGamal.
309  * Initialized in #init_crypto_constants.
310  */
311 static gcry_mpi_t elgamal_p;
312
313 /**
314  * Generator for prime field of order 'elgamal_q'.
315  * Initialized in #init_crypto_constants.
316  */
317 static gcry_mpi_t elgamal_g;
318
319 /**
320  * Peer that runs this service.
321  */
322 static struct GNUNET_PeerIdentity my_peer;
323
324 /**
325  * Peer that runs this service.
326  */
327 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_peer_private_key;
328
329 /**
330  * Configuration of this service.
331  */
332 static const struct GNUNET_CONFIGURATION_Handle *cfg;
333
334 /**
335  * Server for this service.
336  */
337 static struct GNUNET_SERVER_Handle *srv;
338
339
340 /**
341  * Get the peer info belonging to a peer identity in a keygen session.
342  *
343  * @param ks The keygen session.
344  * @param peer The peer identity.
345  * @return The Keygen peer info, or NULL if the peer could not be found.
346  */
347 static struct KeygenPeerInfo *
348 get_keygen_peer_info (const struct KeygenSession *ks,
349                       const struct GNUNET_PeerIdentity *peer)
350 {
351   unsigned int i;
352   for (i = 0; i < ks->num_peers; i++)
353     if (0 == memcmp (peer, &ks->info[i].peer, sizeof (struct GNUNET_PeerIdentity)))
354       return &ks->info[i];
355   return NULL;
356 }
357
358
359 /**
360  * Get the peer info belonging to a peer identity in a decrypt session.
361  *
362  * @param ds The decrypt session.
363  * @param peer The peer identity.
364  * @return The decrypt peer info, or NULL if the peer could not be found.
365  */
366 static struct DecryptPeerInfo *
367 get_decrypt_peer_info (const struct DecryptSession *ds,
368                        const struct GNUNET_PeerIdentity *peer)
369 {
370   unsigned int i;
371   for (i = 0; i < ds->share->num_peers; i++)
372     if (0 == memcmp (peer, &ds->info[i].peer, sizeof (struct GNUNET_PeerIdentity)))
373       return &ds->info[i];
374   return NULL;
375 }
376
377
378 /**
379  * Interpolate between two points in time.
380  *
381  * @param start start time
382  * @param end end time
383  * @param num numerator of the scale factor
384  * @param denum denumerator of the scale factor
385  */
386 static struct GNUNET_TIME_Absolute
387 time_between (struct GNUNET_TIME_Absolute start,
388               struct GNUNET_TIME_Absolute end,
389               int num, int denum)
390 {
391   struct GNUNET_TIME_Absolute result;
392   uint64_t diff;
393
394   GNUNET_assert (start.abs_value_us <= end.abs_value_us);
395   diff = end.abs_value_us - start.abs_value_us;
396   result.abs_value_us = start.abs_value_us + ((diff * num) / denum);
397
398   return result;
399 }
400
401
402 /**
403  * Compare two peer identities.  Indended to be used with qsort or bsearch.
404  *
405  * @param p1 Some peer identity.
406  * @param p2 Some peer identity.
407  * @return 1 if p1 > p2, -1 if p1 < p2 and 0 if p1 == p2.
408  */
409 static int
410 peer_id_cmp (const void *p1, const void *p2)
411 {
412   return memcmp (p1, p2, sizeof (struct GNUNET_PeerIdentity));
413 }
414
415
416 /**
417  * Get the index of a peer in an array of peers
418  *
419  * @param haystack Array of peers.
420  * @param n Size of @a haystack.
421  * @param needle Peer to find
422  * @return Index of @a needle in @a haystack, or -1 if peer
423  *         is not in the list.
424  */
425 static int
426 peer_find (const struct GNUNET_PeerIdentity *haystack, unsigned int n,
427            const struct GNUNET_PeerIdentity *needle)
428 {
429   unsigned int i;
430   for (i = 0; i < n; i++)
431     if (0 == memcmp (&haystack[i], needle, sizeof (struct GNUNET_PeerIdentity)))
432       return i;
433   return -1;
434 }
435
436
437 /**
438  * Normalize the given list of peers, by including the local peer
439  * (if it is missing) and sorting the peers by their identity.
440  *
441  * @param listed Peers in the unnormalized list.
442  * @param num_listed Peers in the un-normalized list.
443  * @param[out] num_normalized Number of peers in the normalized list.
444  * @param[out] my_peer_idx Index of the local peer in the normalized list.
445  * @return Normalized list, must be free'd by the caller.
446  */
447 static struct GNUNET_PeerIdentity *
448 normalize_peers (struct GNUNET_PeerIdentity *listed,
449                  unsigned int num_listed,
450                  unsigned int *num_normalized,
451                  unsigned int *my_peer_idx)
452 {
453   unsigned int local_peer_in_list;
454   /* number of peers in the normalized list */
455   unsigned int n;
456   struct GNUNET_PeerIdentity *normalized;
457
458   local_peer_in_list = GNUNET_YES;
459   n = num_listed;
460   if (peer_find (listed, num_listed, &my_peer) < 0)
461   {
462     local_peer_in_list = GNUNET_NO;
463     n += 1;
464   }
465
466   normalized = GNUNET_new_array (n, struct GNUNET_PeerIdentity);
467
468   if (GNUNET_NO == local_peer_in_list)
469     normalized[n - 1] = my_peer;
470
471   memcpy (normalized, listed, num_listed * sizeof (struct GNUNET_PeerIdentity));
472   qsort (normalized, n, sizeof (struct GNUNET_PeerIdentity), &peer_id_cmp);
473
474   if (NULL != my_peer_idx)
475     *my_peer_idx = peer_find (normalized, n, &my_peer);
476   if (NULL != num_normalized)
477     *num_normalized = n;
478
479   return normalized;
480 }
481
482
483 /**
484  * Get a the j-th lagrange coefficient for a set of indices.
485  *
486  * @param[out] coeff the lagrange coefficient
487  * @param j lagrange coefficient we want to compute
488  * @param indices indices
489  * @param num number of indices in @a indices
490  */
491 static void
492 compute_lagrange_coefficient (gcry_mpi_t coeff, unsigned int j,
493                               unsigned int *indices,
494                               unsigned int num)
495 {
496   unsigned int i;
497   /* numerator */
498   gcry_mpi_t n;
499   /* denominator */
500   gcry_mpi_t d;
501   /* temp value for l-j */
502   gcry_mpi_t tmp;
503
504   GNUNET_assert (0 != coeff);
505
506   GNUNET_assert (0 != (n = gcry_mpi_new (0)));
507   GNUNET_assert (0 != (d = gcry_mpi_new (0)));
508   GNUNET_assert (0 != (tmp = gcry_mpi_new (0)));
509
510   gcry_mpi_set_ui (n, 1);
511   gcry_mpi_set_ui (d, 1);
512
513   for (i = 0; i < num; i++)
514   {
515     unsigned int l = indices[i];
516     if (l == j)
517       continue;
518     gcry_mpi_mul_ui (n, n, l + 1);
519     // d <- d * (l-j)
520     gcry_mpi_set_ui (tmp, l + 1);
521     gcry_mpi_sub_ui (tmp, tmp, j + 1);
522     gcry_mpi_mul (d, d, tmp);
523   }
524
525   // gcry_mpi_invm does not like negative numbers ...
526   gcry_mpi_mod (d, d, elgamal_q);
527
528   GNUNET_assert (gcry_mpi_cmp_ui (d, 0) > 0);
529
530   // now we do the actual division, with everything mod q, as we
531   // are not operating on elements from <g>, but on exponents
532   GNUNET_assert (0 != gcry_mpi_invm (d, d, elgamal_q));
533
534   gcry_mpi_mulm (coeff, n, d, elgamal_q);
535
536   gcry_mpi_release (n);
537   gcry_mpi_release (d);
538   gcry_mpi_release (tmp);
539 }
540
541
542 /**
543  * Destroy a decrypt session, removing it from
544  * the linked list of decrypt sessions.
545  *
546  * @param ds decrypt session to destroy
547  */
548 static void
549 decrypt_session_destroy (struct DecryptSession *ds)
550 {
551   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying decrypt session\n");
552
553   GNUNET_CONTAINER_DLL_remove (decrypt_sessions_head, decrypt_sessions_tail, ds);
554
555   if (NULL != ds->consensus)
556   {
557     GNUNET_CONSENSUS_destroy (ds->consensus);
558     ds->consensus = NULL;
559   }
560
561   if (NULL != ds->client_mq)
562   {
563     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying decrypt MQ\n");
564     GNUNET_MQ_destroy (ds->client_mq);
565     ds->client_mq = NULL;
566   }
567
568   if (NULL != ds->client)
569   {
570     GNUNET_SERVER_client_disconnect (ds->client);
571     ds->client = NULL;
572   }
573
574   GNUNET_free (ds);
575 }
576
577 static void
578 keygen_info_destroy (struct KeygenPeerInfo *info)
579 {
580   if (NULL != info->sigma)
581   {
582     gcry_mpi_release (info->sigma);
583     info->sigma = NULL;
584   }
585   if (NULL != info->presecret_commitment)
586   {
587     gcry_mpi_release (info->presecret_commitment);
588     info->presecret_commitment = NULL;
589   }
590   if (NULL != info->preshare_commitment)
591   {
592     gcry_mpi_release (info->preshare_commitment);
593     info->presecret_commitment = NULL;
594   }
595 }
596
597
598 static void
599 keygen_session_destroy (struct KeygenSession *ks)
600 {
601   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying keygen session\n");
602
603   GNUNET_CONTAINER_DLL_remove (keygen_sessions_head, keygen_sessions_tail, ks);
604
605   if (NULL != ks->info)
606   {
607     unsigned int i;
608     for (i = 0; i < ks->num_peers; i++)
609       keygen_info_destroy (&ks->info[i]);
610     GNUNET_free (ks->info);
611     ks->info = NULL;
612   }
613
614   if (NULL != ks->consensus)
615   {
616     GNUNET_CONSENSUS_destroy (ks->consensus);
617     ks->consensus = NULL;
618   }
619
620   if (NULL != ks->presecret_polynomial)
621   {
622     unsigned int i;
623     for (i = 0; i < ks->threshold; i++)
624     {
625       GNUNET_assert (NULL != ks->presecret_polynomial[i]);
626       gcry_mpi_release (ks->presecret_polynomial[i]);
627       ks->presecret_polynomial[i] = NULL;
628     }
629     GNUNET_free (ks->presecret_polynomial);
630     ks->presecret_polynomial = NULL;
631   }
632
633   if (NULL != ks->client_mq)
634   {
635     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying keygen MQ\n");
636     GNUNET_MQ_destroy (ks->client_mq);
637     ks->client_mq = NULL;
638   }
639
640   if (NULL != ks->my_share)
641   {
642     gcry_mpi_release (ks->my_share);
643     ks->my_share = NULL;
644   }
645
646   if (NULL != ks->public_key)
647   {
648     gcry_mpi_release (ks->public_key);
649     ks->public_key = NULL;
650   }
651
652   if (NULL != ks->peers)
653   {
654     GNUNET_free (ks->peers);
655     ks->peers = NULL;
656   }
657
658   if (NULL != ks->client)
659   {
660     GNUNET_SERVER_client_disconnect (ks->client);
661     ks->client = NULL;
662   }
663
664   GNUNET_free (ks);
665 }
666
667
668 /**
669  * Task run during shutdown.
670  *
671  * @param cls unused
672  * @param tc unused
673  */
674 static void
675 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
676 {
677   while (NULL != decrypt_sessions_head)
678     decrypt_session_destroy (decrypt_sessions_head);
679
680   while (NULL != keygen_sessions_head)
681     keygen_session_destroy (keygen_sessions_head);
682 }
683
684
685
686 /**
687  * Generate the random coefficients of our pre-secret polynomial
688  *
689  * @param ks the session
690  */
691 static void
692 generate_presecret_polynomial (struct KeygenSession *ks)
693 {
694   int i;
695   gcry_mpi_t v;
696
697   GNUNET_assert (NULL == ks->presecret_polynomial);
698   ks->presecret_polynomial = GNUNET_new_array (ks->threshold, gcry_mpi_t);
699   for (i = 0; i < ks->threshold; i++)
700   {
701     v = ks->presecret_polynomial[i] = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS);
702     GNUNET_assert (NULL != v);
703     // Randomize v such that 0 < v < elgamal_q.
704     // The '- 1' is necessary as bitlength(q) = bitlength(p) - 1.
705     do 
706     {
707       gcry_mpi_randomize (v, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
708     } while ((gcry_mpi_cmp_ui (v, 0) == 0) || (gcry_mpi_cmp (v, elgamal_q) >= 0));
709   }
710 }
711
712
713 /**
714  * Consensus element handler for round one.
715  * We should get one ephemeral key for each peer.
716  *
717  * @param cls Closure (keygen session).
718  * @param element The element from consensus, or
719  *                NULL if consensus failed.
720  */
721 static void
722 keygen_round1_new_element (void *cls,
723                            const struct GNUNET_SET_Element *element)
724 {
725   const struct GNUNET_SECRETSHARING_KeygenCommitData *d;
726   struct KeygenSession *ks = cls;
727   struct KeygenPeerInfo *info;
728
729   if (NULL == element)
730   {
731     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "round1 consensus failed\n");
732     return;
733   }
734
735   /* elements have fixed size */
736   if (element->size != sizeof (struct GNUNET_SECRETSHARING_KeygenCommitData))
737   {
738     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
739                 "keygen commit data with wrong size (%u) in consensus, "
740                 " %u expected\n",
741                 element->size, sizeof (struct GNUNET_SECRETSHARING_KeygenCommitData));
742     return;
743   }
744
745   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round1 element\n");
746
747   d = element->data;
748   info = get_keygen_peer_info (ks, &d->peer);
749
750   if (NULL == info)
751   {
752     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong peer identity (%s) in consensus\n",
753                 GNUNET_i2s (&d->peer));
754     return;
755   }
756
757   /* Check that the right amount of data has been signed. */
758   if (d->purpose.size !=
759       htonl (element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose)))
760   {
761     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong signature purpose size in consensus\n");
762     return;
763   }
764
765   if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG1,
766                                                &d->purpose, &d->signature, &d->peer.public_key))
767   {
768     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with invalid signature in consensus\n");
769     return;
770   }
771   info->paillier_public_key = d->pubkey;
772   GNUNET_CRYPTO_mpi_scan_unsigned (&info->presecret_commitment, &d->commitment, 512 / 8);
773   info->round1_valid = GNUNET_YES;
774 }
775
776
777 /**
778  * Evaluate the polynomial with coefficients @a coeff at @a x.
779  * The i-th element in @a coeff corresponds to the coefficient of x^i.
780  *
781  * @param[out] z result of the evaluation
782  * @param coeff array of coefficients
783  * @param num_coeff number of coefficients
784  * @param x where to evaluate the polynomial
785  * @param m what group are we operating in?
786  */
787 static void
788 horner_eval (gcry_mpi_t z, gcry_mpi_t *coeff, unsigned int num_coeff, gcry_mpi_t x, gcry_mpi_t m)
789 {
790   unsigned int i;
791
792   gcry_mpi_set_ui (z, 0);
793   for (i = 0; i < num_coeff; i++)
794   {
795     // z <- zx + c
796     gcry_mpi_mul (z, z, x);
797     gcry_mpi_addm (z, z, coeff[num_coeff - i - 1], m);
798   }
799 }
800
801
802 static void
803 keygen_round2_conclude (void *cls)
804 {
805   struct KeygenSession *ks = cls;
806   struct GNUNET_SECRETSHARING_SecretReadyMessage *m;
807   struct GNUNET_MQ_Envelope *ev;
808   size_t share_size;
809   unsigned int i;
810   unsigned int j;
811   struct GNUNET_SECRETSHARING_Share *share;
812
813   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "round2 conclude\n");
814
815   GNUNET_CONSENSUS_destroy (ks->consensus);
816   ks->consensus = NULL;
817
818   share = GNUNET_new (struct GNUNET_SECRETSHARING_Share);
819
820   share->num_peers = 0;
821
822   for (i = 0; i < ks->num_peers; i++)
823     if (GNUNET_YES == ks->info[i].round2_valid)
824       share->num_peers++;
825
826   share->peers = GNUNET_new_array (share->num_peers, struct GNUNET_PeerIdentity);
827   share->sigmas =
828       GNUNET_new_array (share->num_peers, struct GNUNET_SECRETSHARING_FieldElement);
829   share->original_indices = GNUNET_new_array (share->num_peers, uint16_t);
830
831   /* maybe we're not even in the list of peers? */
832   share->my_peer = share->num_peers;
833
834   j = 0; /* running index of valid peers */
835   for (i = 0; i < ks->num_peers; i++)
836   {
837     if (GNUNET_YES == ks->info[i].round2_valid)
838     {
839       share->peers[j] = ks->info[i].peer;
840       GNUNET_CRYPTO_mpi_print_unsigned (&share->sigmas[j],
841                                         GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
842                                         ks->info[i].sigma);
843       share->original_indices[i] = j;
844       if (0 == memcmp (&share->peers[i], &my_peer, sizeof (struct GNUNET_PeerIdentity)))
845         share->my_peer = j;
846       j += 1;
847     }
848   }
849
850   if (share->my_peer == share->num_peers)
851   {
852     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: peer identity not in share\n", ks->local_peer_idx);
853   }
854
855   GNUNET_CRYPTO_mpi_print_unsigned (&share->my_share, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
856                                     ks->my_share);
857   GNUNET_CRYPTO_mpi_print_unsigned (&share->public_key, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
858                                     ks->public_key);
859
860   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "keygen completed with %u peers\n", share->num_peers);
861
862   /* Write the share. If 0 peers completed the dkg, an empty
863    * share will be sent. */
864
865   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, NULL, 0, &share_size));
866
867   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "writing share of size %u\n",
868               (unsigned int) share_size);
869
870   ev = GNUNET_MQ_msg_extra (m, share_size,
871                             GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_SECRET_READY);
872
873   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, &m[1], share_size, NULL));
874
875   GNUNET_SECRETSHARING_share_destroy (share);
876   share = NULL;
877
878   GNUNET_MQ_send (ks->client_mq, ev);
879 }
880
881
882 /**
883  * Insert round 2 element in the consensus, consisting of
884  * (1) The exponentiated pre-share polynomial coefficients A_{i,l}=g^{a_{i,l}}
885  * (2) The exponentiated pre-shares y_{i,j}=g^{s_{i,j}}
886  * (3) The encrypted pre-shares Y_{i,j}
887  * (4) The zero knowledge proof for fairness of
888  *     the encryption
889  *
890  * @param ks session to use
891  */
892 static void
893 insert_round2_element (struct KeygenSession *ks)
894 {
895   struct GNUNET_SET_Element *element;
896   struct GNUNET_SECRETSHARING_KeygenRevealData *d;
897   unsigned char *pos;
898   unsigned char *last_pos;
899   size_t element_size;
900   unsigned int i;
901   gcry_mpi_t idx;
902   gcry_mpi_t v;
903
904   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting round2 element\n",
905               ks->local_peer_idx);
906
907   GNUNET_assert (NULL != (v = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
908   GNUNET_assert (NULL != (idx = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
909
910   element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
911                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers +
912                   sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers +
913                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->threshold);
914
915   element = GNUNET_malloc (sizeof (struct GNUNET_SET_Element) + element_size);
916   element->size = element_size;
917   element->data = (void *) &element[1];
918
919   d = (void *) element->data;
920   d->peer = my_peer;
921
922   // start inserting vector elements
923   // after the fixed part of the element's data
924   pos = (void *) &d[1];
925   last_pos = pos + element_size;
926
927   // exponentiated pre-shares
928   for (i = 0; i < ks->num_peers; i++)
929   {
930     ptrdiff_t remaining = last_pos - pos;
931     GNUNET_assert (remaining > 0);
932     gcry_mpi_set_ui (idx, i + 1);
933     // evaluate the polynomial
934     horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_q);
935     // take g to the result
936     gcry_mpi_powm (v, elgamal_g, v, elgamal_p);
937     GNUNET_CRYPTO_mpi_print_unsigned (pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
938     pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8;
939   }
940
941   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed exp preshares\n",
942               ks->local_peer_idx);
943
944   // encrypted pre-shares
945   for (i = 0; i < ks->num_peers; i++)
946   {
947     ptrdiff_t remaining = last_pos - pos;
948     struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext;
949
950     GNUNET_assert (remaining > 0);
951     ciphertext = (void *) pos;
952     memset (ciphertext, 0, sizeof *ciphertext);
953     if (GNUNET_YES == ks->info[i].round1_valid)
954     {
955       gcry_mpi_set_ui (idx, i + 1);
956       // evaluate the polynomial
957       horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_q);
958       // encrypt the result
959       GNUNET_CRYPTO_paillier_encrypt (&ks->info[i].paillier_public_key, v, 0, ciphertext);
960     }
961     pos += sizeof *ciphertext;
962   }
963
964   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed enc preshares\n",
965               ks->local_peer_idx);
966
967   // exponentiated coefficients
968   for (i = 0; i < ks->threshold; i++)
969   {
970     ptrdiff_t remaining = last_pos - pos;
971     GNUNET_assert (remaining > 0);
972     gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[i], elgamal_p);
973     GNUNET_CRYPTO_mpi_print_unsigned (pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
974     pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8;
975   }
976
977   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed exp coefficients\n",
978               ks->local_peer_idx);
979
980   d->purpose.size = htonl (element_size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose));
981   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2);
982   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d->purpose, &d->signature);
983
984   GNUNET_CONSENSUS_insert (ks->consensus, element, NULL, NULL);
985   GNUNET_free (element); /* FIXME: maybe stack-allocate instead? */
986
987   gcry_mpi_release (v);
988   gcry_mpi_release (idx);
989 }
990
991
992 static gcry_mpi_t
993 keygen_reveal_get_exp_preshare (struct KeygenSession *ks,
994                                 const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
995                                 unsigned int idx)
996 {
997   unsigned char *pos;
998   gcry_mpi_t exp_preshare;
999
1000   GNUNET_assert (idx < ks->num_peers);
1001
1002   pos = (void *) &d[1];
1003   // skip exponentiated pre-shares we don't want
1004   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * idx;
1005   GNUNET_CRYPTO_mpi_scan_unsigned (&exp_preshare, pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1006   return exp_preshare;
1007 }
1008
1009 static gcry_mpi_t
1010 keygen_reveal_get_exp_coeff (struct KeygenSession *ks,
1011                              const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
1012                              unsigned int idx)
1013 {
1014   unsigned char *pos;
1015   gcry_mpi_t exp_coeff;
1016
1017   GNUNET_assert (idx < ks->threshold);
1018
1019   pos = (void *) &d[1];
1020   // skip exponentiated pre-shares
1021   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers;
1022   // skip encrypted pre-shares
1023   pos += sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers;
1024   // skip exp. coeffs we are not interested in
1025   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * idx;
1026   // the first exponentiated coefficient is the public key share
1027   GNUNET_CRYPTO_mpi_scan_unsigned (&exp_coeff, pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1028   return exp_coeff;
1029 }
1030
1031
1032 static struct GNUNET_CRYPTO_PaillierCiphertext *
1033 keygen_reveal_get_enc_preshare (struct KeygenSession *ks,
1034                                 const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
1035                                 unsigned int idx)
1036 {
1037   unsigned char *pos;
1038
1039   GNUNET_assert (idx < ks->num_peers);
1040
1041   pos = (void *) &d[1];
1042   // skip exponentiated pre-shares
1043   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers;
1044   // skip encrypted pre-shares we're not interested in
1045   pos += sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * idx;
1046   return (struct GNUNET_CRYPTO_PaillierCiphertext *) pos;
1047 }
1048
1049
1050 static void
1051 keygen_round2_new_element (void *cls,
1052                            const struct GNUNET_SET_Element *element)
1053 {
1054   struct KeygenSession *ks = cls;
1055   const struct GNUNET_SECRETSHARING_KeygenRevealData *d;
1056   struct KeygenPeerInfo *info;
1057   size_t expected_element_size;
1058   unsigned int j;
1059   int cmp_result;
1060   gcry_mpi_t tmp;
1061   gcry_mpi_t public_key_share;
1062   gcry_mpi_t preshare;
1063
1064   if (NULL == element)
1065   {
1066     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "round2 consensus failed\n");
1067     return;
1068   }
1069
1070   expected_element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
1071                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers +
1072                   sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers +
1073                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->threshold);
1074
1075   if (element->size != expected_element_size)
1076   {
1077     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1078                 "keygen round2 data with wrong size (%u) in consensus, "
1079                 " %u expected\n",
1080                 element->size, expected_element_size);
1081     return;
1082   }
1083
1084   d = (const void *) element->data;
1085
1086   info = get_keygen_peer_info (ks, &d->peer);
1087
1088   if (NULL == info)
1089   {
1090     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong peer identity (%s) in consensus\n",
1091                 GNUNET_i2s (&d->peer));
1092     return;
1093   }
1094
1095   if (GNUNET_NO == info->round1_valid)
1096   {
1097     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1098                 "ignoring round2 element from peer with invalid round1 element (%s)\n",
1099                 GNUNET_i2s (&d->peer));
1100     return;
1101   }
1102
1103   if (GNUNET_YES == info->round2_valid)
1104   {
1105     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1106                 "ignoring duplicate round2 element (%s)\n",
1107                 GNUNET_i2s (&d->peer));
1108     return;
1109   }
1110
1111   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round2 element\n");
1112
1113   if (ntohl (d->purpose.size) !=
1114       element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose))
1115   {
1116     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with wrong signature purpose size in consensus\n");
1117     return;
1118   }
1119
1120   if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2,
1121                                                &d->purpose, &d->signature, &d->peer.public_key))
1122   {
1123     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with invalid signature in consensus\n");
1124     return;
1125   }
1126
1127   public_key_share = keygen_reveal_get_exp_coeff (ks, d, 0);
1128   info->preshare_commitment = keygen_reveal_get_exp_preshare (ks, d, ks->local_peer_idx);
1129
1130   if (NULL == ks->public_key)
1131   {
1132     GNUNET_assert (NULL != (ks->public_key = gcry_mpi_new (0)));
1133     gcry_mpi_set_ui (ks->public_key, 1);
1134   }
1135   gcry_mpi_mulm (ks->public_key, ks->public_key, public_key_share, elgamal_p);
1136   
1137   gcry_mpi_release (public_key_share);
1138   public_key_share = NULL;
1139
1140   GNUNET_assert (NULL != (preshare = gcry_mpi_new (0)));
1141   GNUNET_CRYPTO_paillier_decrypt (&ks->paillier_private_key,
1142                                   &ks->info[ks->local_peer_idx].paillier_public_key,
1143                                   keygen_reveal_get_enc_preshare (ks, d, ks->local_peer_idx),
1144                                   preshare);
1145
1146   GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
1147   gcry_mpi_powm (tmp, elgamal_g, preshare, elgamal_p);
1148
1149   // TODO: restore a valid secret from the decryption (the hard part, solving SVP with gauss)
1150   cmp_result = gcry_mpi_cmp (tmp, info->preshare_commitment);
1151   gcry_mpi_release (tmp);
1152   tmp = NULL;
1153   if (0 != cmp_result)
1154   {
1155     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Got invalid presecret from P%u\n",
1156                 (unsigned int) ks->local_peer_idx, (unsigned int) (info - ks->info));
1157     return;
1158   }
1159
1160   if (NULL == ks->my_share)
1161   {
1162     GNUNET_assert (NULL != (ks->my_share = gcry_mpi_new (0)));
1163   }
1164   gcry_mpi_addm (ks->my_share, ks->my_share, preshare, elgamal_q);
1165
1166   for (j = 0; j < ks->num_peers; j++)
1167   {
1168     gcry_mpi_t presigma;
1169     if (NULL == ks->info[j].sigma)
1170     {
1171       GNUNET_assert (NULL != (ks->info[j].sigma = gcry_mpi_new (0)));
1172       gcry_mpi_set_ui (ks->info[j].sigma, 1);
1173     }
1174     presigma = keygen_reveal_get_exp_preshare (ks, d, j);
1175     gcry_mpi_mulm (ks->info[j].sigma, ks->info[j].sigma, presigma, elgamal_p);
1176     gcry_mpi_release (presigma);
1177   }
1178
1179   gcry_mpi_t prod;
1180   GNUNET_assert (NULL != (prod = gcry_mpi_new (0)));
1181   gcry_mpi_t j_to_k;
1182   GNUNET_assert (NULL != (j_to_k = gcry_mpi_new (0)));
1183   // validate that the polynomial sharing matches the additive sharing
1184   for (j = 0; j < ks->num_peers; j++)
1185   {
1186     unsigned int k;
1187     int cmp_result;
1188     gcry_mpi_t exp_preshare;
1189     gcry_mpi_set_ui (prod, 1);
1190     for (k = 0; k < ks->threshold; k++)
1191     {
1192       // Using pow(double,double) is a bit sketchy.
1193       // We count players from 1, but shares from 0.
1194       gcry_mpi_t tmp;
1195       gcry_mpi_set_ui (j_to_k, (unsigned int) pow(j+1, k)); 
1196       tmp = keygen_reveal_get_exp_coeff (ks, d, k);
1197       gcry_mpi_powm (tmp, tmp, j_to_k, elgamal_p);
1198       gcry_mpi_mulm (prod, prod, tmp, elgamal_p);
1199       gcry_mpi_release (tmp);
1200     }
1201     exp_preshare = keygen_reveal_get_exp_preshare (ks, d, j);
1202     gcry_mpi_mod (exp_preshare, exp_preshare, elgamal_p);
1203     cmp_result = gcry_mpi_cmp (prod, exp_preshare);
1204     gcry_mpi_release (exp_preshare);
1205     exp_preshare = NULL;
1206     if (0 != cmp_result)
1207     {
1208       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: reveal data from P%u incorrect\n",
1209                   ks->local_peer_idx, j);
1210       /* no need for further verification, round2 stays invalid ... */
1211       return;
1212     }
1213   }
1214
1215   // TODO: verify proof of fair encryption (once implemented)
1216   
1217   info->round2_valid = GNUNET_YES;
1218
1219   gcry_mpi_release (preshare);
1220   gcry_mpi_release (prod);
1221   gcry_mpi_release (j_to_k);
1222 }
1223
1224
1225 /**
1226  * Called when the first consensus round has concluded.
1227  * Will initiate the second round.
1228  *
1229  * @param cls closure
1230  */
1231 static void
1232 keygen_round1_conclude (void *cls)
1233 {
1234   struct KeygenSession *ks = cls;
1235
1236   GNUNET_CONSENSUS_destroy (ks->consensus);
1237
1238   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &ks->session_id,
1239                                            time_between (ks->start_time, ks->deadline, 1, 2),
1240                                            ks->deadline,
1241                                            keygen_round2_new_element, ks);
1242
1243   insert_round2_element (ks);
1244
1245   GNUNET_CONSENSUS_conclude (ks->consensus,
1246                              keygen_round2_conclude,
1247                              ks);
1248 }
1249
1250
1251 /**
1252  * Insert the ephemeral key and the presecret commitment
1253  * of this peer in the consensus of the given session.
1254  *
1255  * @param ks session to use
1256  */
1257 static void
1258 insert_round1_element (struct KeygenSession *ks)
1259 {
1260   struct GNUNET_SET_Element *element;
1261   struct GNUNET_SECRETSHARING_KeygenCommitData *d;
1262   // g^a_{i,0}
1263   gcry_mpi_t v;
1264   // big-endian representation of 'v'
1265   unsigned char v_data[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8];
1266
1267   element = GNUNET_malloc (sizeof *element + sizeof *d);
1268   d = (void *) &element[1];
1269   element->data = d;
1270   element->size = sizeof *d;
1271
1272   d->peer = my_peer;
1273
1274   GNUNET_assert (0 != (v = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
1275
1276   gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[0], elgamal_p);
1277
1278   GNUNET_CRYPTO_mpi_print_unsigned (v_data, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
1279
1280   GNUNET_CRYPTO_hash (v_data, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, &d->commitment);
1281
1282   d->pubkey = ks->info[ks->local_peer_idx].paillier_public_key;
1283
1284   d->purpose.size = htonl ((sizeof *d) - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose));
1285   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG1);
1286   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d->purpose, &d->signature));
1287
1288   GNUNET_CONSENSUS_insert (ks->consensus, element, NULL, NULL);
1289
1290   gcry_mpi_release (v);
1291   GNUNET_free (element);
1292 }
1293
1294
1295 /**
1296  * Functions with this signature are called whenever a message is
1297  * received.
1298  *
1299  * @param cls closure
1300  * @param client identification of the client
1301  * @param message the actual message
1302  */
1303 static void handle_client_keygen (void *cls,
1304                                   struct GNUNET_SERVER_Client *client,
1305                                   const struct GNUNET_MessageHeader
1306                                   *message)
1307 {
1308   const struct GNUNET_SECRETSHARING_CreateMessage *msg =
1309       (const struct GNUNET_SECRETSHARING_CreateMessage *) message;
1310   struct KeygenSession *ks;
1311   unsigned int i;
1312
1313   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "client requested key generation\n");
1314
1315   ks = GNUNET_new (struct KeygenSession);
1316
1317   /* FIXME: check if client already has some session */
1318
1319   GNUNET_CONTAINER_DLL_insert (keygen_sessions_head, keygen_sessions_tail, ks);
1320
1321   ks->client = client;
1322   ks->client_mq = GNUNET_MQ_queue_for_server_client (client);
1323
1324   ks->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
1325   ks->threshold = ntohs (msg->threshold);
1326   ks->num_peers = ntohs (msg->num_peers);
1327
1328   ks->peers = normalize_peers ((struct GNUNET_PeerIdentity *) &msg[1], ks->num_peers,
1329                                &ks->num_peers, &ks->local_peer_idx);
1330
1331
1332   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "first round of consensus with %u peers\n", ks->num_peers);
1333   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &msg->session_id,
1334                                            GNUNET_TIME_absolute_ntoh (msg->start),
1335                                            GNUNET_TIME_absolute_ntoh (msg->deadline),
1336                                            keygen_round1_new_element, ks);
1337
1338   ks->info = GNUNET_new_array (ks->num_peers, struct KeygenPeerInfo);
1339
1340   for (i = 0; i < ks->num_peers; i++)
1341     ks->info[i].peer = ks->peers[i];
1342
1343   GNUNET_CRYPTO_paillier_create (&ks->info[ks->local_peer_idx].paillier_public_key,
1344                                  &ks->paillier_private_key);
1345
1346   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Generated paillier key pair\n", ks->local_peer_idx);
1347
1348   generate_presecret_polynomial (ks);
1349
1350   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Generated presecret polynomial\n", ks->local_peer_idx);
1351
1352   insert_round1_element (ks);
1353
1354   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Concluding for round 1\n", ks->local_peer_idx);
1355
1356   GNUNET_CONSENSUS_conclude (ks->consensus,
1357                              keygen_round1_conclude,
1358                              ks);
1359
1360   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1361
1362   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Waiting for round 1 elements ...\n", ks->local_peer_idx);
1363 }
1364
1365
1366 /**
1367  * Called when the partial decryption consensus concludes.
1368  */
1369 static void
1370 decrypt_conclude (void *cls)
1371 {
1372   struct DecryptSession *ds = cls;
1373   struct GNUNET_SECRETSHARING_DecryptResponseMessage *msg;
1374   struct GNUNET_MQ_Envelope *ev;
1375   gcry_mpi_t lagrange;
1376   gcry_mpi_t m;
1377   gcry_mpi_t tmp;
1378   gcry_mpi_t c_2;
1379   gcry_mpi_t prod;
1380   unsigned int *indices;
1381   unsigned int num;
1382   unsigned int i;
1383   unsigned int j;
1384
1385   GNUNET_CONSENSUS_destroy (ds->consensus);
1386   ds->consensus = NULL;
1387
1388   GNUNET_assert (0 != (lagrange = gcry_mpi_new (0)));
1389   GNUNET_assert (0 != (m = gcry_mpi_new (0)));
1390   GNUNET_assert (0 != (tmp = gcry_mpi_new (0)));
1391   GNUNET_assert (0 != (prod = gcry_mpi_new (0)));
1392
1393   num = 0;
1394   for (i = 0; i < ds->share->num_peers; i++)
1395     if (NULL != ds->info[i].partial_decryption)
1396       num++;
1397
1398   indices = GNUNET_malloc (num * sizeof (unsigned int));
1399   j = 0;
1400   for (i = 0; i < ds->share->num_peers; i++)
1401     if (NULL != ds->info[i].partial_decryption)
1402       indices[j++] = ds->info[i].original_index;
1403
1404   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: decrypt conclude, with %u peers\n",
1405               ds->share->my_peer, num);
1406
1407   gcry_mpi_set_ui (prod, 1);
1408   for (i = 0; i < num; i++)
1409   {
1410
1411     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: index of %u: %u\n",
1412                 ds->share->my_peer, i, indices[i]);
1413     compute_lagrange_coefficient (lagrange, indices[i], indices, num);
1414     // w_i^{\lambda_i}
1415     gcry_mpi_powm (tmp, ds->info[indices[i]].partial_decryption, lagrange, elgamal_p);
1416
1417     // product of all exponentiated partiel decryptions ...
1418     gcry_mpi_mulm (prod, prod, tmp, elgamal_p);
1419   }
1420
1421   GNUNET_CRYPTO_mpi_scan_unsigned (&c_2, ds->ciphertext.c2_bits, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1422
1423   GNUNET_assert (0 != gcry_mpi_invm (prod, prod, elgamal_p));
1424   gcry_mpi_mulm (m, c_2, prod, elgamal_p);
1425   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT_DONE);
1426   GNUNET_CRYPTO_mpi_print_unsigned (&msg->plaintext, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, m);
1427   msg->success = htonl (1);
1428   GNUNET_MQ_send (ds->client_mq, ev);
1429
1430   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "sent decrypt done to client\n");
1431
1432   // FIXME: what if not enough peers participated?
1433 }
1434
1435
1436 /**
1437  * Get a string representation of an MPI.
1438  * The caller must free the returned string.
1439  *
1440  * @param mpi mpi to convert to a string
1441  * @return string representation of @a mpi, must be free'd by the caller
1442  */
1443 static char *
1444 mpi_to_str (gcry_mpi_t mpi)
1445 {
1446   unsigned char *buf;
1447
1448   GNUNET_assert (0 == gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buf, NULL, mpi));
1449   return (char *) buf;
1450 }
1451
1452
1453 /**
1454  * Called when a new partial decryption arrives.
1455  */
1456 static void
1457 decrypt_new_element (void *cls,
1458                      const struct GNUNET_SET_Element *element)
1459 {
1460   struct DecryptSession *session = cls;
1461   const struct GNUNET_SECRETSHARING_DecryptData *d;
1462   struct DecryptPeerInfo *info;
1463   struct GNUNET_HashCode challenge_hash;
1464
1465   /* nizk response */
1466   gcry_mpi_t r;
1467   /* nizk challenge */
1468   gcry_mpi_t challenge;
1469   /* nizk commit1, g^\beta */
1470   gcry_mpi_t commit1;
1471   /* nizk commit2, c_1^\beta */
1472   gcry_mpi_t commit2;
1473   /* homomorphic commitment to the peer's share,
1474    * public key share */
1475   gcry_mpi_t sigma;
1476   /* partial decryption we received */
1477   gcry_mpi_t w;
1478   /* ciphertext component #1 */
1479   gcry_mpi_t c1;
1480   /* temporary variable (for comparision) #1 */
1481   gcry_mpi_t tmp1;
1482   /* temporary variable (for comparision) #2 */
1483   gcry_mpi_t tmp2;
1484
1485   if (NULL == element)
1486   {
1487     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decryption failed\n");
1488     /* FIXME: destroy */
1489     return;
1490   }
1491
1492   if (element->size != sizeof *d)
1493   {
1494     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "element of wrong size in decrypt consensus\n");
1495     return;
1496   }
1497
1498   d = element->data;
1499
1500   info = get_decrypt_peer_info (session, &d->peer);
1501   
1502   if (NULL == info)
1503   {
1504     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decrypt element from invalid peer (%s)\n",
1505                 GNUNET_i2s (&d->peer));
1506     return;
1507   }
1508
1509   if (NULL != info->partial_decryption)
1510   {
1511     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decrypt element duplicate\n",
1512                 GNUNET_i2s (&d->peer));
1513     return;
1514   }
1515
1516   if (0 != memcmp (&d->ciphertext, &session->ciphertext, sizeof (struct GNUNET_SECRETSHARING_Ciphertext)))
1517   {
1518     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: got decrypt element with non-matching ciphertext from P%u\n",
1519                 (unsigned int) session->share->my_peer, (unsigned int) (info - session->info));
1520
1521     return;
1522   }
1523
1524
1525   GNUNET_CRYPTO_hash (offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext) + (char *) d,
1526                       offsetof (struct GNUNET_SECRETSHARING_DecryptData, nizk_response) - 
1527                           offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext),
1528                       &challenge_hash);
1529
1530   GNUNET_CRYPTO_mpi_scan_unsigned (&challenge, &challenge_hash,
1531                                    sizeof (struct GNUNET_HashCode));
1532
1533   GNUNET_CRYPTO_mpi_scan_unsigned (&sigma, &session->share->sigmas[info - session->info],
1534                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1535
1536   GNUNET_CRYPTO_mpi_scan_unsigned (&c1, session->ciphertext.c1_bits,
1537                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1538
1539   GNUNET_CRYPTO_mpi_scan_unsigned (&commit1, &d->nizk_commit1,
1540                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1541
1542   GNUNET_CRYPTO_mpi_scan_unsigned (&commit2, &d->nizk_commit2,
1543                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1544
1545   GNUNET_CRYPTO_mpi_scan_unsigned (&r, &d->nizk_response,
1546                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1547
1548   GNUNET_CRYPTO_mpi_scan_unsigned (&w, &d->partial_decryption,
1549                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1550
1551   GNUNET_assert (NULL != (tmp1 = gcry_mpi_new (0)));
1552   GNUNET_assert (NULL != (tmp2 = gcry_mpi_new (0)));
1553
1554   // tmp1 = g^r
1555   gcry_mpi_powm (tmp1, elgamal_g, r, elgamal_p);
1556
1557   // tmp2 = g^\beta * \sigma^challenge
1558   gcry_mpi_powm (tmp2, sigma, challenge, elgamal_p);
1559   gcry_mpi_mulm (tmp2, tmp2, commit1, elgamal_p);
1560
1561   if (0 != gcry_mpi_cmp (tmp1, tmp2))
1562   {
1563     char *tmp1_str;
1564     char *tmp2_str;
1565     tmp1_str = mpi_to_str (tmp1);
1566     tmp2_str = mpi_to_str (tmp2);
1567     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Received invalid partial decryption from P%u (eqn 1), expected %s got %s\n",
1568                 session->share->my_peer, info - session->info, tmp1_str, tmp2_str);
1569     GNUNET_free (tmp1_str);
1570     GNUNET_free (tmp2_str);
1571     // return;
1572   }
1573
1574
1575   gcry_mpi_powm (tmp1, c1, r, elgamal_p);
1576
1577   gcry_mpi_powm (tmp2, w, challenge, elgamal_p);
1578   gcry_mpi_mulm (tmp2, tmp2, commit2, elgamal_p);
1579
1580
1581   if (0 != gcry_mpi_cmp (tmp1, tmp2))
1582   {
1583     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Received invalid partial decryption from P%u (eqn 2)\n",
1584                 session->share->my_peer, info - session->info);
1585     // return;
1586   }
1587
1588
1589   GNUNET_CRYPTO_mpi_scan_unsigned (&info->partial_decryption, &d->partial_decryption,
1590                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1591 }
1592
1593
1594 static void
1595 insert_decrypt_element (struct DecryptSession *ds)
1596 {
1597   struct GNUNET_SECRETSHARING_DecryptData d;
1598   struct GNUNET_SET_Element element;
1599   /* our share */
1600   gcry_mpi_t s;
1601   /* partial decryption with our share */
1602   gcry_mpi_t w;
1603   /* first component of the elgamal ciphertext */
1604   gcry_mpi_t c1;
1605   /* nonce for dlog zkp */
1606   gcry_mpi_t beta;
1607   gcry_mpi_t tmp;
1608   gcry_mpi_t challenge;
1609   gcry_mpi_t sigma;
1610   struct GNUNET_HashCode challenge_hash;
1611
1612   /* make vagrind happy until we implement the real deal ... */
1613   memset (&d, 0, sizeof d);
1614
1615   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting decrypt element\n",
1616               ds->share->my_peer);
1617
1618   GNUNET_assert (ds->share->my_peer < ds->share->num_peers);
1619
1620   GNUNET_CRYPTO_mpi_scan_unsigned (&c1, &ds->ciphertext.c1_bits,
1621                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1622   GNUNET_CRYPTO_mpi_scan_unsigned (&s, &ds->share->my_share,
1623                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1624   GNUNET_CRYPTO_mpi_scan_unsigned (&sigma, &ds->share->sigmas[ds->share->my_peer],
1625                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1626
1627   GNUNET_assert (NULL != (w = gcry_mpi_new (0)));
1628   GNUNET_assert (NULL != (beta = gcry_mpi_new (0)));
1629   GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
1630
1631   // FIXME: unnecessary, remove once crypto works
1632   gcry_mpi_powm (tmp, elgamal_g, s, elgamal_p);
1633   if (0 != gcry_mpi_cmp (tmp, sigma))
1634   {
1635     char *sigma_str = mpi_to_str (sigma);
1636     char *tmp_str = mpi_to_str (tmp);
1637     char *s_str = mpi_to_str (s);
1638     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Share of P%u is invalid, ref sigma %s, "
1639                 "computed sigma %s, s %s\n",
1640                 ds->share->my_peer,
1641                 sigma_str, tmp_str, s_str);
1642     GNUNET_free (sigma_str);
1643     GNUNET_free (tmp_str);
1644     GNUNET_free (s_str);
1645   }
1646
1647   gcry_mpi_powm (w, c1, s, elgamal_p);
1648
1649   element.data = (void *) &d;
1650   element.size = sizeof (struct GNUNET_SECRETSHARING_DecryptData);
1651   element.type = 0;
1652
1653   d.ciphertext = ds->ciphertext;
1654   d.peer = my_peer;
1655   GNUNET_CRYPTO_mpi_print_unsigned (&d.partial_decryption, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, w);
1656
1657   // create the zero knowledge proof
1658   // randomly choose beta such that 0 < beta < q
1659   do 
1660   {
1661     gcry_mpi_randomize (beta, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
1662   } while ((gcry_mpi_cmp_ui (beta, 0) == 0) || (gcry_mpi_cmp (beta, elgamal_q) >= 0));
1663   // tmp = g^beta
1664   gcry_mpi_powm (tmp, elgamal_g, beta, elgamal_p);
1665   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_commit1, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
1666   // tmp = (c_1)^beta
1667   gcry_mpi_powm (tmp, c1, beta, elgamal_p);
1668   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_commit2, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
1669
1670   // the challenge is the hash of everything up to the response
1671   GNUNET_CRYPTO_hash (offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext) + (char *) &d,
1672                       offsetof (struct GNUNET_SECRETSHARING_DecryptData, nizk_response) - 
1673                           offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext),
1674                       &challenge_hash);
1675
1676   GNUNET_CRYPTO_mpi_scan_unsigned (&challenge, &challenge_hash,
1677                                    sizeof (struct GNUNET_HashCode));
1678
1679   // compute the response in tmp,
1680   // tmp = (c * s + beta) mod q
1681   gcry_mpi_mulm (tmp, challenge, s, elgamal_q);
1682   gcry_mpi_addm (tmp, tmp, beta, elgamal_q);
1683
1684   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_response, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
1685
1686   d.purpose.size = htonl (element.size - offsetof (struct GNUNET_SECRETSHARING_DecryptData, purpose));
1687   d.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DECRYPTION);
1688   
1689   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d.purpose, &d.signature);
1690
1691   GNUNET_CONSENSUS_insert (ds->consensus, &element, NULL, NULL);
1692   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting decrypt element done!\n",
1693               ds->share->my_peer);
1694 }
1695
1696
1697 /**
1698  * Functions with this signature are called whenever a message is
1699  * received.
1700  *
1701  * @param cls closure
1702  * @param client identification of the client
1703  * @param message the actual message
1704  */
1705 static void handle_client_decrypt (void *cls,
1706                                    struct GNUNET_SERVER_Client *client,
1707                                    const struct GNUNET_MessageHeader
1708                                    *message)
1709 {
1710   const struct GNUNET_SECRETSHARING_DecryptRequestMessage *msg =
1711       (const void *) message;
1712   struct DecryptSession *ds;
1713   struct GNUNET_HashCode session_id;
1714   unsigned int i;
1715
1716   ds = GNUNET_new (struct DecryptSession);
1717   // FIXME: check if session already exists
1718   GNUNET_CONTAINER_DLL_insert (decrypt_sessions_head, decrypt_sessions_tail, ds);
1719   ds->client = client;
1720   ds->client_mq = GNUNET_MQ_queue_for_server_client (client);
1721   ds->start = GNUNET_TIME_absolute_ntoh (msg->start);
1722   ds->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
1723   ds->ciphertext = msg->ciphertext;
1724
1725   ds->share = GNUNET_SECRETSHARING_share_read (&msg[1], ntohs (msg->header.size) - sizeof *msg, NULL);
1726   // FIXME: probably should be break rather than assert
1727   GNUNET_assert (NULL != ds->share);
1728
1729   // FIXME: this is probably sufficient, but kdf/hash with all values would be nicer ...
1730   GNUNET_CRYPTO_hash (&msg->ciphertext, sizeof (struct GNUNET_SECRETSHARING_Ciphertext), &session_id);
1731
1732   ds->consensus = GNUNET_CONSENSUS_create (cfg,
1733                                            ds->share->num_peers,
1734                                            ds->share->peers,
1735                                            &session_id,
1736                                            ds->start,
1737                                            ds->deadline,
1738                                            &decrypt_new_element,
1739                                            ds);
1740
1741
1742   ds->info = GNUNET_new_array (ds->share->num_peers, struct DecryptPeerInfo);
1743   for (i = 0; i < ds->share->num_peers; i++)
1744   {
1745     ds->info[i].peer = ds->share->peers[i];
1746     ds->info[i].original_index = ds->share->original_indices[i];
1747   }
1748
1749   insert_decrypt_element (ds);
1750
1751   GNUNET_CONSENSUS_conclude (ds->consensus, decrypt_conclude, ds);
1752
1753   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1754
1755   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "decrypting with %u peers\n",
1756               ds->share->num_peers);
1757 }
1758
1759
1760 static void
1761 init_crypto_constants (void)
1762 {
1763   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_q, GCRYMPI_FMT_HEX,
1764                                      GNUNET_SECRETSHARING_ELGAMAL_Q_HEX, 0, NULL));
1765   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_p, GCRYMPI_FMT_HEX,
1766                                      GNUNET_SECRETSHARING_ELGAMAL_P_HEX, 0, NULL));
1767   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_g, GCRYMPI_FMT_HEX,
1768                                      GNUNET_SECRETSHARING_ELGAMAL_G_HEX, 0, NULL));
1769 }
1770
1771
1772 static struct KeygenSession *
1773 keygen_session_get (struct GNUNET_SERVER_Client *client)
1774 {
1775   struct KeygenSession *ks;
1776   for (ks = keygen_sessions_head; NULL != ks; ks = ks->next)
1777     if (ks->client == client)
1778       return ks;
1779   return NULL;
1780 }
1781
1782 static struct DecryptSession *
1783 decrypt_session_get (struct GNUNET_SERVER_Client *client)
1784 {
1785   struct DecryptSession *ds;
1786   for (ds = decrypt_sessions_head; NULL != ds; ds = ds->next)
1787     if (ds->client == client)
1788       return ds;
1789   return NULL;
1790 }
1791
1792
1793 /**
1794  * Clean up after a client has disconnected
1795  *
1796  * @param cls closure, unused
1797  * @param client the client to clean up after
1798  */
1799 static void
1800 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1801 {
1802   struct KeygenSession *ks;
1803   struct DecryptSession *ds;
1804
1805   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handling client disconnect\n");
1806
1807   ks = keygen_session_get (client);
1808   if (NULL != ks)
1809     keygen_session_destroy (ks);
1810
1811   ds = decrypt_session_get (client);
1812   if (NULL != ds)
1813     decrypt_session_destroy (ds);
1814 }
1815
1816
1817 /**
1818  * Process template requests.
1819  *
1820  * @param cls closure
1821  * @param server the initialized server
1822  * @param c configuration to use
1823  */
1824 static void
1825 run (void *cls, struct GNUNET_SERVER_Handle *server,
1826      const struct GNUNET_CONFIGURATION_Handle *c)
1827 {
1828   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1829     {handle_client_keygen, NULL, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_GENERATE, 0},
1830     {handle_client_decrypt, NULL, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT, 0},
1831     {NULL, NULL, 0, 0}
1832   };
1833   cfg = c;
1834   srv = server;
1835   my_peer_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
1836   if (NULL == my_peer_private_key)
1837   {
1838     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not access host private key\n");
1839     GNUNET_break (0);
1840     GNUNET_SCHEDULER_shutdown ();
1841     return;
1842   }
1843   init_crypto_constants ();
1844   if (GNUNET_OK != GNUNET_CRYPTO_get_peer_identity (cfg, &my_peer))
1845   {
1846     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not retrieve host identity\n");
1847     GNUNET_break (0);
1848     GNUNET_SCHEDULER_shutdown ();
1849     return;
1850   }
1851   GNUNET_SERVER_add_handlers (server, handlers);
1852   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1853   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1854                                 NULL);
1855 }
1856
1857
1858 /**
1859  * The main function for the template service.
1860  *
1861  * @param argc number of arguments from the command line
1862  * @param argv command line arguments
1863  * @return 0 ok, 1 on error
1864  */
1865 int
1866 main (int argc, char *const *argv)
1867 {
1868   return (GNUNET_OK ==
1869           GNUNET_SERVICE_run (argc, argv, "secretsharing",
1870                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1871 }
1872