- htons => htonl
[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 /**
37  * Info about a peer in a key generation session.
38  */
39 struct KeygenPeerInfo
40 {
41   /**
42    * Peer identity of the peer.
43    */
44   struct GNUNET_PeerIdentity peer;
45
46   /**
47    * g-component of the peer's paillier public key.
48    */
49   gcry_mpi_t paillier_g;
50
51   /**
52    * mu-component of the peer's paillier public key.
53    */
54   gcry_mpi_t paillier_n;
55
56   /**
57    * The peer's commitment to his presecret.
58    */
59   gcry_mpi_t presecret_commitment;
60
61   /**
62    * The peer's preshare that we could decrypt
63    * with out private key.
64    */
65   gcry_mpi_t decrypted_preshare;
66
67   /**
68    * Multiplicative share of the public key.
69    */
70   gcry_mpi_t public_key_share;
71
72   /**
73    * Did we successfully receive the round1 element
74    * of the peer?
75    */
76   int round1_valid;
77
78   /**
79    * Did we successfully receive the round1 element
80    * of the peer?
81    */
82   int round2_valid;
83 };
84
85
86 struct DecryptPeerInfo
87 {
88   /**
89    * Identity of the peer.
90    */
91   struct GNUNET_PeerIdentity peer;
92
93   /**
94    * Original index in the key generation round.
95    * Necessary for computing the lagrange coefficients.
96    */
97   unsigned int real_index;
98
99   /**
100    * Set to the partial decryption of
101    * this peer, or NULL if we did not
102    * receive a partial decryption from this
103    * peer or the zero knowledge proof failed.
104    */
105   gcry_mpi_t partial_decryption;
106 };
107
108
109 /**
110  * Session to establish a threshold-shared secret.
111  */
112 struct KeygenSession
113 {
114   /**
115    * Keygen sessions are held in a linked list.
116    */
117   struct KeygenSession *next;
118
119   /**
120    * Keygen sessions are held in a linked list.
121    */
122   struct KeygenSession *prev;
123
124   /**
125    * Current consensus, used for both DKG rounds.
126    */
127   struct GNUNET_CONSENSUS_Handle *consensus;
128
129   /**
130    * Client that is interested in the result
131    * of this key generation session.
132    */
133   struct GNUNET_SERVER_Client *client;
134
135   /**
136    * Message queue for 'client'
137    */
138   struct GNUNET_MQ_Handle *client_mq;
139
140   /**
141    * Randomly generated coefficients of the polynomial for sharing our
142    * pre-secret, where 'preshares[0]' is our pre-secret.  Contains 'threshold'
143    * elements, thus represents a polynomial of degree 'threshold-1', which can
144    * be interpolated with 'threshold' data points.
145    *
146    * The pre-secret-shares 'i=1,...,num_peers' are given by evaluating this
147    * polyomial at 'i' for share i.
148    */
149   gcry_mpi_t *presecret_polynomial;
150
151   /**
152    * Minimum number of shares required to restore the secret.
153    * Also the number of coefficients for the polynomial representing
154    * the sharing.  Obviously, the polynomial then has degree threshold-1.
155    */
156   unsigned int threshold;
157
158   /**
159    * Total number of peers.
160    */
161   unsigned int num_peers;
162
163   /**
164    * Index of the local peer.
165    */
166   unsigned int local_peer;
167
168   /**
169    * Information about all participating peers.
170    * Array of size 'num_peers'.
171    */
172   struct KeygenPeerInfo *info;
173
174   /**
175    * List of all peers involved in the secret sharing session.
176    */
177   struct GNUNET_PeerIdentity *peers;
178
179   /**
180    * Identifier for this session.
181    */
182   struct GNUNET_HashCode session_id;
183
184   /**
185    * g-component of our peer's paillier private key.
186    */
187   gcry_mpi_t paillier_lambda;
188
189   /**
190    * g-component of our peer's paillier private key.
191    */
192   gcry_mpi_t paillier_mu;
193
194   /**
195    * When would we like the key to be established?
196    */
197   struct GNUNET_TIME_Absolute deadline;
198
199   /**
200    * When does the DKG start?  Necessary to compute fractions of the
201    * operation's desired time interval.
202    */
203   struct GNUNET_TIME_Absolute start_time;
204
205   /**
206    * Index of the local peer in the ordered list
207    * of peers in the session.
208    */
209   unsigned int local_peer_idx;
210 };
211
212
213 struct DecryptSession
214 {
215   /**
216    * Decrypt sessions are stored in a linked list.
217    */
218   struct DecryptSession *next;
219
220   /**
221    * Decrypt sessions are stored in a linked list.
222    */
223   struct DecryptSession *prev;
224
225   /**
226    * Handle to the consensus over partial decryptions.
227    */
228   struct GNUNET_CONSENSUS_Handle *consensus;
229
230   /**
231    * Client connected to us.
232    */
233   struct GNUNET_SERVER_Client *client;
234
235   /**
236    * Message queue for 'client'.
237    */
238   struct GNUNET_MQ_Handle *client_mq;
239
240   /**
241    * When would we like the ciphertext to be
242    * decrypted?
243    */
244   struct GNUNET_TIME_Absolute deadline;
245
246   /**
247    * Ciphertext we want to decrypt.
248    */
249   struct GNUNET_SECRETSHARING_Ciphertext ciphertext;
250
251   /**
252    * Share of the local peer.
253    */
254   struct GNUNET_SECRETSHARING_Share *share;
255
256   /**
257    * State information about other peers.
258    */
259   struct DecryptPeerInfo *info;
260 };
261
262
263 /**
264  * Decrypt sessions are held in a linked list.
265  */
266 static struct DecryptSession *decrypt_sessions_head;
267
268 /**
269  * Decrypt sessions are held in a linked list.
270  */
271 static struct DecryptSession *decrypt_sessions_tail;
272
273 /**
274  * Decrypt sessions are held in a linked list.
275  */
276 static struct KeygenSession *keygen_sessions_head;
277
278 /**
279  * Decrypt sessions are held in a linked list.
280  */
281 static struct KeygenSession *keygen_sessions_tail;
282
283 /**
284  * The ElGamal prime field order as libgcrypt mpi.
285  * Will be initialized to 'ELGAMAL_Q_DATA'.
286  */
287 static gcry_mpi_t elgamal_q;
288
289 /**
290  * Modulus of the prime field used for ElGamal.
291  * Will be initialized to 'ELGAMAL_P_DATA'.
292  */
293 static gcry_mpi_t elgamal_p;
294
295 /**
296  * Generator for prime field of order 'elgamal_q'.
297  * Will be initialized to 'ELGAMAL_G_DATA'.
298  */
299 static gcry_mpi_t elgamal_g;
300
301 /**
302  * Peer that runs this service.
303  */
304 static struct GNUNET_PeerIdentity my_peer;
305
306 /**
307  * Peer that runs this service.
308  */
309 static struct GNUNET_CRYPTO_EddsaPrivateKey *my_peer_private_key;
310
311 /**
312  * Configuration of this service.
313  */
314 static const struct GNUNET_CONFIGURATION_Handle *cfg;
315
316 /**
317  * Server for this service.
318  */
319 static struct GNUNET_SERVER_Handle *srv;
320
321 /**
322  * Print a field element in a fixed-size buffer.
323  */
324 static void
325 print_field_element (void *buf, gcry_mpi_t x)
326 {
327   GNUNET_assert (0);
328 }
329
330
331 static struct KeygenPeerInfo *
332 get_keygen_peer_info (const struct KeygenSession *ks,
333                       const struct GNUNET_PeerIdentity *peer)
334 {
335   unsigned int i;
336   for (i = 0; i < ks->num_peers; i++)
337     if (0 == memcmp (peer, &ks->info[i].peer, sizeof (struct GNUNET_PeerIdentity)))
338       return &ks->info[i];
339   return NULL;
340 }
341
342
343 static struct DecryptPeerInfo *
344 get_decrypt_peer_info (const struct DecryptSession *ds,
345                       const struct GNUNET_PeerIdentity *peer)
346 {
347   unsigned int i;
348   for (i = 0; i < ds->share->num_peers; i++)
349     if (0 == memcmp (peer, &ds->info[i].peer, sizeof (struct GNUNET_PeerIdentity)))
350       return &ds->info[i];
351   return NULL;
352 }
353
354
355 static struct GNUNET_TIME_Absolute
356 time_between (struct GNUNET_TIME_Absolute start,
357               struct GNUNET_TIME_Absolute end,
358               int num, int denum)
359 {
360   struct GNUNET_TIME_Absolute result;
361   uint64_t diff;
362
363   GNUNET_assert (start.abs_value_us <= end.abs_value_us);
364   diff = end.abs_value_us - start.abs_value_us;
365   result.abs_value_us = start.abs_value_us + ((diff * num) / denum);
366
367   return result;
368 }
369
370
371 /**
372  * Compare two peer identities.  Indended to be used with qsort or bsearch.
373  *
374  * @param p1 some peer identity
375  * @param p2 some peer identity
376  * @return 1 if p1 > p2, -1 if p1 < p2 and 0 if p1 == p2.
377  */
378 static int
379 peer_id_cmp (const void *p1, const void *p2)
380 {
381   return memcmp (p1, p2, sizeof (struct GNUNET_PeerIdentity));
382 }
383
384
385 int
386 peer_find (const struct GNUNET_PeerIdentity *haystack, unsigned int n,
387            const struct GNUNET_PeerIdentity *needle)
388 {
389   unsigned int i;
390   for (i = 0; i < n; i++)
391     if (0 == memcmp (&haystack[i], needle, sizeof (struct GNUNET_PeerIdentity)))
392       return i;
393   return -1;
394 }
395
396
397 /**
398  * Normalize the given list of peers, by including the local peer
399  * (if it is missing) and sorting the peers by their identity.
400  *
401  * @param listed peers in the unnormalized list
402  * @param num_listed peers in the un-normalized list
403  * @param[out] num_normalized number of peers in the normalized list
404  * @param[out] my_peer_idx index of the local peer in the normalized list
405  * @return normalized list, must be free'd by the caller
406  */
407 static struct GNUNET_PeerIdentity *
408 normalize_peers (struct GNUNET_PeerIdentity *listed,
409                  unsigned int num_listed,
410                  unsigned int *num_normalized,
411                  unsigned int *my_peer_idx)
412 {
413   unsigned int local_peer_in_list;
414   unsigned int n;
415   struct GNUNET_PeerIdentity *normalized;
416
417   local_peer_in_list = GNUNET_YES;
418   n = num_listed;
419   if (peer_find (listed, num_listed, &my_peer) < 0)
420   {
421     local_peer_in_list = GNUNET_NO;
422     n += 1;
423   }
424
425   normalized = GNUNET_new_array (n, struct GNUNET_PeerIdentity);
426
427   if (GNUNET_NO == local_peer_in_list)
428     normalized[n - 1] = my_peer;
429
430   memcpy (normalized, listed, num_listed * sizeof (struct GNUNET_PeerIdentity));
431   qsort (normalized, n, sizeof (struct GNUNET_PeerIdentity), &peer_id_cmp);
432
433   if (NULL != my_peer_idx)
434     *my_peer_idx = peer_find (normalized, n, &my_peer);
435   if (NULL != num_normalized)
436     *num_normalized = n;
437
438   return normalized;
439 }
440
441
442 /**
443  * Get a the j-th lagrage coefficient for a set of indices.
444  *
445  * @param[out] coeff the lagrange coefficient
446  * @param j lagrage coefficient we want to compute
447  * @param indices indices
448  * @param num number of indices in @a indices
449  */
450 static void
451 compute_lagrange_coefficient (gcry_mpi_t coeff, unsigned int j,
452                               unsigned int *indices,
453                               unsigned int num)
454 {
455   int i;
456   /* numerator */
457   gcry_mpi_t n;
458   /* denominator */
459   gcry_mpi_t d;
460   /* temp value for l-j */
461   gcry_mpi_t tmp;
462
463   GNUNET_assert (0 != coeff);
464
465   GNUNET_assert (0 != (n = gcry_mpi_new (0)));
466   GNUNET_assert (0 != (d = gcry_mpi_new (0)));
467   GNUNET_assert (0 != (tmp = gcry_mpi_new (0)));
468
469   gcry_mpi_set_ui (n, 1);
470   gcry_mpi_set_ui (d, 1);
471
472   gcry_mpi_set_ui (coeff, 0);
473   for (i = 0; i < num; i++)
474   {
475     int l = indices[i];
476     if (l == j)
477       continue;
478     gcry_mpi_mul_ui (n, n, l);
479     // d <- d * (l-j)
480     gcry_mpi_set_ui (tmp, l);
481     gcry_mpi_sub_ui (tmp, tmp, j);
482     gcry_mpi_mul (d, d, tmp);
483   }
484
485   // now we do the actual division, with everything mod q, as we
486   // are not operating on elemets from <g>, but on exponents
487   GNUNET_assert (0 == gcry_mpi_invm (d, d, elgamal_q));
488   gcry_mpi_mulm (coeff, n, d, elgamal_q);
489
490   gcry_mpi_release (n);
491   gcry_mpi_release (d);
492   gcry_mpi_release (tmp);
493 }
494
495
496 /**
497  * Create a key pair for the paillier crypto system.
498  *
499  * Uses the simplified key generation of Jonathan Katz, Yehuda Lindell,
500  * "Introduction to Modern Cryptography: Principles and Protocols".
501  *
502  * @param g g-component of public key
503  * @param n n-component of public key
504  * @param lambda lambda-component of private key
505  * @param mu mu-componenent of private key
506  */
507 static void
508 paillier_create (gcry_mpi_t g, gcry_mpi_t n, gcry_mpi_t lambda, gcry_mpi_t mu)
509 {
510   gcry_mpi_t p;
511   gcry_mpi_t q;
512   gcry_mpi_t phi;
513   gcry_mpi_t tmp;
514
515   GNUNET_assert (0 != (phi = gcry_mpi_new (PAILLIER_BITS)));
516   GNUNET_assert (0 != (tmp = gcry_mpi_new (PAILLIER_BITS)));
517
518   // generate rsa modulus
519   GNUNET_assert (0 == gcry_prime_generate (&p, PAILLIER_BITS / 2, 0, NULL, NULL, NULL,
520                                            GCRY_WEAK_RANDOM, 0));
521   GNUNET_assert (0 == gcry_prime_generate (&q, PAILLIER_BITS / 2, 0, NULL, NULL, NULL,
522                                            GCRY_WEAK_RANDOM, 0));
523   gcry_mpi_mul (n, p, q);
524   gcry_mpi_add_ui (g, n, 1);
525   // compute phi(n) = (p-1)(q-1)
526   gcry_mpi_sub_ui (phi, p, 1);
527   gcry_mpi_sub_ui (tmp, q, 1);
528   gcry_mpi_mul (phi, phi, tmp);
529   gcry_mpi_set (lambda, phi);
530   // compute mu
531   GNUNET_assert (0 != gcry_mpi_invm (mu, phi, n));
532
533   gcry_mpi_release (p);
534   gcry_mpi_release (q);
535   gcry_mpi_release (phi);
536   gcry_mpi_release (tmp);
537 }
538
539
540 /**
541  * Encrypt a value using Paillier's scheme.
542  *
543  * @param c resulting ciphertext
544  * @param m plaintext to encrypt
545  * @param g g-component of public key
546  * @param n n-component of public key
547  */
548 static void
549 paillier_encrypt (gcry_mpi_t c, gcry_mpi_t m, gcry_mpi_t g, gcry_mpi_t n)
550 {
551   gcry_mpi_t n_square;
552   gcry_mpi_t r;
553
554   GNUNET_assert (0 != (n_square = gcry_mpi_new (0)));
555   GNUNET_assert (0 != (r = gcry_mpi_new (0)));
556
557   gcry_mpi_mul (n_square, n, n);
558
559   // generate r < n
560   do
561   {
562     gcry_mpi_randomize (r, PAILLIER_BITS, GCRY_WEAK_RANDOM);
563   }
564   while (gcry_mpi_cmp (r, n) > 0);
565
566   gcry_mpi_powm (c, g, m, n_square);
567   gcry_mpi_powm (r, r, n, n_square);
568   gcry_mpi_mulm (c, r, c, n_square);
569
570   gcry_mpi_release (n_square);
571   gcry_mpi_release (r);
572 }
573
574
575 /**
576  * Decrypt a ciphertext using Paillier's scheme.
577  *
578  * @param[out] m resulting plaintext
579  * @param c ciphertext to decrypt
580  * @param lambda lambda-component of private key
581  * @param mu mu-component of private key
582  * @param n n-component of public key
583  */
584 static void
585 paillier_decrypt (gcry_mpi_t m, gcry_mpi_t c, gcry_mpi_t mu, gcry_mpi_t lambda, gcry_mpi_t n)
586 {
587   gcry_mpi_t n_square;
588   GNUNET_assert (0 != (n_square = gcry_mpi_new (0)));
589   gcry_mpi_mul (n_square, n, n);
590   gcry_mpi_powm (m, c, lambda, n_square);
591   gcry_mpi_sub_ui (m, m, 1);
592   // m = m/n
593   gcry_mpi_div (m, NULL, m, n, 0);
594   gcry_mpi_mulm (m, m, mu, n);
595   gcry_mpi_release (n_square);
596 }
597
598
599 /**
600  * Task run during shutdown.
601  *
602  * @param cls unused
603  * @param tc unused
604  */
605 static void
606 cleanup_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
607 {
608   /* FIXME: do clean up here */
609 }
610
611
612 static void
613 generate_presecret_polynomial (struct KeygenSession *ks)
614 {
615   int i;
616   GNUNET_assert (NULL == ks->presecret_polynomial);
617   ks->presecret_polynomial = GNUNET_malloc (ks->threshold * sizeof (gcry_mpi_t));
618   for (i = 0; i < ks->threshold; i++)
619   {
620     ks->presecret_polynomial[i] = gcry_mpi_new (PAILLIER_BITS);
621     GNUNET_assert (0 != ks->presecret_polynomial[i]);
622     gcry_mpi_randomize (ks->presecret_polynomial[i], PAILLIER_BITS,
623                         GCRY_WEAK_RANDOM);
624   }
625 }
626
627
628 /**
629  * Consensus element handler for round one.
630  *
631  * @param cls closure (keygen session)
632  * @param element the element from consensus
633  */
634 static void
635 keygen_round1_new_element (void *cls,
636                            const struct GNUNET_SET_Element *element)
637 {
638   const struct GNUNET_SECRETSHARING_KeygenCommitData *d;
639   struct KeygenSession *ks = cls;
640   struct KeygenPeerInfo *info;
641
642   if (NULL == element)
643   {
644     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "round1 consensus failed\n");
645     return;
646   }
647
648   if (element->size != sizeof (struct GNUNET_SECRETSHARING_KeygenCommitData))
649   {
650     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
651                 "keygen commit data with wrong size (%u) in consensus, "
652                 " %u expected\n",
653                 element->size, sizeof (struct GNUNET_SECRETSHARING_KeygenCommitData));
654     return;
655   }
656
657   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round1 element\n");
658
659   d = element->data;
660
661   info = get_keygen_peer_info (ks, &d->peer);
662
663   if (NULL == info)
664   {
665     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong peer identity (%s) in consensus\n",
666                 GNUNET_i2s (&d->peer));
667     return;
668   }
669
670   if (d->purpose.size !=
671       htonl (element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose)))
672   {
673     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong signature purpose size in consensus\n");
674     return;
675   }
676
677   if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG1,
678                                                &d->purpose, &d->signature, &d->peer.public_key))
679   {
680     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with invalid signature in consensus\n");
681     return;
682   }
683
684   GNUNET_assert (0 == gcry_mpi_scan (&info->paillier_g, GCRYMPI_FMT_USG,
685                                      &d->pubkey.g, sizeof d->pubkey.g, NULL));
686   GNUNET_assert (0 == gcry_mpi_scan (&info->paillier_n, GCRYMPI_FMT_USG,
687                                      &d->pubkey.n, sizeof d->pubkey.n, NULL));
688   GNUNET_assert (0 == gcry_mpi_scan (&info->presecret_commitment, GCRYMPI_FMT_USG,
689                                      &d->commitment, sizeof d->commitment, NULL));
690   info->round1_valid = GNUNET_YES;
691 }
692
693
694 /**
695  * Evaluate the polynomial with coefficients @a coeff at @a x.
696  * The i-th element in @a coeff corresponds to the coefficient of x^i.
697  *
698  * @param[out] z result of the evaluation
699  * @param coeff array of coefficients
700  * @param num_coeff number of coefficients
701  * @param x where to evaluate the polynomial
702  * @param m what group are we operating in?
703  */
704 static void
705 horner_eval (gcry_mpi_t z, gcry_mpi_t *coeff, unsigned int num_coeff, gcry_mpi_t x, gcry_mpi_t m)
706 {
707   unsigned int i;
708
709   gcry_mpi_set_ui (z, 0);
710   for (i = 0; i < num_coeff; i++)
711   {
712     // z <- zx + c
713     gcry_mpi_mul (z, z, x);
714     gcry_mpi_addm (z, z, coeff[num_coeff - i - 1], m);
715   }
716 }
717
718
719 static void
720 keygen_round2_conclude (void *cls)
721 {
722   struct KeygenSession *ks = cls;
723   struct GNUNET_SECRETSHARING_SecretReadyMessage *m;
724   struct GNUNET_MQ_Envelope *ev;
725   size_t share_size;
726   unsigned int i;
727   unsigned int j;
728   struct GNUNET_SECRETSHARING_Share *share;
729   gcry_mpi_t s;
730   gcry_mpi_t h;
731
732   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "round2 conclude\n");
733
734   GNUNET_assert (0 != (s = gcry_mpi_new (PAILLIER_BITS)));
735   GNUNET_assert (0 != (h = gcry_mpi_new (PAILLIER_BITS)));
736
737   // multiplicative identity
738   gcry_mpi_set_ui (s, 1);
739
740   share = GNUNET_new (struct GNUNET_SECRETSHARING_Share);
741
742   share->num_peers = 0;
743
744   for (i = 0; i < ks->num_peers; i++)
745     if (GNUNET_YES == ks->info[i].round2_valid)
746       share->num_peers++;
747
748   share->peers = GNUNET_new_array (share->num_peers, struct GNUNET_PeerIdentity);
749   share->hom_share_commitments =
750       GNUNET_new_array (share->num_peers, struct GNUNET_SECRETSHARING_FieldElement);
751   share->original_indices = GNUNET_new_array (share->num_peers, uint16_t);
752
753   j = 0;
754   for (i = 0; i < ks->num_peers; i++)
755   {
756     if (GNUNET_YES == ks->info[i].round2_valid)
757     {
758       gcry_mpi_addm (s, s, ks->info[i].decrypted_preshare, elgamal_p);
759       gcry_mpi_mulm (h, h, ks->info[i].public_key_share, elgamal_p);
760       share->peers[i] = ks->info[i].peer;
761       share->original_indices[i] = j++;
762     }
763   }
764
765   gcry_mpi_print (GCRYMPI_FMT_USG, (void *) &share->my_share, PAILLIER_BITS / 8, NULL, s);
766   gcry_mpi_print (GCRYMPI_FMT_USG, (void *) &share->public_key, PAILLIER_BITS / 8, NULL, s);
767
768   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "keygen successful with %u peers\n", share->num_peers);
769
770   m = GNUNET_malloc (sizeof (struct GNUNET_SECRETSHARING_SecretReadyMessage) +
771                      ks->num_peers * sizeof (struct GNUNET_PeerIdentity));
772
773   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, NULL, 0, &share_size));
774
775   ev = GNUNET_MQ_msg_extra (m, share_size,
776                             GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_SECRET_READY);
777
778   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, &m[1], share_size, NULL));
779
780   GNUNET_MQ_send (ks->client_mq, ev);
781 }
782
783
784 /**
785  * Insert round 2 element in the consensus, consisting of
786  * (1) The exponentiated pre-share polynomial coefficients A_{i,l}=g^{a_{i,l}}
787  * (2) The exponentiated pre-shares y_{i,j}=g^{s_{i,j}}
788  * (3) The encrypted pre-shares Y_{i,j}
789  * (4) The zero knowledge proof for correctness of
790  *    the encryption
791  *
792  * @param ks session to use
793  */
794 static void
795 insert_round2_element (struct KeygenSession *ks)
796 {
797   struct GNUNET_SET_Element *element;
798   struct GNUNET_SECRETSHARING_KeygenRevealData *d;
799   unsigned char *pos;
800   unsigned char *last_pos;
801   size_t element_size;
802   unsigned int i;
803   gcry_mpi_t idx;
804   gcry_mpi_t v;
805
806   GNUNET_assert (0 != (v = gcry_mpi_new (PAILLIER_BITS)));
807   GNUNET_assert (0 != (idx = gcry_mpi_new (PAILLIER_BITS)));
808
809   element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
810                   2 * PAILLIER_BITS / 8 * ks->num_peers +
811                   1 * PAILLIER_BITS / 8 * ks->threshold);
812
813   element = GNUNET_malloc (sizeof (struct GNUNET_SET_Element) + element_size);
814   element->size = element_size;
815   element->data = (void *) &element[1];
816
817   d = (void *) element->data;
818   d->peer = my_peer;
819
820   pos = (void *) &d[1];
821   last_pos = pos + element_size;
822
823   // exponentiated pre-shares
824   for (i = 0; i < ks->num_peers; i++)
825   {
826     ptrdiff_t remaining = last_pos - pos;
827     GNUNET_assert (remaining > 0);
828     gcry_mpi_set_ui (idx, i);
829     // evaluate the polynomial
830     horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_p);
831     // take g to the result
832     gcry_mpi_powm (v, elgamal_g, v, elgamal_p);
833     gcry_mpi_print (GCRYMPI_FMT_USG, pos, (size_t) remaining, NULL, v);
834     pos += PAILLIER_BITS / 8;
835   }
836
837   // encrypted pre-shares
838   for (i = 0; i < ks->num_peers; i++)
839   {
840     ptrdiff_t remaining = last_pos - pos;
841     GNUNET_assert (remaining > 0);
842     if (GNUNET_NO == ks->info[i].round1_valid)
843       gcry_mpi_set_ui (v, 0);
844     else
845       paillier_encrypt (v, ks->presecret_polynomial[0],
846                         ks->info[i].paillier_g, ks->info[i].paillier_g);
847     gcry_mpi_print (GCRYMPI_FMT_USG, pos, (size_t) remaining, NULL, v);
848     pos += PAILLIER_BITS / 8;
849   }
850
851   // exponentiated coefficients
852   for (i = 0; i < ks->threshold; i++)
853   {
854     ptrdiff_t remaining = last_pos - pos;
855     GNUNET_assert (remaining > 0);
856     gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[i], elgamal_p);
857     gcry_mpi_print (GCRYMPI_FMT_USG, pos, (size_t) remaining, NULL, v);
858     pos += PAILLIER_BITS / 8;
859   }
860
861   d->purpose.size = htonl (element_size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose));
862   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2);
863   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d->purpose, &d->signature);
864
865   GNUNET_CONSENSUS_insert (ks->consensus, element, NULL, NULL);
866   GNUNET_free (element); /* FIXME: maybe stack-allocate instead? */
867
868   gcry_mpi_release (v);
869   gcry_mpi_release (idx);
870 }
871
872
873 static void
874 keygen_round2_new_element (void *cls,
875                            const struct GNUNET_SET_Element *element)
876 {
877   struct KeygenSession *ks = cls;
878   const struct GNUNET_SECRETSHARING_KeygenRevealData *d;
879   struct KeygenPeerInfo *info;
880   unsigned char *pos;
881   gcry_mpi_t c;
882   size_t expected_element_size;
883
884   if (NULL == element)
885   {
886     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "round2 consensus failed\n");
887     return;
888   }
889
890   expected_element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
891                   2 * PAILLIER_BITS / 8 * ks->num_peers +
892                   1 * PAILLIER_BITS / 8 * ks->threshold);
893
894   if (element->size != expected_element_size)
895   {
896     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
897                 "keygen round2 data with wrong size (%u) in consensus, "
898                 " %u expected\n",
899                 element->size, expected_element_size);
900     return;
901   }
902
903   d = (const void *) element->data;
904
905   info = get_keygen_peer_info (ks, &d->peer);
906
907   if (NULL == info)
908   {
909     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong peer identity (%s) in consensus\n",
910                 GNUNET_i2s (&d->peer));
911     return;
912   }
913
914   if (GNUNET_NO == info->round1_valid)
915   {
916     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
917                 "ignoring round2 element from peer with invalid round1 element (%s)\n",
918                 GNUNET_i2s (&d->peer));
919     return;
920   }
921
922   if (GNUNET_YES == info->round2_valid)
923   {
924     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
925                 "ignoring duplicate round2 element (%s)\n",
926                 GNUNET_i2s (&d->peer));
927     return;
928   }
929
930   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round2 element\n");
931
932
933   pos = (void *) &d[1];
934   // skip exponentiated pre-shares
935   pos += PAILLIER_BITS / 8 * ks->num_peers;
936   // skip encrypted pre-shares
937   pos += PAILLIER_BITS / 8 * ks->num_peers;
938   // the first exponentiated coefficient is the public key share
939   GNUNET_assert (0 == gcry_mpi_scan (&info->public_key_share, GCRYMPI_FMT_USG,
940                                      pos, PAILLIER_BITS / 8, NULL));
941
942   pos = (void *) &d[1];
943   // skip exp. pre-shares
944   pos += PAILLIER_BITS / 8 * ks->num_peers;
945   // skip to the encrypted value for our peer
946   pos += PAILLIER_BITS / 8 * ks->local_peer_idx;
947
948   GNUNET_assert (0 == gcry_mpi_scan (&c, GCRYMPI_FMT_USG,
949                                      pos, PAILLIER_BITS / 8, NULL));
950
951   GNUNET_assert (0 != (info->decrypted_preshare = mpi_new (0)));
952
953   paillier_decrypt (info->decrypted_preshare, c, ks->paillier_lambda, ks->paillier_mu,
954                     ks->info[ks->local_peer_idx].paillier_n);
955
956   // TODO: validate zero knowledge proofs
957
958   if (d->purpose.size !=
959       htons (element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose)))
960   {
961     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with wrong signature purpose size in consensus\n");
962     return;
963   }
964
965   if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2,
966                                                &d->purpose, &d->signature, &d->peer.public_key))
967   {
968     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with invalid signature in consensus\n");
969     return;
970   }
971   
972   info->round2_valid = GNUNET_YES;
973 }
974
975
976 /**
977  * Called when the first consensus round has concluded.
978  * Will initiate the second round.
979  *
980  * @param cls closure
981  */
982 static void
983 keygen_round1_conclude (void *cls)
984 {
985   struct KeygenSession *ks = cls;
986
987   GNUNET_CONSENSUS_destroy (ks->consensus);
988
989   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &ks->session_id,
990                                            keygen_round2_new_element, ks);
991
992   insert_round2_element (ks);
993
994   GNUNET_CONSENSUS_conclude (ks->consensus,
995                              /* last round, thus conclude at DKG deadline */
996                              ks->deadline,
997                              keygen_round2_conclude,
998                              ks);
999 }
1000
1001
1002 /**
1003  * Insert the ephemeral key and the presecret commitment
1004  * of this peer in the consensus of the given session.
1005  *
1006  * @param ks session to use
1007  */
1008 static void
1009 insert_round1_element (struct KeygenSession *ks)
1010 {
1011   struct GNUNET_SET_Element *element;
1012   struct GNUNET_SECRETSHARING_KeygenCommitData *d;
1013   // g^a_{i,0}
1014   gcry_mpi_t v;
1015   // big-endian representation of 'v'
1016   unsigned char v_data[PAILLIER_BITS / 8];
1017
1018   element = GNUNET_malloc (sizeof *element + sizeof *d);
1019   d = (void *) &element[1];
1020   element->data = d;
1021   element->size = sizeof *d;
1022
1023   d->peer = my_peer;
1024
1025   GNUNET_assert (0 != (v = gcry_mpi_new (PAILLIER_BITS)));
1026
1027   gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[0], elgamal_p);
1028
1029   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1030                                       v_data, PAILLIER_BITS / 8, NULL,
1031                                       v));
1032
1033   GNUNET_CRYPTO_hash (v_data, PAILLIER_BITS / 8, &d->commitment);
1034
1035   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1036                                       (unsigned char *) d->pubkey.g, PAILLIER_BITS / 8, NULL,
1037                                       ks->info[ks->local_peer_idx].paillier_g));
1038
1039   GNUNET_assert (0 == gcry_mpi_print (GCRYMPI_FMT_USG,
1040                                       (unsigned char *) d->pubkey.n, PAILLIER_BITS / 8, NULL,
1041                                       ks->info[ks->local_peer_idx].paillier_n));
1042
1043   d->purpose.size = htonl ((sizeof *d) - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose));
1044   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG1);
1045   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d->purpose, &d->signature));
1046
1047   GNUNET_CONSENSUS_insert (ks->consensus, element, NULL, NULL);
1048 }
1049
1050
1051 /**
1052  * Functions with this signature are called whenever a message is
1053  * received.
1054  *
1055  * @param cls closure
1056  * @param client identification of the client
1057  * @param message the actual message
1058  */
1059 static void handle_client_keygen (void *cls,
1060                                   struct GNUNET_SERVER_Client *client,
1061                                   const struct GNUNET_MessageHeader
1062                                   *message)
1063 {
1064   const struct GNUNET_SECRETSHARING_CreateMessage *msg =
1065       (const struct GNUNET_SECRETSHARING_CreateMessage *) message;
1066   struct KeygenSession *ks;
1067   unsigned int i;
1068
1069   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "client requested key generation\n");
1070
1071   ks = GNUNET_new (struct KeygenSession);
1072
1073   /* FIXME: check if client already has some session */
1074
1075   GNUNET_CONTAINER_DLL_insert (keygen_sessions_head, keygen_sessions_tail, ks);
1076
1077   ks->client = client;
1078   ks->client_mq = GNUNET_MQ_queue_for_server_client (client);
1079
1080   ks->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
1081   ks->threshold = ntohs (msg->threshold);
1082   ks->num_peers = ntohs (msg->num_peers);
1083
1084   ks->peers = normalize_peers ((struct GNUNET_PeerIdentity *) &msg[1], ks->num_peers,
1085                                &ks->num_peers, &ks->local_peer_idx);
1086
1087
1088   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "first round of consensus with %u peers\n", ks->num_peers);
1089   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &msg->session_id,
1090                                            keygen_round1_new_element, ks);
1091
1092   ks->info = GNUNET_malloc (ks->num_peers * sizeof (struct KeygenPeerInfo));
1093
1094   for (i = 0; i < ks->num_peers; i++)
1095     ks->info[i].peer = ks->peers[i];
1096
1097   GNUNET_assert (0 != (ks->info[ks->local_peer_idx].paillier_g = mpi_new (0)));
1098   GNUNET_assert (0 != (ks->info[ks->local_peer_idx].paillier_n = mpi_new (0)));
1099   GNUNET_assert (0 != (ks->paillier_lambda = mpi_new (0)));
1100   GNUNET_assert (0 != (ks->paillier_mu = mpi_new (0)));
1101
1102   paillier_create (ks->info[ks->local_peer_idx].paillier_g,
1103                    ks->info[ks->local_peer_idx].paillier_n,
1104                    ks->paillier_lambda,
1105                    ks->paillier_mu);
1106
1107
1108   generate_presecret_polynomial (ks);
1109
1110   insert_round1_element (ks);
1111
1112   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "starting conclude of round 1\n");
1113
1114   GNUNET_CONSENSUS_conclude (ks->consensus,
1115                              /* half the overall time */
1116                              time_between (ks->start_time, ks->deadline, 1, 2),
1117                              keygen_round1_conclude,
1118                              ks);
1119
1120   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1121 }
1122
1123
1124 /**
1125  * Called when the partial decryption consensus concludes.
1126  */
1127 static void
1128 decrypt_conclude (void *cls)
1129 {
1130   struct DecryptSession *ds = cls;
1131   struct GNUNET_SECRETSHARING_DecryptResponseMessage *msg;
1132   struct GNUNET_MQ_Envelope *ev;
1133   gcry_mpi_t lagrange;
1134   gcry_mpi_t m;
1135   gcry_mpi_t tmp;
1136   gcry_mpi_t c_2;
1137   unsigned int *indices;
1138   unsigned int num;
1139   unsigned int i;
1140   unsigned int j;
1141
1142   GNUNET_assert (0 != (lagrange = gcry_mpi_new (0)));
1143   GNUNET_assert (0 != (m = gcry_mpi_new (0)));
1144   GNUNET_assert (0 != (tmp = gcry_mpi_new (0)));
1145
1146   num = 0;
1147   for (i = 0; i < ds->share->num_peers; i++)
1148     if (NULL != ds->info[i].partial_decryption)
1149       num++;
1150
1151   indices = GNUNET_malloc (num * sizeof (unsigned int));
1152   j = 0;
1153   for (i = 0; i < ds->share->num_peers; i++)
1154     if (NULL != ds->info[i].partial_decryption)
1155       indices[j++] = ds->info[i].real_index;
1156
1157   gcry_mpi_set_ui (m, 1);
1158
1159   for (i = 0; i < num; i++)
1160   {
1161     compute_lagrange_coefficient (lagrange, indices[i], indices, num);
1162     // w_j^{\lambda_j}
1163     gcry_mpi_powm (tmp, ds->info[indices[i]].partial_decryption, lagrange, elgamal_p);
1164     gcry_mpi_mulm (m, m, tmp, elgamal_p);
1165   }
1166
1167   GNUNET_assert (0 == gcry_mpi_scan (&c_2, GCRYMPI_FMT_USG, ds->ciphertext.c2_bits,
1168                                      PAILLIER_BITS / 8, NULL));
1169
1170   // m <- c_2 / m
1171   gcry_mpi_invm (m, m, elgamal_p);
1172   gcry_mpi_mulm (m, c_2, m, elgamal_p);
1173
1174   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT_DONE);
1175   print_field_element (&msg->plaintext, m);
1176   msg->success = htonl (1);
1177   GNUNET_MQ_send (ds->client_mq, ev);
1178
1179   // FIXME: what if not enough peers participated?
1180 }
1181
1182
1183 /**
1184  * Called when a new partial decryption arrives.
1185  */
1186 static void
1187 decrypt_new_element (void *cls,
1188                      const struct GNUNET_SET_Element *element)
1189 {
1190   struct DecryptSession *session = cls;
1191   const struct GNUNET_SECRETSHARING_DecryptData *d;
1192   struct DecryptPeerInfo *info;
1193
1194   if (NULL == element)
1195   {
1196     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decryption failed\n");
1197     /* FIXME: destroy */
1198     return;
1199   }
1200
1201   if (element->size != sizeof *d)
1202   {
1203     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "element of wrong size in decrypt consensus\n");
1204     return;
1205   }
1206
1207   d = element->data;
1208
1209   info = get_decrypt_peer_info (session, &d->peer);
1210   
1211   if (NULL == info)
1212   {
1213     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decrypt element from invalid peer (%s)\n",
1214                 GNUNET_i2s (&d->peer));
1215     return;
1216   }
1217
1218   if (NULL != info->partial_decryption)
1219   {
1220     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decrypt element duplicate\n",
1221                 GNUNET_i2s (&d->peer));
1222     return;
1223   }
1224
1225   // FIXME: check NIZP first
1226
1227   GNUNET_assert (0 == gcry_mpi_scan (&info->partial_decryption,
1228                                      GCRYMPI_FMT_USG, &d->partial_decryption, PAILLIER_BITS / 8, NULL));
1229 }
1230
1231 static void
1232 insert_decrypt_element (struct DecryptSession *ds)
1233 {
1234   struct GNUNET_SECRETSHARING_DecryptData d;
1235   struct GNUNET_SET_Element element;
1236   gcry_mpi_t x;
1237   gcry_mpi_t s;
1238
1239   GNUNET_assert (0 == gcry_mpi_scan (&x, GCRYMPI_FMT_USG, ds->ciphertext.c1_bits, PAILLIER_BITS / 8, NULL));
1240   GNUNET_assert (0 == gcry_mpi_scan (&s, GCRYMPI_FMT_USG, &ds->share->my_share, PAILLIER_BITS / 8, NULL));
1241
1242   gcry_mpi_powm (x, x, s, elgamal_p);
1243
1244   element.data = (void *) &d;
1245   element.size = sizeof (struct GNUNET_SECRETSHARING_DecryptData);
1246
1247   d.peer = my_peer;
1248   d.purpose.size = htons (element.size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose));
1249   d.purpose.purpose = htons (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DECRYPTION);
1250   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d.purpose, &d.signature);
1251
1252   print_field_element (&d.partial_decryption, x);
1253
1254   GNUNET_CONSENSUS_insert (ds->consensus, &element, NULL, NULL);
1255 }
1256
1257
1258 /**
1259  * Functions with this signature are called whenever a message is
1260  * received.
1261  *
1262  * @param cls closure
1263  * @param client identification of the client
1264  * @param message the actual message
1265  */
1266 static void handle_client_decrypt (void *cls,
1267                                    struct GNUNET_SERVER_Client *client,
1268                                    const struct GNUNET_MessageHeader
1269                                    *message)
1270 {
1271   const struct GNUNET_SECRETSHARING_DecryptRequestMessage *msg =
1272       (const void *) message;
1273   struct DecryptSession *ds;
1274   struct GNUNET_HashCode session_id;
1275
1276   ds = GNUNET_new (struct DecryptSession);
1277   // FIXME: check if session already exists
1278   GNUNET_CONTAINER_DLL_insert (decrypt_sessions_head, decrypt_sessions_tail, ds);
1279   ds->client = client;
1280   ds->client_mq = GNUNET_MQ_queue_for_server_client (client);
1281   ds->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
1282   ds->ciphertext = msg->ciphertext;
1283
1284   ds->share = GNUNET_SECRETSHARING_share_read (&msg[1], ntohs (msg->header.size) - sizeof *msg, NULL);
1285   // FIXME: probably should be break rather than assert
1286   GNUNET_assert (NULL != ds->share);
1287
1288   // FIXME: this is probably sufficient, but kdf/hash with all values would be nicer ...
1289   GNUNET_CRYPTO_hash (&msg->ciphertext, sizeof (struct GNUNET_SECRETSHARING_Ciphertext), &session_id);
1290
1291   ds->consensus = GNUNET_CONSENSUS_create (cfg,
1292                                            ds->share->num_peers,
1293                                            ds->share->peers,
1294                                            &session_id,
1295                                            decrypt_new_element,
1296                                            ds);
1297
1298   insert_decrypt_element (ds);
1299
1300   GNUNET_CONSENSUS_conclude (ds->consensus, ds->deadline, decrypt_conclude, ds);
1301 }
1302
1303
1304 static void
1305 init_crypto_constants (void)
1306 {
1307   /* 1024-bit safe prime */
1308   const char *elgamal_p_hex =
1309       "0x08a347d3d69e8b2dd7d1b12a08dfbccbebf4ca"
1310       "6f4269a0814e158a34312964d946b3ef22882317"
1311       "2bcf30fc08f772774cb404f9bc002a6f66b09a79"
1312       "d810d67c4f8cb3bedc6060e3c8ef874b1b64df71"
1313       "6c7d2b002da880e269438d5a776e6b5f253c8df5"
1314       "6a16b1c7ce58def07c03db48238aadfc52a354a2"
1315       "7ed285b0c1675cad3f3";
1316   /* 1023-bit Sophie Germain prime, q = (p-1)/2 */
1317   const char *elgamal_q_hex =
1318       "0x0451a3e9eb4f4596ebe8d895046fde65f5fa65"
1319       "37a134d040a70ac51a1894b26ca359f79144118b"
1320       "95e7987e047bb93ba65a027cde001537b3584d3c"
1321       "ec086b3e27c659df6e303071e477c3a58db26fb8"
1322       "b63e958016d4407134a1c6ad3bb735af929e46fa"
1323       "b50b58e3e72c6f783e01eda411c556fe2951aa51"
1324       "3f6942d860b3ae569f9";
1325   /* generator of the unique size q subgroup of Z_p^* */
1326   const char *elgamal_g_hex =
1327       "0x05c00c36d2e822950087ef09d8252994adc4e4"
1328       "8fe3ec70269f035b46063aff0c99b633fd64df43"
1329       "02442e1914c829a41505a275438871f365e91c12"
1330       "3d5303ef9e90f4b8cb89bf86cc9b513e74a72634"
1331       "9cfd9f953674fab5d511e1c078fc72d72b34086f"
1332       "c82b4b951989eb85325cb203ff98df76bc366bba"
1333       "1d7024c3650f60d0da";
1334
1335   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_q, GCRYMPI_FMT_HEX,
1336                                      elgamal_q_hex, 0, NULL));
1337   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_p, GCRYMPI_FMT_HEX,
1338                                      elgamal_p_hex, 0, NULL));
1339   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_g, GCRYMPI_FMT_HEX,
1340                                      elgamal_g_hex, 0, NULL));
1341 }
1342
1343
1344 /**
1345  * Process template requests.
1346  *
1347  * @param cls closure
1348  * @param server the initialized server
1349  * @param c configuration to use
1350  */
1351 static void
1352 run (void *cls, struct GNUNET_SERVER_Handle *server,
1353      const struct GNUNET_CONFIGURATION_Handle *c)
1354 {
1355   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1356     {handle_client_keygen, NULL, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_GENERATE, 0},
1357     {handle_client_decrypt, NULL, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT, 0},
1358     {NULL, NULL, 0, 0}
1359   };
1360   cfg = c;
1361   srv = server;
1362   my_peer_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
1363   if (NULL == my_peer_private_key)
1364   {
1365     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not access host private key\n");
1366     GNUNET_break (0);
1367     GNUNET_SCHEDULER_shutdown ();
1368     return;
1369   }
1370   init_crypto_constants ();
1371   if (GNUNET_OK != GNUNET_CRYPTO_get_peer_identity (cfg, &my_peer))
1372   {
1373     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not retrieve host identity\n");
1374     GNUNET_break (0);
1375     GNUNET_SCHEDULER_shutdown ();
1376     return;
1377   }
1378   GNUNET_SERVER_add_handlers (server, handlers);
1379   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1380                                 NULL);
1381 }
1382
1383
1384 /**
1385  * The main function for the template service.
1386  *
1387  * @param argc number of arguments from the command line
1388  * @param argv command line arguments
1389  * @return 0 ok, 1 on error
1390  */
1391 int
1392 main (int argc, char *const *argv)
1393 {
1394   return (GNUNET_OK ==
1395           GNUNET_SERVICE_run (argc, argv, "secretsharing",
1396                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1397 }
1398