rename element's type field to 'element_type'
[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->info)
562   {
563     unsigned int i;
564     for (i = 0; i < ds->share->num_peers; i++)
565     {
566       if (NULL != ds->info[i].partial_decryption)
567       {
568         gcry_mpi_release (ds->info[i].partial_decryption);
569         ds->info[i].partial_decryption = NULL;
570       }
571     }
572     GNUNET_free (ds->info);
573     ds->info = NULL;
574   }
575
576   if (NULL != ds->share)
577   {
578     GNUNET_SECRETSHARING_share_destroy (ds->share);
579     ds->share = NULL;
580   }
581
582   if (NULL != ds->client_mq)
583   {
584     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying decrypt MQ\n");
585     GNUNET_MQ_destroy (ds->client_mq);
586     ds->client_mq = NULL;
587   }
588
589   if (NULL != ds->client)
590   {
591     GNUNET_SERVER_client_disconnect (ds->client);
592     ds->client = NULL;
593   }
594
595   GNUNET_free (ds);
596 }
597
598 static void
599 keygen_info_destroy (struct KeygenPeerInfo *info)
600 {
601   if (NULL != info->sigma)
602   {
603     gcry_mpi_release (info->sigma);
604     info->sigma = NULL;
605   }
606   if (NULL != info->presecret_commitment)
607   {
608     gcry_mpi_release (info->presecret_commitment);
609     info->presecret_commitment = NULL;
610   }
611   if (NULL != info->preshare_commitment)
612   {
613     gcry_mpi_release (info->preshare_commitment);
614     info->presecret_commitment = NULL;
615   }
616 }
617
618
619 static void
620 keygen_session_destroy (struct KeygenSession *ks)
621 {
622   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying keygen session\n");
623
624   GNUNET_CONTAINER_DLL_remove (keygen_sessions_head, keygen_sessions_tail, ks);
625
626   if (NULL != ks->info)
627   {
628     unsigned int i;
629     for (i = 0; i < ks->num_peers; i++)
630       keygen_info_destroy (&ks->info[i]);
631     GNUNET_free (ks->info);
632     ks->info = NULL;
633   }
634
635   if (NULL != ks->consensus)
636   {
637     GNUNET_CONSENSUS_destroy (ks->consensus);
638     ks->consensus = NULL;
639   }
640
641   if (NULL != ks->presecret_polynomial)
642   {
643     unsigned int i;
644     for (i = 0; i < ks->threshold; i++)
645     {
646       GNUNET_assert (NULL != ks->presecret_polynomial[i]);
647       gcry_mpi_release (ks->presecret_polynomial[i]);
648       ks->presecret_polynomial[i] = NULL;
649     }
650     GNUNET_free (ks->presecret_polynomial);
651     ks->presecret_polynomial = NULL;
652   }
653
654   if (NULL != ks->client_mq)
655   {
656     GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "destroying keygen MQ\n");
657     GNUNET_MQ_destroy (ks->client_mq);
658     ks->client_mq = NULL;
659   }
660
661   if (NULL != ks->my_share)
662   {
663     gcry_mpi_release (ks->my_share);
664     ks->my_share = NULL;
665   }
666
667   if (NULL != ks->public_key)
668   {
669     gcry_mpi_release (ks->public_key);
670     ks->public_key = NULL;
671   }
672
673   if (NULL != ks->peers)
674   {
675     GNUNET_free (ks->peers);
676     ks->peers = NULL;
677   }
678
679   if (NULL != ks->client)
680   {
681     GNUNET_SERVER_client_disconnect (ks->client);
682     ks->client = NULL;
683   }
684
685   GNUNET_free (ks);
686 }
687
688
689 /**
690  * Task run during shutdown.
691  *
692  * @param cls unused
693  * @param tc unused
694  */
695 static void
696 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
697 {
698   while (NULL != decrypt_sessions_head)
699     decrypt_session_destroy (decrypt_sessions_head);
700
701   while (NULL != keygen_sessions_head)
702     keygen_session_destroy (keygen_sessions_head);
703 }
704
705
706
707 /**
708  * Generate the random coefficients of our pre-secret polynomial
709  *
710  * @param ks the session
711  */
712 static void
713 generate_presecret_polynomial (struct KeygenSession *ks)
714 {
715   int i;
716   gcry_mpi_t v;
717
718   GNUNET_assert (NULL == ks->presecret_polynomial);
719   ks->presecret_polynomial = GNUNET_new_array (ks->threshold, gcry_mpi_t);
720   for (i = 0; i < ks->threshold; i++)
721   {
722     v = ks->presecret_polynomial[i] = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS);
723     GNUNET_assert (NULL != v);
724     // Randomize v such that 0 < v < elgamal_q.
725     // The '- 1' is necessary as bitlength(q) = bitlength(p) - 1.
726     do
727     {
728       gcry_mpi_randomize (v, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
729     } while ((gcry_mpi_cmp_ui (v, 0) == 0) || (gcry_mpi_cmp (v, elgamal_q) >= 0));
730   }
731 }
732
733
734 /**
735  * Consensus element handler for round one.
736  * We should get one ephemeral key for each peer.
737  *
738  * @param cls Closure (keygen session).
739  * @param element The element from consensus, or
740  *                NULL if consensus failed.
741  */
742 static void
743 keygen_round1_new_element (void *cls,
744                            const struct GNUNET_SET_Element *element)
745 {
746   const struct GNUNET_SECRETSHARING_KeygenCommitData *d;
747   struct KeygenSession *ks = cls;
748   struct KeygenPeerInfo *info;
749
750   if (NULL == element)
751   {
752     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "round1 consensus failed\n");
753     return;
754   }
755
756   /* elements have fixed size */
757   if (element->size != sizeof (struct GNUNET_SECRETSHARING_KeygenCommitData))
758   {
759     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
760                 "keygen commit data with wrong size (%u) in consensus, "
761                 " %u expected\n",
762                 element->size, sizeof (struct GNUNET_SECRETSHARING_KeygenCommitData));
763     return;
764   }
765
766   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round1 element\n");
767
768   d = element->data;
769   info = get_keygen_peer_info (ks, &d->peer);
770
771   if (NULL == info)
772   {
773     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong peer identity (%s) in consensus\n",
774                 GNUNET_i2s (&d->peer));
775     return;
776   }
777
778   /* Check that the right amount of data has been signed. */
779   if (d->purpose.size !=
780       htonl (element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose)))
781   {
782     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong signature purpose size in consensus\n");
783     return;
784   }
785
786   if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG1,
787                                                &d->purpose, &d->signature, &d->peer.public_key))
788   {
789     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with invalid signature in consensus\n");
790     return;
791   }
792   info->paillier_public_key = d->pubkey;
793   GNUNET_CRYPTO_mpi_scan_unsigned (&info->presecret_commitment, &d->commitment, 512 / 8);
794   info->round1_valid = GNUNET_YES;
795 }
796
797
798 /**
799  * Evaluate the polynomial with coefficients @a coeff at @a x.
800  * The i-th element in @a coeff corresponds to the coefficient of x^i.
801  *
802  * @param[out] z result of the evaluation
803  * @param coeff array of coefficients
804  * @param num_coeff number of coefficients
805  * @param x where to evaluate the polynomial
806  * @param m what group are we operating in?
807  */
808 static void
809 horner_eval (gcry_mpi_t z, gcry_mpi_t *coeff, unsigned int num_coeff, gcry_mpi_t x, gcry_mpi_t m)
810 {
811   unsigned int i;
812
813   gcry_mpi_set_ui (z, 0);
814   for (i = 0; i < num_coeff; i++)
815   {
816     // z <- zx + c
817     gcry_mpi_mul (z, z, x);
818     gcry_mpi_addm (z, z, coeff[num_coeff - i - 1], m);
819   }
820 }
821
822
823 static void
824 keygen_round2_conclude (void *cls)
825 {
826   struct KeygenSession *ks = cls;
827   struct GNUNET_SECRETSHARING_SecretReadyMessage *m;
828   struct GNUNET_MQ_Envelope *ev;
829   size_t share_size;
830   unsigned int i;
831   unsigned int j;
832   struct GNUNET_SECRETSHARING_Share *share;
833
834   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "round2 conclude\n");
835
836   GNUNET_CONSENSUS_destroy (ks->consensus);
837   ks->consensus = NULL;
838
839   share = GNUNET_new (struct GNUNET_SECRETSHARING_Share);
840
841   share->num_peers = 0;
842
843   for (i = 0; i < ks->num_peers; i++)
844     if (GNUNET_YES == ks->info[i].round2_valid)
845       share->num_peers++;
846
847   share->peers = GNUNET_new_array (share->num_peers, struct GNUNET_PeerIdentity);
848   share->sigmas =
849       GNUNET_new_array (share->num_peers, struct GNUNET_SECRETSHARING_FieldElement);
850   share->original_indices = GNUNET_new_array (share->num_peers, uint16_t);
851
852   /* maybe we're not even in the list of peers? */
853   share->my_peer = share->num_peers;
854
855   j = 0; /* running index of valid peers */
856   for (i = 0; i < ks->num_peers; i++)
857   {
858     if (GNUNET_YES == ks->info[i].round2_valid)
859     {
860       share->peers[j] = ks->info[i].peer;
861       GNUNET_CRYPTO_mpi_print_unsigned (&share->sigmas[j],
862                                         GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
863                                         ks->info[i].sigma);
864       share->original_indices[i] = j;
865       if (0 == memcmp (&share->peers[i], &my_peer, sizeof (struct GNUNET_PeerIdentity)))
866         share->my_peer = j;
867       j += 1;
868     }
869   }
870
871   if (share->my_peer == share->num_peers)
872   {
873     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: peer identity not in share\n", ks->local_peer_idx);
874   }
875
876   GNUNET_CRYPTO_mpi_print_unsigned (&share->my_share, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
877                                     ks->my_share);
878   GNUNET_CRYPTO_mpi_print_unsigned (&share->public_key, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
879                                     ks->public_key);
880
881   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "keygen completed with %u peers\n", share->num_peers);
882
883   /* Write the share. If 0 peers completed the dkg, an empty
884    * share will be sent. */
885
886   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, NULL, 0, &share_size));
887
888   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "writing share of size %u\n",
889               (unsigned int) share_size);
890
891   ev = GNUNET_MQ_msg_extra (m, share_size,
892                             GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_SECRET_READY);
893
894   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, &m[1], share_size, NULL));
895
896   GNUNET_SECRETSHARING_share_destroy (share);
897   share = NULL;
898
899   GNUNET_MQ_send (ks->client_mq, ev);
900 }
901
902
903
904 static void
905 restore_fair (const struct GNUNET_CRYPTO_PaillierPublicKey *ppub,
906               const struct GNUNET_SECRETSHARING_FairEncryption *fe,
907               gcry_mpi_t x, gcry_mpi_t xres)
908 {
909   gcry_mpi_t a_1;
910   gcry_mpi_t a_2;
911   gcry_mpi_t b_1;
912   gcry_mpi_t b_2;
913   gcry_mpi_t big_a;
914   gcry_mpi_t big_b;
915   gcry_mpi_t big_t;
916   gcry_mpi_t n;
917   gcry_mpi_t t_1;
918   gcry_mpi_t t_2;
919   gcry_mpi_t t;
920   gcry_mpi_t r;
921   gcry_mpi_t v;
922
923
924   GNUNET_assert (NULL != (n = gcry_mpi_new (0)));
925   GNUNET_assert (NULL != (t = gcry_mpi_new (0)));
926   GNUNET_assert (NULL != (t_1 = gcry_mpi_new (0)));
927   GNUNET_assert (NULL != (t_2 = gcry_mpi_new (0)));
928   GNUNET_assert (NULL != (r = gcry_mpi_new (0)));
929   GNUNET_assert (NULL != (big_t = gcry_mpi_new (0)));
930   GNUNET_assert (NULL != (v = gcry_mpi_new (0)));
931   GNUNET_assert (NULL != (big_a = gcry_mpi_new (0)));
932   GNUNET_assert (NULL != (big_b = gcry_mpi_new (0)));
933
934   // a = (N,0)^T
935   GNUNET_CRYPTO_mpi_scan_unsigned (&a_1, ppub, sizeof (struct GNUNET_CRYPTO_PaillierPublicKey));
936   GNUNET_assert (NULL != (a_2 = gcry_mpi_new (0)));
937   gcry_mpi_set_ui (a_2, 0);
938   // b = (x,1)^T
939   GNUNET_assert (NULL != (b_1 = gcry_mpi_new (0)));
940   gcry_mpi_set (b_1, x);
941   GNUNET_assert (NULL != (b_2 = gcry_mpi_new (0)));
942   gcry_mpi_set_ui (b_2, 1);
943
944   // A = a DOT a
945   gcry_mpi_mul (t, a_1, a_1);
946   gcry_mpi_mul (big_a, a_2, a_2);
947   gcry_mpi_add (big_a, big_a, t);
948
949   // B = b DOT b
950   gcry_mpi_mul (t, b_1, b_1);
951   gcry_mpi_mul (big_b, b_2, b_2);
952   gcry_mpi_add (big_b, big_b, t);
953
954   while (1)
955   {
956     // n = a DOT b
957     gcry_mpi_mul (t, a_1, b_1);
958     gcry_mpi_mul (n, a_2, b_2);
959     gcry_mpi_add (n, n, t);
960
961     // r = nearest(n/B)
962     gcry_mpi_div (r, NULL, n, big_b, 0);
963
964     // T := A - 2rn + rrB
965     gcry_mpi_mul (v, r, n);
966     gcry_mpi_mul_ui (v, v, 2);
967     gcry_mpi_sub (big_t, big_a, v);
968     gcry_mpi_mul (v, r, r);
969     gcry_mpi_mul (v, v, big_b);
970     gcry_mpi_add (big_t, big_t, v);
971
972     if (gcry_mpi_cmp (big_t, big_b) >= 0)
973     {
974       break;
975     }
976
977     // t = a - rb
978     gcry_mpi_mul (v, r, b_1);
979     gcry_mpi_sub (t_1, a_1, v);
980     gcry_mpi_mul (v, r, b_2);
981     gcry_mpi_sub (t_2, a_2, v);
982
983     // a = b
984     gcry_mpi_set (a_1, b_1);
985     gcry_mpi_set (a_2, b_2);
986     // b = t
987     gcry_mpi_set (b_1, t_1);
988     gcry_mpi_set (b_2, t_2);
989
990     gcry_mpi_set (big_a, big_b);
991     gcry_mpi_set (big_b, big_t);
992   }
993
994   {
995     gcry_mpi_t paillier_n;
996
997     GNUNET_CRYPTO_mpi_scan_unsigned (&paillier_n, ppub, sizeof (struct GNUNET_CRYPTO_PaillierPublicKey));
998
999     gcry_mpi_set (xres, b_2);
1000     gcry_mpi_invm (xres, xres, elgamal_q);
1001     gcry_mpi_mulm (xres, xres, b_1, elgamal_q);
1002   }
1003
1004   gcry_mpi_release (a_1);
1005   gcry_mpi_release (a_2);
1006   gcry_mpi_release (b_1);
1007   gcry_mpi_release (b_2);
1008   gcry_mpi_release (big_a);
1009   gcry_mpi_release (big_b);
1010   gcry_mpi_release (big_t);
1011   gcry_mpi_release (n);
1012   gcry_mpi_release (t_1);
1013   gcry_mpi_release (t_2);
1014   gcry_mpi_release (t);
1015   gcry_mpi_release (r);
1016   gcry_mpi_release (v);
1017 }
1018
1019
1020 static void
1021 get_fair_encryption_challenge (const struct GNUNET_SECRETSHARING_FairEncryption *fe, gcry_mpi_t e)
1022 {
1023   struct {
1024     struct GNUNET_CRYPTO_PaillierCiphertext c;
1025     char h[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8];
1026     char t1[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8];
1027     char t2[GNUNET_CRYPTO_PAILLIER_BITS * 2 / 8];
1028   } hash_data;
1029   struct GNUNET_HashCode e_hash;
1030
1031   memcpy (&hash_data.c, &fe->c, sizeof (struct GNUNET_CRYPTO_PaillierCiphertext));
1032   memcpy (&hash_data.h, &fe->h, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1033   memcpy (&hash_data.t1, &fe->t1, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1034   memcpy (&hash_data.t2, &fe->t2, GNUNET_CRYPTO_PAILLIER_BITS * 2 / 8);
1035
1036   GNUNET_CRYPTO_mpi_scan_unsigned (&e, &e_hash, sizeof (struct GNUNET_HashCode));
1037   gcry_mpi_mod (e, e, elgamal_q);
1038 }
1039
1040
1041 static int
1042 verify_fair (const struct GNUNET_CRYPTO_PaillierPublicKey *ppub, const struct GNUNET_SECRETSHARING_FairEncryption *fe)
1043 {
1044   gcry_mpi_t n;
1045   gcry_mpi_t n_sq;
1046   gcry_mpi_t z;
1047   gcry_mpi_t t1;
1048   gcry_mpi_t t2;
1049   gcry_mpi_t e;
1050   gcry_mpi_t w;
1051   gcry_mpi_t tmp1;
1052   gcry_mpi_t tmp2;
1053   gcry_mpi_t y;
1054   gcry_mpi_t big_y;
1055   int res;
1056
1057   GNUNET_assert (NULL != (n_sq = gcry_mpi_new (0)));
1058   GNUNET_assert (NULL != (tmp1 = gcry_mpi_new (0)));
1059   GNUNET_assert (NULL != (tmp2 = gcry_mpi_new (0)));
1060   GNUNET_assert (NULL != (e = gcry_mpi_new (0)));
1061
1062   get_fair_encryption_challenge (fe, e);
1063
1064   GNUNET_CRYPTO_mpi_scan_unsigned (&n, ppub, sizeof (struct GNUNET_CRYPTO_PaillierPublicKey));
1065   GNUNET_CRYPTO_mpi_scan_unsigned (&t1, fe->t1, GNUNET_CRYPTO_PAILLIER_BITS / 8);
1066   GNUNET_CRYPTO_mpi_scan_unsigned (&z, fe->z, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1067   GNUNET_CRYPTO_mpi_scan_unsigned (&y, fe->h, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1068   GNUNET_CRYPTO_mpi_scan_unsigned (&w, fe->w, GNUNET_CRYPTO_PAILLIER_BITS / 8);
1069   GNUNET_CRYPTO_mpi_scan_unsigned (&big_y, fe->c.bits, GNUNET_CRYPTO_PAILLIER_BITS * 2 / 8);
1070   GNUNET_CRYPTO_mpi_scan_unsigned (&t2, fe->t2, GNUNET_CRYPTO_PAILLIER_BITS * 2 / 8);
1071   gcry_mpi_mul (n_sq, n, n);
1072
1073   // tmp1 = g^z
1074   gcry_mpi_powm (tmp1, elgamal_g, z, elgamal_p);
1075   // tmp2 = y^{-e}
1076   gcry_mpi_powm (tmp1, y, e, elgamal_p);
1077   gcry_mpi_invm (tmp1, tmp1, elgamal_p);
1078   // tmp1 = tmp1 * tmp2
1079   gcry_mpi_mulm (tmp1, tmp1, tmp2, elgamal_p);
1080
1081   if (0 == gcry_mpi_cmp (t1, tmp1))
1082   {
1083     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "fair encryption invalid (t1)\n");
1084     res = GNUNET_NO;
1085     goto cleanup;
1086   }
1087
1088   gcry_mpi_powm (big_y, big_y, e, n_sq);
1089   gcry_mpi_invm (big_y, big_y, n_sq);
1090
1091   gcry_mpi_add_ui (tmp1, n, 1);
1092   gcry_mpi_powm (tmp1, tmp1, z, n_sq);
1093
1094   gcry_mpi_powm (tmp2, w, n, n_sq);
1095
1096   gcry_mpi_mulm (tmp1, tmp1, tmp2, n_sq);
1097   gcry_mpi_mulm (tmp1, tmp1, big_y, n_sq);
1098
1099
1100   if (0 == gcry_mpi_cmp (t2, tmp1))
1101   {
1102     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "fair encryption invalid (t2)\n");
1103     res = GNUNET_NO;
1104     goto cleanup;
1105   }
1106
1107   res = GNUNET_YES;
1108
1109 cleanup:
1110
1111   gcry_mpi_release (n);
1112   gcry_mpi_release (n_sq);
1113   gcry_mpi_release (z);
1114   gcry_mpi_release (t1);
1115   gcry_mpi_release (t2);
1116   gcry_mpi_release (e);
1117   gcry_mpi_release (w);
1118   gcry_mpi_release (tmp1);
1119   gcry_mpi_release (tmp2);
1120   gcry_mpi_release (y);
1121   gcry_mpi_release (big_y);
1122   return res;
1123 }
1124
1125
1126 /**
1127  * Create a fair Paillier encryption of then given ciphertext.
1128  *
1129  * @param v the ciphertext
1130  * @param[out] fe the fair encryption
1131  */
1132 static void
1133 encrypt_fair (gcry_mpi_t v, const struct GNUNET_CRYPTO_PaillierPublicKey *ppub, struct GNUNET_SECRETSHARING_FairEncryption *fe)
1134 {
1135   gcry_mpi_t r;
1136   gcry_mpi_t s;
1137   gcry_mpi_t t1;
1138   gcry_mpi_t t2;
1139   gcry_mpi_t z;
1140   gcry_mpi_t w;
1141   gcry_mpi_t n;
1142   gcry_mpi_t e;
1143   gcry_mpi_t n_sq;
1144   gcry_mpi_t u;
1145   gcry_mpi_t Y;
1146   gcry_mpi_t G;
1147   gcry_mpi_t h;
1148   GNUNET_assert (NULL != (r = gcry_mpi_new (0)));
1149   GNUNET_assert (NULL != (s = gcry_mpi_new (0)));
1150   GNUNET_assert (NULL != (t1 = gcry_mpi_new (0)));
1151   GNUNET_assert (NULL != (t2 = gcry_mpi_new (0)));
1152   GNUNET_assert (NULL != (z = gcry_mpi_new (0)));
1153   GNUNET_assert (NULL != (w = gcry_mpi_new (0)));
1154   GNUNET_assert (NULL != (n_sq = gcry_mpi_new (0)));
1155   GNUNET_assert (NULL != (e = gcry_mpi_new (0)));
1156   GNUNET_assert (NULL != (u = gcry_mpi_new (0)));
1157   GNUNET_assert (NULL != (Y = gcry_mpi_new (0)));
1158   GNUNET_assert (NULL != (G = gcry_mpi_new (0)));
1159   GNUNET_assert (NULL != (h = gcry_mpi_new (0)));
1160
1161   GNUNET_CRYPTO_mpi_scan_unsigned (&n, ppub, sizeof (struct GNUNET_CRYPTO_PaillierPublicKey));
1162   gcry_mpi_mul (n_sq, n, n);
1163   gcry_mpi_add_ui (G, n, 1);
1164
1165   do {
1166     gcry_mpi_randomize (u, GNUNET_CRYPTO_PAILLIER_BITS, GCRY_WEAK_RANDOM);
1167   }
1168   while (gcry_mpi_cmp (u, n) >= 0);
1169
1170   gcry_mpi_powm (t1, G, v, n_sq);
1171   gcry_mpi_powm (t2, u, n, n_sq);
1172   gcry_mpi_mulm (Y, t1, t2, n_sq);
1173
1174   GNUNET_CRYPTO_mpi_print_unsigned (fe->c.bits,
1175                                     sizeof fe->c.bits,
1176                                     Y);
1177
1178
1179   gcry_mpi_randomize (r, 2048, GCRY_WEAK_RANDOM);
1180   do {
1181     gcry_mpi_randomize (s, GNUNET_CRYPTO_PAILLIER_BITS, GCRY_WEAK_RANDOM);
1182   }
1183   while (gcry_mpi_cmp (s, n) >= 0);
1184
1185   // compute t1
1186   gcry_mpi_mulm (t1, elgamal_g, r, elgamal_p);
1187   // compute t2 (use z and w as temp)
1188   gcry_mpi_powm (z, G, r, n_sq);
1189   gcry_mpi_powm (w, s, n, n_sq);
1190   gcry_mpi_mulm (t2, z, w, n_sq);
1191
1192
1193   gcry_mpi_powm (h, elgamal_g, v, elgamal_p);
1194
1195   GNUNET_CRYPTO_mpi_print_unsigned (fe->h,
1196                                     GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
1197                                     h);
1198
1199   GNUNET_CRYPTO_mpi_print_unsigned (fe->t1,
1200                                     GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
1201                                     t1);
1202
1203   GNUNET_CRYPTO_mpi_print_unsigned (fe->t2,
1204                                     GNUNET_CRYPTO_PAILLIER_BITS * 2 / 8,
1205                                     t2);
1206
1207
1208   get_fair_encryption_challenge (fe, e);
1209
1210   // compute z
1211   gcry_mpi_mul (z, e, v);
1212   gcry_mpi_addm (z, z, r, elgamal_q);
1213   // compute w
1214   gcry_mpi_powm (w, u, e, n);
1215   gcry_mpi_mulm (w, w, s, n);
1216
1217   GNUNET_CRYPTO_mpi_print_unsigned (fe->z,
1218                                     GNUNET_SECRETSHARING_ELGAMAL_BITS / 8,
1219                                     z);
1220
1221   GNUNET_CRYPTO_mpi_print_unsigned (fe->w,
1222                                     GNUNET_CRYPTO_PAILLIER_BITS / 8,
1223                                     w);
1224
1225   gcry_mpi_release (n);
1226   gcry_mpi_release (r);
1227   gcry_mpi_release (s);
1228   gcry_mpi_release (t1);
1229   gcry_mpi_release (t2);
1230   gcry_mpi_release (z);
1231   gcry_mpi_release (w);
1232   gcry_mpi_release (e);
1233   gcry_mpi_release (n_sq);
1234   gcry_mpi_release (u);
1235   gcry_mpi_release (Y);
1236   gcry_mpi_release (G);
1237   gcry_mpi_release (h);
1238 }
1239
1240
1241 /**
1242  * Insert round 2 element in the consensus, consisting of
1243  * (1) The exponentiated pre-share polynomial coefficients A_{i,l}=g^{a_{i,l}}
1244  * (2) The exponentiated pre-shares y_{i,j}=g^{s_{i,j}}
1245  * (3) The encrypted pre-shares Y_{i,j}
1246  * (4) The zero knowledge proof for fairness of
1247  *     the encryption
1248  *
1249  * @param ks session to use
1250  */
1251 static void
1252 insert_round2_element (struct KeygenSession *ks)
1253 {
1254   struct GNUNET_SET_Element *element;
1255   struct GNUNET_SECRETSHARING_KeygenRevealData *d;
1256   unsigned char *pos;
1257   unsigned char *last_pos;
1258   size_t element_size;
1259   unsigned int i;
1260   gcry_mpi_t idx;
1261   gcry_mpi_t v;
1262
1263   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting round2 element\n",
1264               ks->local_peer_idx);
1265
1266   GNUNET_assert (NULL != (v = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
1267   GNUNET_assert (NULL != (idx = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
1268
1269   element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
1270                   sizeof (struct GNUNET_SECRETSHARING_FairEncryption) * ks->num_peers +
1271                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->threshold);
1272
1273   element = GNUNET_malloc (sizeof (struct GNUNET_SET_Element) + element_size);
1274   element->size = element_size;
1275   element->data = (void *) &element[1];
1276
1277   d = (void *) element->data;
1278   d->peer = my_peer;
1279
1280   // start inserting vector elements
1281   // after the fixed part of the element's data
1282   pos = (void *) &d[1];
1283   last_pos = pos + element_size;
1284
1285   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed exp preshares\n",
1286               ks->local_peer_idx);
1287
1288   // encrypted pre-shares
1289   // and fair encryption proof
1290   {
1291     for (i = 0; i < ks->num_peers; i++)
1292     {
1293       ptrdiff_t remaining = last_pos - pos;
1294       struct GNUNET_SECRETSHARING_FairEncryption *fe = (void *) pos;
1295
1296       GNUNET_assert (remaining > 0);
1297       memset (fe, 0, sizeof *fe);
1298       if (GNUNET_YES == ks->info[i].round1_valid)
1299       {
1300         gcry_mpi_set_ui (idx, i + 1);
1301         // evaluate the polynomial
1302         horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_q);
1303         // encrypt the result
1304         encrypt_fair (v, &ks->info[i].paillier_public_key, fe);
1305       }
1306       pos += sizeof *fe;
1307     }
1308   }
1309
1310   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed enc preshares\n",
1311               ks->local_peer_idx);
1312
1313   // exponentiated coefficients
1314   for (i = 0; i < ks->threshold; i++)
1315   {
1316     ptrdiff_t remaining = last_pos - pos;
1317     GNUNET_assert (remaining > 0);
1318     gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[i], elgamal_p);
1319     GNUNET_CRYPTO_mpi_print_unsigned (pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
1320     pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8;
1321   }
1322
1323   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed exp coefficients\n",
1324               ks->local_peer_idx);
1325
1326
1327   d->purpose.size = htonl (element_size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose));
1328   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2);
1329   GNUNET_assert (GNUNET_OK ==
1330                  GNUNET_CRYPTO_eddsa_sign (my_peer_private_key,
1331                                            &d->purpose,
1332                                            &d->signature));
1333
1334   GNUNET_CONSENSUS_insert (ks->consensus, element, NULL, NULL);
1335   GNUNET_free (element); /* FIXME: maybe stack-allocate instead? */
1336
1337   gcry_mpi_release (v);
1338   gcry_mpi_release (idx);
1339 }
1340
1341
1342 static gcry_mpi_t
1343 keygen_reveal_get_exp_coeff (struct KeygenSession *ks,
1344                              const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
1345                              unsigned int idx)
1346 {
1347   unsigned char *pos;
1348   gcry_mpi_t exp_coeff;
1349
1350   GNUNET_assert (idx < ks->threshold);
1351
1352   pos = (void *) &d[1];
1353   // skip encrypted pre-shares
1354   pos += sizeof (struct GNUNET_SECRETSHARING_FairEncryption) * ks->num_peers;
1355   // skip exp. coeffs we are not interested in
1356   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * idx;
1357   // the first exponentiated coefficient is the public key share
1358   GNUNET_CRYPTO_mpi_scan_unsigned (&exp_coeff, pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1359   return exp_coeff;
1360 }
1361
1362
1363 static struct GNUNET_SECRETSHARING_FairEncryption *
1364 keygen_reveal_get_enc_preshare (struct KeygenSession *ks,
1365                                 const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
1366                                 unsigned int idx)
1367 {
1368   unsigned char *pos;
1369
1370   GNUNET_assert (idx < ks->num_peers);
1371
1372   pos = (void *) &d[1];
1373   // skip encrypted pre-shares we're not interested in
1374   pos += sizeof (struct GNUNET_SECRETSHARING_FairEncryption) * idx;
1375   return (struct GNUNET_SECRETSHARING_FairEncryption *) pos;
1376 }
1377
1378
1379 static gcry_mpi_t
1380 keygen_reveal_get_exp_preshare (struct KeygenSession *ks,
1381                                 const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
1382                                 unsigned int idx)
1383 {
1384   gcry_mpi_t exp_preshare;
1385   struct GNUNET_SECRETSHARING_FairEncryption *fe;
1386
1387   GNUNET_assert (idx < ks->num_peers);
1388   fe = keygen_reveal_get_enc_preshare (ks, d, idx);
1389   GNUNET_CRYPTO_mpi_scan_unsigned (&exp_preshare, fe->h, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1390   return exp_preshare;
1391 }
1392
1393
1394 static void
1395 keygen_round2_new_element (void *cls,
1396                            const struct GNUNET_SET_Element *element)
1397 {
1398   struct KeygenSession *ks = cls;
1399   const struct GNUNET_SECRETSHARING_KeygenRevealData *d;
1400   struct KeygenPeerInfo *info;
1401   size_t expected_element_size;
1402   unsigned int j;
1403   int cmp_result;
1404   gcry_mpi_t tmp;
1405   gcry_mpi_t public_key_share;
1406   gcry_mpi_t preshare;
1407
1408   if (NULL == element)
1409   {
1410     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "round2 consensus failed\n");
1411     return;
1412   }
1413
1414   expected_element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
1415                   sizeof (struct GNUNET_SECRETSHARING_FairEncryption) * ks->num_peers +
1416                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->threshold);
1417
1418   if (element->size != expected_element_size)
1419   {
1420     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1421                 "keygen round2 data with wrong size (%u) in consensus, "
1422                 " %u expected\n",
1423                 element->size, expected_element_size);
1424     return;
1425   }
1426
1427   d = (const void *) element->data;
1428
1429   info = get_keygen_peer_info (ks, &d->peer);
1430
1431   if (NULL == info)
1432   {
1433     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong peer identity (%s) in consensus\n",
1434                 GNUNET_i2s (&d->peer));
1435     return;
1436   }
1437
1438   if (GNUNET_NO == info->round1_valid)
1439   {
1440     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1441                 "ignoring round2 element from peer with invalid round1 element (%s)\n",
1442                 GNUNET_i2s (&d->peer));
1443     return;
1444   }
1445
1446   if (GNUNET_YES == info->round2_valid)
1447   {
1448     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1449                 "ignoring duplicate round2 element (%s)\n",
1450                 GNUNET_i2s (&d->peer));
1451     return;
1452   }
1453
1454   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round2 element\n");
1455
1456   if (ntohl (d->purpose.size) !=
1457       element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose))
1458   {
1459     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with wrong signature purpose size in consensus\n");
1460     return;
1461   }
1462
1463   if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2,
1464                                                &d->purpose, &d->signature, &d->peer.public_key))
1465   {
1466     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with invalid signature in consensus\n");
1467     return;
1468   }
1469
1470   public_key_share = keygen_reveal_get_exp_coeff (ks, d, 0);
1471   info->preshare_commitment = keygen_reveal_get_exp_preshare (ks, d, ks->local_peer_idx);
1472
1473   if (NULL == ks->public_key)
1474   {
1475     GNUNET_assert (NULL != (ks->public_key = gcry_mpi_new (0)));
1476     gcry_mpi_set_ui (ks->public_key, 1);
1477   }
1478   gcry_mpi_mulm (ks->public_key, ks->public_key, public_key_share, elgamal_p);
1479
1480   gcry_mpi_release (public_key_share);
1481   public_key_share = NULL;
1482
1483   {
1484     struct GNUNET_SECRETSHARING_FairEncryption *fe = keygen_reveal_get_enc_preshare (ks, d, ks->local_peer_idx);
1485     GNUNET_assert (NULL != (preshare = gcry_mpi_new (0)));
1486     GNUNET_CRYPTO_paillier_decrypt (&ks->paillier_private_key,
1487                                     &ks->info[ks->local_peer_idx].paillier_public_key,
1488                                     &fe->c,
1489                                     preshare);
1490
1491     // FIXME: not doing the restoration is less expensive
1492     restore_fair (&ks->info[ks->local_peer_idx].paillier_public_key,
1493                   fe,
1494                   preshare,
1495                   preshare);
1496   }
1497
1498   GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
1499   gcry_mpi_powm (tmp, elgamal_g, preshare, elgamal_p);
1500
1501   cmp_result = gcry_mpi_cmp (tmp, info->preshare_commitment);
1502   gcry_mpi_release (tmp);
1503   tmp = NULL;
1504   if (0 != cmp_result)
1505   {
1506     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Got invalid presecret from P%u\n",
1507                 (unsigned int) ks->local_peer_idx, (unsigned int) (info - ks->info));
1508     return;
1509   }
1510
1511   if (NULL == ks->my_share)
1512   {
1513     GNUNET_assert (NULL != (ks->my_share = gcry_mpi_new (0)));
1514   }
1515   gcry_mpi_addm (ks->my_share, ks->my_share, preshare, elgamal_q);
1516
1517   for (j = 0; j < ks->num_peers; j++)
1518   {
1519     gcry_mpi_t presigma;
1520     if (NULL == ks->info[j].sigma)
1521     {
1522       GNUNET_assert (NULL != (ks->info[j].sigma = gcry_mpi_new (0)));
1523       gcry_mpi_set_ui (ks->info[j].sigma, 1);
1524     }
1525     presigma = keygen_reveal_get_exp_preshare (ks, d, j);
1526     gcry_mpi_mulm (ks->info[j].sigma, ks->info[j].sigma, presigma, elgamal_p);
1527     gcry_mpi_release (presigma);
1528   }
1529
1530   gcry_mpi_t prod;
1531   GNUNET_assert (NULL != (prod = gcry_mpi_new (0)));
1532   gcry_mpi_t j_to_k;
1533   GNUNET_assert (NULL != (j_to_k = gcry_mpi_new (0)));
1534   // validate that the polynomial sharing matches the additive sharing
1535   for (j = 0; j < ks->num_peers; j++)
1536   {
1537     unsigned int k;
1538     int cmp_result;
1539     gcry_mpi_t exp_preshare;
1540     gcry_mpi_set_ui (prod, 1);
1541     for (k = 0; k < ks->threshold; k++)
1542     {
1543       // Using pow(double,double) is a bit sketchy.
1544       // We count players from 1, but shares from 0.
1545       gcry_mpi_t tmp;
1546       gcry_mpi_set_ui (j_to_k, (unsigned int) pow(j+1, k));
1547       tmp = keygen_reveal_get_exp_coeff (ks, d, k);
1548       gcry_mpi_powm (tmp, tmp, j_to_k, elgamal_p);
1549       gcry_mpi_mulm (prod, prod, tmp, elgamal_p);
1550       gcry_mpi_release (tmp);
1551     }
1552     exp_preshare = keygen_reveal_get_exp_preshare (ks, d, j);
1553     gcry_mpi_mod (exp_preshare, exp_preshare, elgamal_p);
1554     cmp_result = gcry_mpi_cmp (prod, exp_preshare);
1555     gcry_mpi_release (exp_preshare);
1556     exp_preshare = NULL;
1557     if (0 != cmp_result)
1558     {
1559       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: reveal data from P%u incorrect\n",
1560                   ks->local_peer_idx, j);
1561       /* no need for further verification, round2 stays invalid ... */
1562       return;
1563     }
1564   }
1565
1566   // TODO: verify proof of fair encryption (once implemented)
1567   for (j = 0; j < ks->num_peers; j++)
1568   {
1569     struct GNUNET_SECRETSHARING_FairEncryption *fe = keygen_reveal_get_enc_preshare (ks, d, j);
1570     if (GNUNET_YES != verify_fair (&ks->info[j].paillier_public_key, fe))
1571     {
1572       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: reveal data from P%u incorrect (fair encryption)\n",
1573                   ks->local_peer_idx, j);
1574       return;
1575     }
1576
1577   }
1578
1579   info->round2_valid = GNUNET_YES;
1580
1581   gcry_mpi_release (preshare);
1582   gcry_mpi_release (prod);
1583   gcry_mpi_release (j_to_k);
1584 }
1585
1586
1587 /**
1588  * Called when the first consensus round has concluded.
1589  * Will initiate the second round.
1590  *
1591  * @param cls closure
1592  */
1593 static void
1594 keygen_round1_conclude (void *cls)
1595 {
1596   struct KeygenSession *ks = cls;
1597
1598   GNUNET_CONSENSUS_destroy (ks->consensus);
1599
1600   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &ks->session_id,
1601                                            time_between (ks->start_time, ks->deadline, 1, 2),
1602                                            ks->deadline,
1603                                            keygen_round2_new_element, ks);
1604
1605   insert_round2_element (ks);
1606
1607   GNUNET_CONSENSUS_conclude (ks->consensus,
1608                              keygen_round2_conclude,
1609                              ks);
1610 }
1611
1612
1613 /**
1614  * Insert the ephemeral key and the presecret commitment
1615  * of this peer in the consensus of the given session.
1616  *
1617  * @param ks session to use
1618  */
1619 static void
1620 insert_round1_element (struct KeygenSession *ks)
1621 {
1622   struct GNUNET_SET_Element *element;
1623   struct GNUNET_SECRETSHARING_KeygenCommitData *d;
1624   // g^a_{i,0}
1625   gcry_mpi_t v;
1626   // big-endian representation of 'v'
1627   unsigned char v_data[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8];
1628
1629   element = GNUNET_malloc (sizeof *element + sizeof *d);
1630   d = (void *) &element[1];
1631   element->data = d;
1632   element->size = sizeof *d;
1633
1634   d->peer = my_peer;
1635
1636   GNUNET_assert (0 != (v = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
1637
1638   gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[0], elgamal_p);
1639
1640   GNUNET_CRYPTO_mpi_print_unsigned (v_data, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
1641
1642   GNUNET_CRYPTO_hash (v_data, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, &d->commitment);
1643
1644   d->pubkey = ks->info[ks->local_peer_idx].paillier_public_key;
1645
1646   d->purpose.size = htonl ((sizeof *d) - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose));
1647   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG1);
1648   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d->purpose, &d->signature));
1649
1650   GNUNET_CONSENSUS_insert (ks->consensus, element, NULL, NULL);
1651
1652   gcry_mpi_release (v);
1653   GNUNET_free (element);
1654 }
1655
1656
1657 /**
1658  * Functions with this signature are called whenever a message is
1659  * received.
1660  *
1661  * @param cls closure
1662  * @param client identification of the client
1663  * @param message the actual message
1664  */
1665 static void handle_client_keygen (void *cls,
1666                                   struct GNUNET_SERVER_Client *client,
1667                                   const struct GNUNET_MessageHeader
1668                                   *message)
1669 {
1670   const struct GNUNET_SECRETSHARING_CreateMessage *msg =
1671       (const struct GNUNET_SECRETSHARING_CreateMessage *) message;
1672   struct KeygenSession *ks;
1673   unsigned int i;
1674
1675   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "client requested key generation\n");
1676
1677   ks = GNUNET_new (struct KeygenSession);
1678
1679   /* FIXME: check if client already has some session */
1680
1681   GNUNET_CONTAINER_DLL_insert (keygen_sessions_head, keygen_sessions_tail, ks);
1682
1683   ks->client = client;
1684   ks->client_mq = GNUNET_MQ_queue_for_server_client (client);
1685
1686   ks->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
1687   ks->threshold = ntohs (msg->threshold);
1688   ks->num_peers = ntohs (msg->num_peers);
1689
1690   ks->peers = normalize_peers ((struct GNUNET_PeerIdentity *) &msg[1], ks->num_peers,
1691                                &ks->num_peers, &ks->local_peer_idx);
1692
1693
1694   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "first round of consensus with %u peers\n", ks->num_peers);
1695   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &msg->session_id,
1696                                            GNUNET_TIME_absolute_ntoh (msg->start),
1697                                            GNUNET_TIME_absolute_ntoh (msg->deadline),
1698                                            keygen_round1_new_element, ks);
1699
1700   ks->info = GNUNET_new_array (ks->num_peers, struct KeygenPeerInfo);
1701
1702   for (i = 0; i < ks->num_peers; i++)
1703     ks->info[i].peer = ks->peers[i];
1704
1705   GNUNET_CRYPTO_paillier_create (&ks->info[ks->local_peer_idx].paillier_public_key,
1706                                  &ks->paillier_private_key);
1707
1708   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Generated paillier key pair\n", ks->local_peer_idx);
1709
1710   generate_presecret_polynomial (ks);
1711
1712   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Generated presecret polynomial\n", ks->local_peer_idx);
1713
1714   insert_round1_element (ks);
1715
1716   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Concluding for round 1\n", ks->local_peer_idx);
1717
1718   GNUNET_CONSENSUS_conclude (ks->consensus,
1719                              keygen_round1_conclude,
1720                              ks);
1721
1722   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1723
1724   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Waiting for round 1 elements ...\n", ks->local_peer_idx);
1725 }
1726
1727
1728 /**
1729  * Called when the partial decryption consensus concludes.
1730  */
1731 static void
1732 decrypt_conclude (void *cls)
1733 {
1734   struct DecryptSession *ds = cls;
1735   struct GNUNET_SECRETSHARING_DecryptResponseMessage *msg;
1736   struct GNUNET_MQ_Envelope *ev;
1737   gcry_mpi_t lagrange;
1738   gcry_mpi_t m;
1739   gcry_mpi_t tmp;
1740   gcry_mpi_t c_2;
1741   gcry_mpi_t prod;
1742   unsigned int *indices;
1743   unsigned int num;
1744   unsigned int i;
1745   unsigned int j;
1746
1747   GNUNET_CONSENSUS_destroy (ds->consensus);
1748   ds->consensus = NULL;
1749
1750   GNUNET_assert (0 != (lagrange = gcry_mpi_new (0)));
1751   GNUNET_assert (0 != (m = gcry_mpi_new (0)));
1752   GNUNET_assert (0 != (tmp = gcry_mpi_new (0)));
1753   GNUNET_assert (0 != (prod = gcry_mpi_new (0)));
1754
1755   num = 0;
1756   for (i = 0; i < ds->share->num_peers; i++)
1757     if (NULL != ds->info[i].partial_decryption)
1758       num++;
1759
1760   indices = GNUNET_malloc (num * sizeof (unsigned int));
1761   j = 0;
1762   for (i = 0; i < ds->share->num_peers; i++)
1763     if (NULL != ds->info[i].partial_decryption)
1764       indices[j++] = ds->info[i].original_index;
1765
1766   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: decrypt conclude, with %u peers\n",
1767               ds->share->my_peer, num);
1768
1769   gcry_mpi_set_ui (prod, 1);
1770   for (i = 0; i < num; i++)
1771   {
1772
1773     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: index of %u: %u\n",
1774                 ds->share->my_peer, i, indices[i]);
1775     compute_lagrange_coefficient (lagrange, indices[i], indices, num);
1776     // w_i^{\lambda_i}
1777     gcry_mpi_powm (tmp, ds->info[indices[i]].partial_decryption, lagrange, elgamal_p);
1778
1779     // product of all exponentiated partiel decryptions ...
1780     gcry_mpi_mulm (prod, prod, tmp, elgamal_p);
1781   }
1782
1783   GNUNET_CRYPTO_mpi_scan_unsigned (&c_2, ds->ciphertext.c2_bits, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1784
1785   GNUNET_assert (0 != gcry_mpi_invm (prod, prod, elgamal_p));
1786   gcry_mpi_mulm (m, c_2, prod, elgamal_p);
1787   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT_DONE);
1788   GNUNET_CRYPTO_mpi_print_unsigned (&msg->plaintext, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, m);
1789   msg->success = htonl (1);
1790   GNUNET_MQ_send (ds->client_mq, ev);
1791
1792   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "sent decrypt done to client\n");
1793
1794   GNUNET_free (indices);
1795
1796   gcry_mpi_release(lagrange);
1797   gcry_mpi_release(m);
1798   gcry_mpi_release(tmp);
1799   gcry_mpi_release(prod);
1800   gcry_mpi_release(c_2);
1801
1802   // FIXME: what if not enough peers participated?
1803 }
1804
1805
1806 /**
1807  * Get a string representation of an MPI.
1808  * The caller must free the returned string.
1809  *
1810  * @param mpi mpi to convert to a string
1811  * @return string representation of @a mpi, must be free'd by the caller
1812  */
1813 static char *
1814 mpi_to_str (gcry_mpi_t mpi)
1815 {
1816   unsigned char *buf;
1817
1818   GNUNET_assert (0 == gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buf, NULL, mpi));
1819   return (char *) buf;
1820 }
1821
1822
1823 /**
1824  * Called when a new partial decryption arrives.
1825  */
1826 static void
1827 decrypt_new_element (void *cls,
1828                      const struct GNUNET_SET_Element *element)
1829 {
1830   struct DecryptSession *session = cls;
1831   const struct GNUNET_SECRETSHARING_DecryptData *d;
1832   struct DecryptPeerInfo *info;
1833   struct GNUNET_HashCode challenge_hash;
1834
1835   /* nizk response */
1836   gcry_mpi_t r;
1837   /* nizk challenge */
1838   gcry_mpi_t challenge;
1839   /* nizk commit1, g^\beta */
1840   gcry_mpi_t commit1;
1841   /* nizk commit2, c_1^\beta */
1842   gcry_mpi_t commit2;
1843   /* homomorphic commitment to the peer's share,
1844    * public key share */
1845   gcry_mpi_t sigma;
1846   /* partial decryption we received */
1847   gcry_mpi_t w;
1848   /* ciphertext component #1 */
1849   gcry_mpi_t c1;
1850   /* temporary variable (for comparision) #1 */
1851   gcry_mpi_t tmp1;
1852   /* temporary variable (for comparision) #2 */
1853   gcry_mpi_t tmp2;
1854
1855   if (NULL == element)
1856   {
1857     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decryption failed\n");
1858     /* FIXME: destroy */
1859     return;
1860   }
1861
1862   if (element->size != sizeof *d)
1863   {
1864     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "element of wrong size in decrypt consensus\n");
1865     return;
1866   }
1867
1868   d = element->data;
1869
1870   info = get_decrypt_peer_info (session, &d->peer);
1871
1872   if (NULL == info)
1873   {
1874     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decrypt element from invalid peer (%s)\n",
1875                 GNUNET_i2s (&d->peer));
1876     return;
1877   }
1878
1879   if (NULL != info->partial_decryption)
1880   {
1881     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decrypt element duplicate\n",
1882                 GNUNET_i2s (&d->peer));
1883     return;
1884   }
1885
1886   if (0 != memcmp (&d->ciphertext, &session->ciphertext, sizeof (struct GNUNET_SECRETSHARING_Ciphertext)))
1887   {
1888     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: got decrypt element with non-matching ciphertext from P%u\n",
1889                 (unsigned int) session->share->my_peer, (unsigned int) (info - session->info));
1890
1891     return;
1892   }
1893
1894
1895   GNUNET_CRYPTO_hash (offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext) + (char *) d,
1896                       offsetof (struct GNUNET_SECRETSHARING_DecryptData, nizk_response) -
1897                           offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext),
1898                       &challenge_hash);
1899
1900   GNUNET_CRYPTO_mpi_scan_unsigned (&challenge, &challenge_hash,
1901                                    sizeof (struct GNUNET_HashCode));
1902
1903   GNUNET_CRYPTO_mpi_scan_unsigned (&sigma, &session->share->sigmas[info - session->info],
1904                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1905
1906   GNUNET_CRYPTO_mpi_scan_unsigned (&c1, session->ciphertext.c1_bits,
1907                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1908
1909   GNUNET_CRYPTO_mpi_scan_unsigned (&commit1, &d->nizk_commit1,
1910                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1911
1912   GNUNET_CRYPTO_mpi_scan_unsigned (&commit2, &d->nizk_commit2,
1913                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1914
1915   GNUNET_CRYPTO_mpi_scan_unsigned (&r, &d->nizk_response,
1916                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1917
1918   GNUNET_CRYPTO_mpi_scan_unsigned (&w, &d->partial_decryption,
1919                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1920
1921   GNUNET_assert (NULL != (tmp1 = gcry_mpi_new (0)));
1922   GNUNET_assert (NULL != (tmp2 = gcry_mpi_new (0)));
1923
1924   // tmp1 = g^r
1925   gcry_mpi_powm (tmp1, elgamal_g, r, elgamal_p);
1926
1927   // tmp2 = g^\beta * \sigma^challenge
1928   gcry_mpi_powm (tmp2, sigma, challenge, elgamal_p);
1929   gcry_mpi_mulm (tmp2, tmp2, commit1, elgamal_p);
1930
1931   if (0 != gcry_mpi_cmp (tmp1, tmp2))
1932   {
1933     char *tmp1_str;
1934     char *tmp2_str;
1935     tmp1_str = mpi_to_str (tmp1);
1936     tmp2_str = mpi_to_str (tmp2);
1937     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Received invalid partial decryption from P%u (eqn 1), expected %s got %s\n",
1938                 session->share->my_peer, info - session->info, tmp1_str, tmp2_str);
1939     GNUNET_free (tmp1_str);
1940     GNUNET_free (tmp2_str);
1941     goto cleanup;
1942   }
1943
1944
1945   gcry_mpi_powm (tmp1, c1, r, elgamal_p);
1946
1947   gcry_mpi_powm (tmp2, w, challenge, elgamal_p);
1948   gcry_mpi_mulm (tmp2, tmp2, commit2, elgamal_p);
1949
1950
1951   if (0 != gcry_mpi_cmp (tmp1, tmp2))
1952   {
1953     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Received invalid partial decryption from P%u (eqn 2)\n",
1954                 session->share->my_peer, info - session->info);
1955     goto cleanup;
1956   }
1957
1958
1959   GNUNET_CRYPTO_mpi_scan_unsigned (&info->partial_decryption, &d->partial_decryption,
1960                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1961 cleanup:
1962   gcry_mpi_release (tmp1);
1963   gcry_mpi_release (tmp2);
1964   gcry_mpi_release (sigma);
1965   gcry_mpi_release (commit1);
1966   gcry_mpi_release (commit2);
1967   gcry_mpi_release (r);
1968   gcry_mpi_release (w);
1969   gcry_mpi_release (challenge);
1970   gcry_mpi_release (c1);
1971 }
1972
1973
1974 static void
1975 insert_decrypt_element (struct DecryptSession *ds)
1976 {
1977   struct GNUNET_SECRETSHARING_DecryptData d;
1978   struct GNUNET_SET_Element element;
1979   /* our share */
1980   gcry_mpi_t s;
1981   /* partial decryption with our share */
1982   gcry_mpi_t w;
1983   /* first component of the elgamal ciphertext */
1984   gcry_mpi_t c1;
1985   /* nonce for dlog zkp */
1986   gcry_mpi_t beta;
1987   gcry_mpi_t tmp;
1988   gcry_mpi_t challenge;
1989   gcry_mpi_t sigma;
1990   struct GNUNET_HashCode challenge_hash;
1991
1992   /* make vagrind happy until we implement the real deal ... */
1993   memset (&d, 0, sizeof d);
1994
1995   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting decrypt element\n",
1996               ds->share->my_peer);
1997
1998   GNUNET_assert (ds->share->my_peer < ds->share->num_peers);
1999
2000   GNUNET_CRYPTO_mpi_scan_unsigned (&c1, &ds->ciphertext.c1_bits,
2001                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
2002   GNUNET_CRYPTO_mpi_scan_unsigned (&s, &ds->share->my_share,
2003                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
2004   GNUNET_CRYPTO_mpi_scan_unsigned (&sigma, &ds->share->sigmas[ds->share->my_peer],
2005                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
2006
2007   GNUNET_assert (NULL != (w = gcry_mpi_new (0)));
2008   GNUNET_assert (NULL != (beta = gcry_mpi_new (0)));
2009   GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
2010
2011   // FIXME: unnecessary, remove once crypto works
2012   gcry_mpi_powm (tmp, elgamal_g, s, elgamal_p);
2013   if (0 != gcry_mpi_cmp (tmp, sigma))
2014   {
2015     char *sigma_str = mpi_to_str (sigma);
2016     char *tmp_str = mpi_to_str (tmp);
2017     char *s_str = mpi_to_str (s);
2018     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Share of P%u is invalid, ref sigma %s, "
2019                 "computed sigma %s, s %s\n",
2020                 ds->share->my_peer,
2021                 sigma_str, tmp_str, s_str);
2022     GNUNET_free (sigma_str);
2023     GNUNET_free (tmp_str);
2024     GNUNET_free (s_str);
2025   }
2026
2027   gcry_mpi_powm (w, c1, s, elgamal_p);
2028
2029   element.data = (void *) &d;
2030   element.size = sizeof (struct GNUNET_SECRETSHARING_DecryptData);
2031   element.element_type = 0;
2032
2033   d.ciphertext = ds->ciphertext;
2034   d.peer = my_peer;
2035   GNUNET_CRYPTO_mpi_print_unsigned (&d.partial_decryption, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, w);
2036
2037   // create the zero knowledge proof
2038   // randomly choose beta such that 0 < beta < q
2039   do
2040   {
2041     gcry_mpi_randomize (beta, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
2042   } while ((gcry_mpi_cmp_ui (beta, 0) == 0) || (gcry_mpi_cmp (beta, elgamal_q) >= 0));
2043   // tmp = g^beta
2044   gcry_mpi_powm (tmp, elgamal_g, beta, elgamal_p);
2045   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_commit1, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
2046   // tmp = (c_1)^beta
2047   gcry_mpi_powm (tmp, c1, beta, elgamal_p);
2048   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_commit2, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
2049
2050   // the challenge is the hash of everything up to the response
2051   GNUNET_CRYPTO_hash (offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext) + (char *) &d,
2052                       offsetof (struct GNUNET_SECRETSHARING_DecryptData, nizk_response) -
2053                           offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext),
2054                       &challenge_hash);
2055
2056   GNUNET_CRYPTO_mpi_scan_unsigned (&challenge, &challenge_hash,
2057                                    sizeof (struct GNUNET_HashCode));
2058
2059   // compute the response in tmp,
2060   // tmp = (c * s + beta) mod q
2061   gcry_mpi_mulm (tmp, challenge, s, elgamal_q);
2062   gcry_mpi_addm (tmp, tmp, beta, elgamal_q);
2063
2064   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_response, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
2065
2066   d.purpose.size = htonl (element.size - offsetof (struct GNUNET_SECRETSHARING_DecryptData, purpose));
2067   d.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DECRYPTION);
2068
2069   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d.purpose, &d.signature);
2070
2071   GNUNET_CONSENSUS_insert (ds->consensus, &element, NULL, NULL);
2072   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting decrypt element done!\n",
2073               ds->share->my_peer);
2074
2075   gcry_mpi_release (s);
2076   gcry_mpi_release (w);
2077   gcry_mpi_release (c1);
2078   gcry_mpi_release (beta);
2079   gcry_mpi_release (tmp);
2080   gcry_mpi_release (challenge);
2081   gcry_mpi_release (sigma);
2082 }
2083
2084
2085 /**
2086  * Functions with this signature are called whenever a message is
2087  * received.
2088  *
2089  * @param cls closure
2090  * @param client identification of the client
2091  * @param message the actual message
2092  */
2093 static void handle_client_decrypt (void *cls,
2094                                    struct GNUNET_SERVER_Client *client,
2095                                    const struct GNUNET_MessageHeader
2096                                    *message)
2097 {
2098   const struct GNUNET_SECRETSHARING_DecryptRequestMessage *msg =
2099       (const void *) message;
2100   struct DecryptSession *ds;
2101   struct GNUNET_HashCode session_id;
2102   unsigned int i;
2103
2104   ds = GNUNET_new (struct DecryptSession);
2105   // FIXME: check if session already exists
2106   GNUNET_CONTAINER_DLL_insert (decrypt_sessions_head, decrypt_sessions_tail, ds);
2107   ds->client = client;
2108   ds->client_mq = GNUNET_MQ_queue_for_server_client (client);
2109   ds->start = GNUNET_TIME_absolute_ntoh (msg->start);
2110   ds->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
2111   ds->ciphertext = msg->ciphertext;
2112
2113   ds->share = GNUNET_SECRETSHARING_share_read (&msg[1], ntohs (msg->header.size) - sizeof *msg, NULL);
2114   // FIXME: probably should be break rather than assert
2115   GNUNET_assert (NULL != ds->share);
2116
2117   // FIXME: this is probably sufficient, but kdf/hash with all values would be nicer ...
2118   GNUNET_CRYPTO_hash (&msg->ciphertext, sizeof (struct GNUNET_SECRETSHARING_Ciphertext), &session_id);
2119
2120   ds->consensus = GNUNET_CONSENSUS_create (cfg,
2121                                            ds->share->num_peers,
2122                                            ds->share->peers,
2123                                            &session_id,
2124                                            ds->start,
2125                                            ds->deadline,
2126                                            &decrypt_new_element,
2127                                            ds);
2128
2129
2130   ds->info = GNUNET_new_array (ds->share->num_peers, struct DecryptPeerInfo);
2131   for (i = 0; i < ds->share->num_peers; i++)
2132   {
2133     ds->info[i].peer = ds->share->peers[i];
2134     ds->info[i].original_index = ds->share->original_indices[i];
2135   }
2136
2137   insert_decrypt_element (ds);
2138
2139   GNUNET_CONSENSUS_conclude (ds->consensus, decrypt_conclude, ds);
2140
2141   GNUNET_SERVER_receive_done (client, GNUNET_OK);
2142
2143   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "decrypting with %u peers\n",
2144               ds->share->num_peers);
2145 }
2146
2147
2148 static void
2149 init_crypto_constants (void)
2150 {
2151   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_q, GCRYMPI_FMT_HEX,
2152                                      GNUNET_SECRETSHARING_ELGAMAL_Q_HEX, 0, NULL));
2153   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_p, GCRYMPI_FMT_HEX,
2154                                      GNUNET_SECRETSHARING_ELGAMAL_P_HEX, 0, NULL));
2155   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_g, GCRYMPI_FMT_HEX,
2156                                      GNUNET_SECRETSHARING_ELGAMAL_G_HEX, 0, NULL));
2157 }
2158
2159
2160 static struct KeygenSession *
2161 keygen_session_get (struct GNUNET_SERVER_Client *client)
2162 {
2163   struct KeygenSession *ks;
2164   for (ks = keygen_sessions_head; NULL != ks; ks = ks->next)
2165     if (ks->client == client)
2166       return ks;
2167   return NULL;
2168 }
2169
2170 static struct DecryptSession *
2171 decrypt_session_get (struct GNUNET_SERVER_Client *client)
2172 {
2173   struct DecryptSession *ds;
2174   for (ds = decrypt_sessions_head; NULL != ds; ds = ds->next)
2175     if (ds->client == client)
2176       return ds;
2177   return NULL;
2178 }
2179
2180
2181 /**
2182  * Clean up after a client has disconnected
2183  *
2184  * @param cls closure, unused
2185  * @param client the client to clean up after
2186  */
2187 static void
2188 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
2189 {
2190   struct KeygenSession *ks;
2191   struct DecryptSession *ds;
2192
2193   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handling client disconnect\n");
2194
2195   ks = keygen_session_get (client);
2196   if (NULL != ks)
2197     keygen_session_destroy (ks);
2198
2199   ds = decrypt_session_get (client);
2200   if (NULL != ds)
2201     decrypt_session_destroy (ds);
2202 }
2203
2204
2205 /**
2206  * Process template requests.
2207  *
2208  * @param cls closure
2209  * @param server the initialized server
2210  * @param c configuration to use
2211  */
2212 static void
2213 run (void *cls, struct GNUNET_SERVER_Handle *server,
2214      const struct GNUNET_CONFIGURATION_Handle *c)
2215 {
2216   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
2217     {handle_client_keygen, NULL, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_GENERATE, 0},
2218     {handle_client_decrypt, NULL, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT, 0},
2219     {NULL, NULL, 0, 0}
2220   };
2221   cfg = c;
2222   srv = server;
2223   my_peer_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
2224   if (NULL == my_peer_private_key)
2225   {
2226     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not access host private key\n");
2227     GNUNET_break (0);
2228     GNUNET_SCHEDULER_shutdown ();
2229     return;
2230   }
2231   init_crypto_constants ();
2232   if (GNUNET_OK != GNUNET_CRYPTO_get_peer_identity (cfg, &my_peer))
2233   {
2234     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not retrieve host identity\n");
2235     GNUNET_break (0);
2236     GNUNET_SCHEDULER_shutdown ();
2237     return;
2238   }
2239   GNUNET_SERVER_add_handlers (server, handlers);
2240   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
2241   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
2242                                 NULL);
2243 }
2244
2245
2246 /**
2247  * The main function for the template service.
2248  *
2249  * @param argc number of arguments from the command line
2250  * @param argv command line arguments
2251  * @return 0 ok, 1 on error
2252  */
2253 int
2254 main (int argc, char *const *argv)
2255 {
2256   return (GNUNET_OK ==
2257           GNUNET_SERVICE_run (argc, argv, "secretsharing",
2258                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
2259 }
2260