-indentation
[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  * Insert round 2 element in the consensus, consisting of
905  * (1) The exponentiated pre-share polynomial coefficients A_{i,l}=g^{a_{i,l}}
906  * (2) The exponentiated pre-shares y_{i,j}=g^{s_{i,j}}
907  * (3) The encrypted pre-shares Y_{i,j}
908  * (4) The zero knowledge proof for fairness of
909  *     the encryption
910  *
911  * @param ks session to use
912  */
913 static void
914 insert_round2_element (struct KeygenSession *ks)
915 {
916   struct GNUNET_SET_Element *element;
917   struct GNUNET_SECRETSHARING_KeygenRevealData *d;
918   unsigned char *pos;
919   unsigned char *last_pos;
920   size_t element_size;
921   unsigned int i;
922   gcry_mpi_t idx;
923   gcry_mpi_t v;
924
925   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting round2 element\n",
926               ks->local_peer_idx);
927
928   GNUNET_assert (NULL != (v = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
929   GNUNET_assert (NULL != (idx = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
930
931   element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
932                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers +
933                   sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers +
934                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->threshold);
935
936   element = GNUNET_malloc (sizeof (struct GNUNET_SET_Element) + element_size);
937   element->size = element_size;
938   element->data = (void *) &element[1];
939
940   d = (void *) element->data;
941   d->peer = my_peer;
942
943   // start inserting vector elements
944   // after the fixed part of the element's data
945   pos = (void *) &d[1];
946   last_pos = pos + element_size;
947
948   // exponentiated pre-shares
949   for (i = 0; i < ks->num_peers; i++)
950   {
951     ptrdiff_t remaining = last_pos - pos;
952     GNUNET_assert (remaining > 0);
953     gcry_mpi_set_ui (idx, i + 1);
954     // evaluate the polynomial
955     horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_q);
956     // take g to the result
957     gcry_mpi_powm (v, elgamal_g, v, elgamal_p);
958     GNUNET_CRYPTO_mpi_print_unsigned (pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
959     pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8;
960   }
961
962   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed exp preshares\n",
963               ks->local_peer_idx);
964
965   // encrypted pre-shares
966   for (i = 0; i < ks->num_peers; i++)
967   {
968     ptrdiff_t remaining = last_pos - pos;
969     struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext;
970
971     GNUNET_assert (remaining > 0);
972     ciphertext = (void *) pos;
973     memset (ciphertext, 0, sizeof *ciphertext);
974     if (GNUNET_YES == ks->info[i].round1_valid)
975     {
976       gcry_mpi_set_ui (idx, i + 1);
977       // evaluate the polynomial
978       horner_eval (v, ks->presecret_polynomial, ks->threshold, idx, elgamal_q);
979       // encrypt the result
980       GNUNET_CRYPTO_paillier_encrypt (&ks->info[i].paillier_public_key, v, 0, ciphertext);
981     }
982     pos += sizeof *ciphertext;
983   }
984
985   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed enc preshares\n",
986               ks->local_peer_idx);
987
988   // exponentiated coefficients
989   for (i = 0; i < ks->threshold; i++)
990   {
991     ptrdiff_t remaining = last_pos - pos;
992     GNUNET_assert (remaining > 0);
993     gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[i], elgamal_p);
994     GNUNET_CRYPTO_mpi_print_unsigned (pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
995     pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8;
996   }
997
998   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: computed exp coefficients\n",
999               ks->local_peer_idx);
1000
1001   d->purpose.size = htonl (element_size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose));
1002   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2);
1003   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d->purpose, &d->signature);
1004
1005   GNUNET_CONSENSUS_insert (ks->consensus, element, NULL, NULL);
1006   GNUNET_free (element); /* FIXME: maybe stack-allocate instead? */
1007
1008   gcry_mpi_release (v);
1009   gcry_mpi_release (idx);
1010 }
1011
1012
1013 static gcry_mpi_t
1014 keygen_reveal_get_exp_preshare (struct KeygenSession *ks,
1015                                 const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
1016                                 unsigned int idx)
1017 {
1018   unsigned char *pos;
1019   gcry_mpi_t exp_preshare;
1020
1021   GNUNET_assert (idx < ks->num_peers);
1022
1023   pos = (void *) &d[1];
1024   // skip exponentiated pre-shares we don't want
1025   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * idx;
1026   GNUNET_CRYPTO_mpi_scan_unsigned (&exp_preshare, pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1027   return exp_preshare;
1028 }
1029
1030 static gcry_mpi_t
1031 keygen_reveal_get_exp_coeff (struct KeygenSession *ks,
1032                              const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
1033                              unsigned int idx)
1034 {
1035   unsigned char *pos;
1036   gcry_mpi_t exp_coeff;
1037
1038   GNUNET_assert (idx < ks->threshold);
1039
1040   pos = (void *) &d[1];
1041   // skip exponentiated pre-shares
1042   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers;
1043   // skip encrypted pre-shares
1044   pos += sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers;
1045   // skip exp. coeffs we are not interested in
1046   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * idx;
1047   // the first exponentiated coefficient is the public key share
1048   GNUNET_CRYPTO_mpi_scan_unsigned (&exp_coeff, pos, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1049   return exp_coeff;
1050 }
1051
1052
1053 static struct GNUNET_CRYPTO_PaillierCiphertext *
1054 keygen_reveal_get_enc_preshare (struct KeygenSession *ks,
1055                                 const struct GNUNET_SECRETSHARING_KeygenRevealData *d,
1056                                 unsigned int idx)
1057 {
1058   unsigned char *pos;
1059
1060   GNUNET_assert (idx < ks->num_peers);
1061
1062   pos = (void *) &d[1];
1063   // skip exponentiated pre-shares
1064   pos += GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers;
1065   // skip encrypted pre-shares we're not interested in
1066   pos += sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * idx;
1067   return (struct GNUNET_CRYPTO_PaillierCiphertext *) pos;
1068 }
1069
1070
1071 static void
1072 keygen_round2_new_element (void *cls,
1073                            const struct GNUNET_SET_Element *element)
1074 {
1075   struct KeygenSession *ks = cls;
1076   const struct GNUNET_SECRETSHARING_KeygenRevealData *d;
1077   struct KeygenPeerInfo *info;
1078   size_t expected_element_size;
1079   unsigned int j;
1080   int cmp_result;
1081   gcry_mpi_t tmp;
1082   gcry_mpi_t public_key_share;
1083   gcry_mpi_t preshare;
1084
1085   if (NULL == element)
1086   {
1087     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "round2 consensus failed\n");
1088     return;
1089   }
1090
1091   expected_element_size = (sizeof (struct GNUNET_SECRETSHARING_KeygenRevealData) +
1092                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->num_peers +
1093                   sizeof (struct GNUNET_CRYPTO_PaillierCiphertext) * ks->num_peers +
1094                   GNUNET_SECRETSHARING_ELGAMAL_BITS / 8 * ks->threshold);
1095
1096   if (element->size != expected_element_size)
1097   {
1098     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1099                 "keygen round2 data with wrong size (%u) in consensus, "
1100                 " %u expected\n",
1101                 element->size, expected_element_size);
1102     return;
1103   }
1104
1105   d = (const void *) element->data;
1106
1107   info = get_keygen_peer_info (ks, &d->peer);
1108
1109   if (NULL == info)
1110   {
1111     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen commit data with wrong peer identity (%s) in consensus\n",
1112                 GNUNET_i2s (&d->peer));
1113     return;
1114   }
1115
1116   if (GNUNET_NO == info->round1_valid)
1117   {
1118     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1119                 "ignoring round2 element from peer with invalid round1 element (%s)\n",
1120                 GNUNET_i2s (&d->peer));
1121     return;
1122   }
1123
1124   if (GNUNET_YES == info->round2_valid)
1125   {
1126     GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1127                 "ignoring duplicate round2 element (%s)\n",
1128                 GNUNET_i2s (&d->peer));
1129     return;
1130   }
1131
1132   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "got round2 element\n");
1133
1134   if (ntohl (d->purpose.size) !=
1135       element->size - offsetof (struct GNUNET_SECRETSHARING_KeygenRevealData, purpose))
1136   {
1137     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with wrong signature purpose size in consensus\n");
1138     return;
1139   }
1140
1141   if (GNUNET_OK != GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG2,
1142                                                &d->purpose, &d->signature, &d->peer.public_key))
1143   {
1144     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "keygen reveal data with invalid signature in consensus\n");
1145     return;
1146   }
1147
1148   public_key_share = keygen_reveal_get_exp_coeff (ks, d, 0);
1149   info->preshare_commitment = keygen_reveal_get_exp_preshare (ks, d, ks->local_peer_idx);
1150
1151   if (NULL == ks->public_key)
1152   {
1153     GNUNET_assert (NULL != (ks->public_key = gcry_mpi_new (0)));
1154     gcry_mpi_set_ui (ks->public_key, 1);
1155   }
1156   gcry_mpi_mulm (ks->public_key, ks->public_key, public_key_share, elgamal_p);
1157   
1158   gcry_mpi_release (public_key_share);
1159   public_key_share = NULL;
1160
1161   GNUNET_assert (NULL != (preshare = gcry_mpi_new (0)));
1162   GNUNET_CRYPTO_paillier_decrypt (&ks->paillier_private_key,
1163                                   &ks->info[ks->local_peer_idx].paillier_public_key,
1164                                   keygen_reveal_get_enc_preshare (ks, d, ks->local_peer_idx),
1165                                   preshare);
1166
1167   GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
1168   gcry_mpi_powm (tmp, elgamal_g, preshare, elgamal_p);
1169
1170   // TODO: restore a valid secret from the decryption (the hard part, solving SVP with gauss)
1171   cmp_result = gcry_mpi_cmp (tmp, info->preshare_commitment);
1172   gcry_mpi_release (tmp);
1173   tmp = NULL;
1174   if (0 != cmp_result)
1175   {
1176     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Got invalid presecret from P%u\n",
1177                 (unsigned int) ks->local_peer_idx, (unsigned int) (info - ks->info));
1178     return;
1179   }
1180
1181   if (NULL == ks->my_share)
1182   {
1183     GNUNET_assert (NULL != (ks->my_share = gcry_mpi_new (0)));
1184   }
1185   gcry_mpi_addm (ks->my_share, ks->my_share, preshare, elgamal_q);
1186
1187   for (j = 0; j < ks->num_peers; j++)
1188   {
1189     gcry_mpi_t presigma;
1190     if (NULL == ks->info[j].sigma)
1191     {
1192       GNUNET_assert (NULL != (ks->info[j].sigma = gcry_mpi_new (0)));
1193       gcry_mpi_set_ui (ks->info[j].sigma, 1);
1194     }
1195     presigma = keygen_reveal_get_exp_preshare (ks, d, j);
1196     gcry_mpi_mulm (ks->info[j].sigma, ks->info[j].sigma, presigma, elgamal_p);
1197     gcry_mpi_release (presigma);
1198   }
1199
1200   gcry_mpi_t prod;
1201   GNUNET_assert (NULL != (prod = gcry_mpi_new (0)));
1202   gcry_mpi_t j_to_k;
1203   GNUNET_assert (NULL != (j_to_k = gcry_mpi_new (0)));
1204   // validate that the polynomial sharing matches the additive sharing
1205   for (j = 0; j < ks->num_peers; j++)
1206   {
1207     unsigned int k;
1208     int cmp_result;
1209     gcry_mpi_t exp_preshare;
1210     gcry_mpi_set_ui (prod, 1);
1211     for (k = 0; k < ks->threshold; k++)
1212     {
1213       // Using pow(double,double) is a bit sketchy.
1214       // We count players from 1, but shares from 0.
1215       gcry_mpi_t tmp;
1216       gcry_mpi_set_ui (j_to_k, (unsigned int) pow(j+1, k)); 
1217       tmp = keygen_reveal_get_exp_coeff (ks, d, k);
1218       gcry_mpi_powm (tmp, tmp, j_to_k, elgamal_p);
1219       gcry_mpi_mulm (prod, prod, tmp, elgamal_p);
1220       gcry_mpi_release (tmp);
1221     }
1222     exp_preshare = keygen_reveal_get_exp_preshare (ks, d, j);
1223     gcry_mpi_mod (exp_preshare, exp_preshare, elgamal_p);
1224     cmp_result = gcry_mpi_cmp (prod, exp_preshare);
1225     gcry_mpi_release (exp_preshare);
1226     exp_preshare = NULL;
1227     if (0 != cmp_result)
1228     {
1229       GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: reveal data from P%u incorrect\n",
1230                   ks->local_peer_idx, j);
1231       /* no need for further verification, round2 stays invalid ... */
1232       return;
1233     }
1234   }
1235
1236   // TODO: verify proof of fair encryption (once implemented)
1237   
1238   info->round2_valid = GNUNET_YES;
1239
1240   gcry_mpi_release (preshare);
1241   gcry_mpi_release (prod);
1242   gcry_mpi_release (j_to_k);
1243 }
1244
1245
1246 /**
1247  * Called when the first consensus round has concluded.
1248  * Will initiate the second round.
1249  *
1250  * @param cls closure
1251  */
1252 static void
1253 keygen_round1_conclude (void *cls)
1254 {
1255   struct KeygenSession *ks = cls;
1256
1257   GNUNET_CONSENSUS_destroy (ks->consensus);
1258
1259   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &ks->session_id,
1260                                            time_between (ks->start_time, ks->deadline, 1, 2),
1261                                            ks->deadline,
1262                                            keygen_round2_new_element, ks);
1263
1264   insert_round2_element (ks);
1265
1266   GNUNET_CONSENSUS_conclude (ks->consensus,
1267                              keygen_round2_conclude,
1268                              ks);
1269 }
1270
1271
1272 /**
1273  * Insert the ephemeral key and the presecret commitment
1274  * of this peer in the consensus of the given session.
1275  *
1276  * @param ks session to use
1277  */
1278 static void
1279 insert_round1_element (struct KeygenSession *ks)
1280 {
1281   struct GNUNET_SET_Element *element;
1282   struct GNUNET_SECRETSHARING_KeygenCommitData *d;
1283   // g^a_{i,0}
1284   gcry_mpi_t v;
1285   // big-endian representation of 'v'
1286   unsigned char v_data[GNUNET_SECRETSHARING_ELGAMAL_BITS / 8];
1287
1288   element = GNUNET_malloc (sizeof *element + sizeof *d);
1289   d = (void *) &element[1];
1290   element->data = d;
1291   element->size = sizeof *d;
1292
1293   d->peer = my_peer;
1294
1295   GNUNET_assert (0 != (v = gcry_mpi_new (GNUNET_SECRETSHARING_ELGAMAL_BITS)));
1296
1297   gcry_mpi_powm (v, elgamal_g, ks->presecret_polynomial[0], elgamal_p);
1298
1299   GNUNET_CRYPTO_mpi_print_unsigned (v_data, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, v);
1300
1301   GNUNET_CRYPTO_hash (v_data, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, &d->commitment);
1302
1303   d->pubkey = ks->info[ks->local_peer_idx].paillier_public_key;
1304
1305   d->purpose.size = htonl ((sizeof *d) - offsetof (struct GNUNET_SECRETSHARING_KeygenCommitData, purpose));
1306   d->purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DKG1);
1307   GNUNET_assert (GNUNET_OK == GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d->purpose, &d->signature));
1308
1309   GNUNET_CONSENSUS_insert (ks->consensus, element, NULL, NULL);
1310
1311   gcry_mpi_release (v);
1312   GNUNET_free (element);
1313 }
1314
1315
1316 /**
1317  * Functions with this signature are called whenever a message is
1318  * received.
1319  *
1320  * @param cls closure
1321  * @param client identification of the client
1322  * @param message the actual message
1323  */
1324 static void handle_client_keygen (void *cls,
1325                                   struct GNUNET_SERVER_Client *client,
1326                                   const struct GNUNET_MessageHeader
1327                                   *message)
1328 {
1329   const struct GNUNET_SECRETSHARING_CreateMessage *msg =
1330       (const struct GNUNET_SECRETSHARING_CreateMessage *) message;
1331   struct KeygenSession *ks;
1332   unsigned int i;
1333
1334   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "client requested key generation\n");
1335
1336   ks = GNUNET_new (struct KeygenSession);
1337
1338   /* FIXME: check if client already has some session */
1339
1340   GNUNET_CONTAINER_DLL_insert (keygen_sessions_head, keygen_sessions_tail, ks);
1341
1342   ks->client = client;
1343   ks->client_mq = GNUNET_MQ_queue_for_server_client (client);
1344
1345   ks->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
1346   ks->threshold = ntohs (msg->threshold);
1347   ks->num_peers = ntohs (msg->num_peers);
1348
1349   ks->peers = normalize_peers ((struct GNUNET_PeerIdentity *) &msg[1], ks->num_peers,
1350                                &ks->num_peers, &ks->local_peer_idx);
1351
1352
1353   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "first round of consensus with %u peers\n", ks->num_peers);
1354   ks->consensus = GNUNET_CONSENSUS_create (cfg, ks->num_peers, ks->peers, &msg->session_id,
1355                                            GNUNET_TIME_absolute_ntoh (msg->start),
1356                                            GNUNET_TIME_absolute_ntoh (msg->deadline),
1357                                            keygen_round1_new_element, ks);
1358
1359   ks->info = GNUNET_new_array (ks->num_peers, struct KeygenPeerInfo);
1360
1361   for (i = 0; i < ks->num_peers; i++)
1362     ks->info[i].peer = ks->peers[i];
1363
1364   GNUNET_CRYPTO_paillier_create (&ks->info[ks->local_peer_idx].paillier_public_key,
1365                                  &ks->paillier_private_key);
1366
1367   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Generated paillier key pair\n", ks->local_peer_idx);
1368
1369   generate_presecret_polynomial (ks);
1370
1371   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Generated presecret polynomial\n", ks->local_peer_idx);
1372
1373   insert_round1_element (ks);
1374
1375   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Concluding for round 1\n", ks->local_peer_idx);
1376
1377   GNUNET_CONSENSUS_conclude (ks->consensus,
1378                              keygen_round1_conclude,
1379                              ks);
1380
1381   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1382
1383   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Waiting for round 1 elements ...\n", ks->local_peer_idx);
1384 }
1385
1386
1387 /**
1388  * Called when the partial decryption consensus concludes.
1389  */
1390 static void
1391 decrypt_conclude (void *cls)
1392 {
1393   struct DecryptSession *ds = cls;
1394   struct GNUNET_SECRETSHARING_DecryptResponseMessage *msg;
1395   struct GNUNET_MQ_Envelope *ev;
1396   gcry_mpi_t lagrange;
1397   gcry_mpi_t m;
1398   gcry_mpi_t tmp;
1399   gcry_mpi_t c_2;
1400   gcry_mpi_t prod;
1401   unsigned int *indices;
1402   unsigned int num;
1403   unsigned int i;
1404   unsigned int j;
1405
1406   GNUNET_CONSENSUS_destroy (ds->consensus);
1407   ds->consensus = NULL;
1408
1409   GNUNET_assert (0 != (lagrange = gcry_mpi_new (0)));
1410   GNUNET_assert (0 != (m = gcry_mpi_new (0)));
1411   GNUNET_assert (0 != (tmp = gcry_mpi_new (0)));
1412   GNUNET_assert (0 != (prod = gcry_mpi_new (0)));
1413
1414   num = 0;
1415   for (i = 0; i < ds->share->num_peers; i++)
1416     if (NULL != ds->info[i].partial_decryption)
1417       num++;
1418
1419   indices = GNUNET_malloc (num * sizeof (unsigned int));
1420   j = 0;
1421   for (i = 0; i < ds->share->num_peers; i++)
1422     if (NULL != ds->info[i].partial_decryption)
1423       indices[j++] = ds->info[i].original_index;
1424
1425   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: decrypt conclude, with %u peers\n",
1426               ds->share->my_peer, num);
1427
1428   gcry_mpi_set_ui (prod, 1);
1429   for (i = 0; i < num; i++)
1430   {
1431
1432     GNUNET_log (GNUNET_ERROR_TYPE_INFO, "P%u: index of %u: %u\n",
1433                 ds->share->my_peer, i, indices[i]);
1434     compute_lagrange_coefficient (lagrange, indices[i], indices, num);
1435     // w_i^{\lambda_i}
1436     gcry_mpi_powm (tmp, ds->info[indices[i]].partial_decryption, lagrange, elgamal_p);
1437
1438     // product of all exponentiated partiel decryptions ...
1439     gcry_mpi_mulm (prod, prod, tmp, elgamal_p);
1440   }
1441
1442   GNUNET_CRYPTO_mpi_scan_unsigned (&c_2, ds->ciphertext.c2_bits, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1443
1444   GNUNET_assert (0 != gcry_mpi_invm (prod, prod, elgamal_p));
1445   gcry_mpi_mulm (m, c_2, prod, elgamal_p);
1446   ev = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT_DONE);
1447   GNUNET_CRYPTO_mpi_print_unsigned (&msg->plaintext, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, m);
1448   msg->success = htonl (1);
1449   GNUNET_MQ_send (ds->client_mq, ev);
1450
1451   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "sent decrypt done to client\n");
1452
1453   GNUNET_free (indices);
1454
1455   gcry_mpi_release(lagrange);
1456   gcry_mpi_release(m);
1457   gcry_mpi_release(tmp);
1458   gcry_mpi_release(prod);
1459   gcry_mpi_release(c_2);
1460
1461   // FIXME: what if not enough peers participated?
1462 }
1463
1464
1465 /**
1466  * Get a string representation of an MPI.
1467  * The caller must free the returned string.
1468  *
1469  * @param mpi mpi to convert to a string
1470  * @return string representation of @a mpi, must be free'd by the caller
1471  */
1472 static char *
1473 mpi_to_str (gcry_mpi_t mpi)
1474 {
1475   unsigned char *buf;
1476
1477   GNUNET_assert (0 == gcry_mpi_aprint (GCRYMPI_FMT_HEX, &buf, NULL, mpi));
1478   return (char *) buf;
1479 }
1480
1481
1482 /**
1483  * Called when a new partial decryption arrives.
1484  */
1485 static void
1486 decrypt_new_element (void *cls,
1487                      const struct GNUNET_SET_Element *element)
1488 {
1489   struct DecryptSession *session = cls;
1490   const struct GNUNET_SECRETSHARING_DecryptData *d;
1491   struct DecryptPeerInfo *info;
1492   struct GNUNET_HashCode challenge_hash;
1493
1494   /* nizk response */
1495   gcry_mpi_t r;
1496   /* nizk challenge */
1497   gcry_mpi_t challenge;
1498   /* nizk commit1, g^\beta */
1499   gcry_mpi_t commit1;
1500   /* nizk commit2, c_1^\beta */
1501   gcry_mpi_t commit2;
1502   /* homomorphic commitment to the peer's share,
1503    * public key share */
1504   gcry_mpi_t sigma;
1505   /* partial decryption we received */
1506   gcry_mpi_t w;
1507   /* ciphertext component #1 */
1508   gcry_mpi_t c1;
1509   /* temporary variable (for comparision) #1 */
1510   gcry_mpi_t tmp1;
1511   /* temporary variable (for comparision) #2 */
1512   gcry_mpi_t tmp2;
1513
1514   if (NULL == element)
1515   {
1516     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decryption failed\n");
1517     /* FIXME: destroy */
1518     return;
1519   }
1520
1521   if (element->size != sizeof *d)
1522   {
1523     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "element of wrong size in decrypt consensus\n");
1524     return;
1525   }
1526
1527   d = element->data;
1528
1529   info = get_decrypt_peer_info (session, &d->peer);
1530   
1531   if (NULL == info)
1532   {
1533     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decrypt element from invalid peer (%s)\n",
1534                 GNUNET_i2s (&d->peer));
1535     return;
1536   }
1537
1538   if (NULL != info->partial_decryption)
1539   {
1540     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "decrypt element duplicate\n",
1541                 GNUNET_i2s (&d->peer));
1542     return;
1543   }
1544
1545   if (0 != memcmp (&d->ciphertext, &session->ciphertext, sizeof (struct GNUNET_SECRETSHARING_Ciphertext)))
1546   {
1547     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: got decrypt element with non-matching ciphertext from P%u\n",
1548                 (unsigned int) session->share->my_peer, (unsigned int) (info - session->info));
1549
1550     return;
1551   }
1552
1553
1554   GNUNET_CRYPTO_hash (offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext) + (char *) d,
1555                       offsetof (struct GNUNET_SECRETSHARING_DecryptData, nizk_response) - 
1556                           offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext),
1557                       &challenge_hash);
1558
1559   GNUNET_CRYPTO_mpi_scan_unsigned (&challenge, &challenge_hash,
1560                                    sizeof (struct GNUNET_HashCode));
1561
1562   GNUNET_CRYPTO_mpi_scan_unsigned (&sigma, &session->share->sigmas[info - session->info],
1563                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1564
1565   GNUNET_CRYPTO_mpi_scan_unsigned (&c1, session->ciphertext.c1_bits,
1566                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1567
1568   GNUNET_CRYPTO_mpi_scan_unsigned (&commit1, &d->nizk_commit1,
1569                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1570
1571   GNUNET_CRYPTO_mpi_scan_unsigned (&commit2, &d->nizk_commit2,
1572                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1573
1574   GNUNET_CRYPTO_mpi_scan_unsigned (&r, &d->nizk_response,
1575                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1576
1577   GNUNET_CRYPTO_mpi_scan_unsigned (&w, &d->partial_decryption,
1578                                    sizeof (struct GNUNET_SECRETSHARING_FieldElement));
1579
1580   GNUNET_assert (NULL != (tmp1 = gcry_mpi_new (0)));
1581   GNUNET_assert (NULL != (tmp2 = gcry_mpi_new (0)));
1582
1583   // tmp1 = g^r
1584   gcry_mpi_powm (tmp1, elgamal_g, r, elgamal_p);
1585
1586   // tmp2 = g^\beta * \sigma^challenge
1587   gcry_mpi_powm (tmp2, sigma, challenge, elgamal_p);
1588   gcry_mpi_mulm (tmp2, tmp2, commit1, elgamal_p);
1589
1590   if (0 != gcry_mpi_cmp (tmp1, tmp2))
1591   {
1592     char *tmp1_str;
1593     char *tmp2_str;
1594     tmp1_str = mpi_to_str (tmp1);
1595     tmp2_str = mpi_to_str (tmp2);
1596     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Received invalid partial decryption from P%u (eqn 1), expected %s got %s\n",
1597                 session->share->my_peer, info - session->info, tmp1_str, tmp2_str);
1598     GNUNET_free (tmp1_str);
1599     GNUNET_free (tmp2_str);
1600     goto cleanup;
1601   }
1602
1603
1604   gcry_mpi_powm (tmp1, c1, r, elgamal_p);
1605
1606   gcry_mpi_powm (tmp2, w, challenge, elgamal_p);
1607   gcry_mpi_mulm (tmp2, tmp2, commit2, elgamal_p);
1608
1609
1610   if (0 != gcry_mpi_cmp (tmp1, tmp2))
1611   {
1612     GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "P%u: Received invalid partial decryption from P%u (eqn 2)\n",
1613                 session->share->my_peer, info - session->info);
1614     goto cleanup;
1615   }
1616
1617
1618   GNUNET_CRYPTO_mpi_scan_unsigned (&info->partial_decryption, &d->partial_decryption,
1619                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1620 cleanup:
1621   gcry_mpi_release (tmp1);
1622   gcry_mpi_release (tmp2);
1623   gcry_mpi_release (sigma);
1624   gcry_mpi_release (commit1);
1625   gcry_mpi_release (commit2);
1626   gcry_mpi_release (r);
1627   gcry_mpi_release (w);
1628   gcry_mpi_release (challenge);
1629   gcry_mpi_release (c1);
1630 }
1631
1632
1633 static void
1634 insert_decrypt_element (struct DecryptSession *ds)
1635 {
1636   struct GNUNET_SECRETSHARING_DecryptData d;
1637   struct GNUNET_SET_Element element;
1638   /* our share */
1639   gcry_mpi_t s;
1640   /* partial decryption with our share */
1641   gcry_mpi_t w;
1642   /* first component of the elgamal ciphertext */
1643   gcry_mpi_t c1;
1644   /* nonce for dlog zkp */
1645   gcry_mpi_t beta;
1646   gcry_mpi_t tmp;
1647   gcry_mpi_t challenge;
1648   gcry_mpi_t sigma;
1649   struct GNUNET_HashCode challenge_hash;
1650
1651   /* make vagrind happy until we implement the real deal ... */
1652   memset (&d, 0, sizeof d);
1653
1654   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting decrypt element\n",
1655               ds->share->my_peer);
1656
1657   GNUNET_assert (ds->share->my_peer < ds->share->num_peers);
1658
1659   GNUNET_CRYPTO_mpi_scan_unsigned (&c1, &ds->ciphertext.c1_bits,
1660                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1661   GNUNET_CRYPTO_mpi_scan_unsigned (&s, &ds->share->my_share,
1662                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1663   GNUNET_CRYPTO_mpi_scan_unsigned (&sigma, &ds->share->sigmas[ds->share->my_peer],
1664                                    GNUNET_SECRETSHARING_ELGAMAL_BITS / 8);
1665
1666   GNUNET_assert (NULL != (w = gcry_mpi_new (0)));
1667   GNUNET_assert (NULL != (beta = gcry_mpi_new (0)));
1668   GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
1669
1670   // FIXME: unnecessary, remove once crypto works
1671   gcry_mpi_powm (tmp, elgamal_g, s, elgamal_p);
1672   if (0 != gcry_mpi_cmp (tmp, sigma))
1673   {
1674     char *sigma_str = mpi_to_str (sigma);
1675     char *tmp_str = mpi_to_str (tmp);
1676     char *s_str = mpi_to_str (s);
1677     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Share of P%u is invalid, ref sigma %s, "
1678                 "computed sigma %s, s %s\n",
1679                 ds->share->my_peer,
1680                 sigma_str, tmp_str, s_str);
1681     GNUNET_free (sigma_str);
1682     GNUNET_free (tmp_str);
1683     GNUNET_free (s_str);
1684   }
1685
1686   gcry_mpi_powm (w, c1, s, elgamal_p);
1687
1688   element.data = (void *) &d;
1689   element.size = sizeof (struct GNUNET_SECRETSHARING_DecryptData);
1690   element.type = 0;
1691
1692   d.ciphertext = ds->ciphertext;
1693   d.peer = my_peer;
1694   GNUNET_CRYPTO_mpi_print_unsigned (&d.partial_decryption, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, w);
1695
1696   // create the zero knowledge proof
1697   // randomly choose beta such that 0 < beta < q
1698   do 
1699   {
1700     gcry_mpi_randomize (beta, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
1701   } while ((gcry_mpi_cmp_ui (beta, 0) == 0) || (gcry_mpi_cmp (beta, elgamal_q) >= 0));
1702   // tmp = g^beta
1703   gcry_mpi_powm (tmp, elgamal_g, beta, elgamal_p);
1704   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_commit1, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
1705   // tmp = (c_1)^beta
1706   gcry_mpi_powm (tmp, c1, beta, elgamal_p);
1707   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_commit2, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
1708
1709   // the challenge is the hash of everything up to the response
1710   GNUNET_CRYPTO_hash (offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext) + (char *) &d,
1711                       offsetof (struct GNUNET_SECRETSHARING_DecryptData, nizk_response) - 
1712                           offsetof (struct GNUNET_SECRETSHARING_DecryptData, ciphertext),
1713                       &challenge_hash);
1714
1715   GNUNET_CRYPTO_mpi_scan_unsigned (&challenge, &challenge_hash,
1716                                    sizeof (struct GNUNET_HashCode));
1717
1718   // compute the response in tmp,
1719   // tmp = (c * s + beta) mod q
1720   gcry_mpi_mulm (tmp, challenge, s, elgamal_q);
1721   gcry_mpi_addm (tmp, tmp, beta, elgamal_q);
1722
1723   GNUNET_CRYPTO_mpi_print_unsigned (&d.nizk_response, GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
1724
1725   d.purpose.size = htonl (element.size - offsetof (struct GNUNET_SECRETSHARING_DecryptData, purpose));
1726   d.purpose.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_SECRETSHARING_DECRYPTION);
1727   
1728   GNUNET_CRYPTO_eddsa_sign (my_peer_private_key, &d.purpose, &d.signature);
1729
1730   GNUNET_CONSENSUS_insert (ds->consensus, &element, NULL, NULL);
1731   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "P%u: Inserting decrypt element done!\n",
1732               ds->share->my_peer);
1733
1734   gcry_mpi_release (s);
1735   gcry_mpi_release (w);
1736   gcry_mpi_release (c1);
1737   gcry_mpi_release (beta);
1738   gcry_mpi_release (tmp);
1739   gcry_mpi_release (challenge);
1740   gcry_mpi_release (sigma);
1741 }
1742
1743
1744 /**
1745  * Functions with this signature are called whenever a message is
1746  * received.
1747  *
1748  * @param cls closure
1749  * @param client identification of the client
1750  * @param message the actual message
1751  */
1752 static void handle_client_decrypt (void *cls,
1753                                    struct GNUNET_SERVER_Client *client,
1754                                    const struct GNUNET_MessageHeader
1755                                    *message)
1756 {
1757   const struct GNUNET_SECRETSHARING_DecryptRequestMessage *msg =
1758       (const void *) message;
1759   struct DecryptSession *ds;
1760   struct GNUNET_HashCode session_id;
1761   unsigned int i;
1762
1763   ds = GNUNET_new (struct DecryptSession);
1764   // FIXME: check if session already exists
1765   GNUNET_CONTAINER_DLL_insert (decrypt_sessions_head, decrypt_sessions_tail, ds);
1766   ds->client = client;
1767   ds->client_mq = GNUNET_MQ_queue_for_server_client (client);
1768   ds->start = GNUNET_TIME_absolute_ntoh (msg->start);
1769   ds->deadline = GNUNET_TIME_absolute_ntoh (msg->deadline);
1770   ds->ciphertext = msg->ciphertext;
1771
1772   ds->share = GNUNET_SECRETSHARING_share_read (&msg[1], ntohs (msg->header.size) - sizeof *msg, NULL);
1773   // FIXME: probably should be break rather than assert
1774   GNUNET_assert (NULL != ds->share);
1775
1776   // FIXME: this is probably sufficient, but kdf/hash with all values would be nicer ...
1777   GNUNET_CRYPTO_hash (&msg->ciphertext, sizeof (struct GNUNET_SECRETSHARING_Ciphertext), &session_id);
1778
1779   ds->consensus = GNUNET_CONSENSUS_create (cfg,
1780                                            ds->share->num_peers,
1781                                            ds->share->peers,
1782                                            &session_id,
1783                                            ds->start,
1784                                            ds->deadline,
1785                                            &decrypt_new_element,
1786                                            ds);
1787
1788
1789   ds->info = GNUNET_new_array (ds->share->num_peers, struct DecryptPeerInfo);
1790   for (i = 0; i < ds->share->num_peers; i++)
1791   {
1792     ds->info[i].peer = ds->share->peers[i];
1793     ds->info[i].original_index = ds->share->original_indices[i];
1794   }
1795
1796   insert_decrypt_element (ds);
1797
1798   GNUNET_CONSENSUS_conclude (ds->consensus, decrypt_conclude, ds);
1799
1800   GNUNET_SERVER_receive_done (client, GNUNET_OK);
1801
1802   GNUNET_log (GNUNET_ERROR_TYPE_INFO, "decrypting with %u peers\n",
1803               ds->share->num_peers);
1804 }
1805
1806
1807 static void
1808 init_crypto_constants (void)
1809 {
1810   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_q, GCRYMPI_FMT_HEX,
1811                                      GNUNET_SECRETSHARING_ELGAMAL_Q_HEX, 0, NULL));
1812   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_p, GCRYMPI_FMT_HEX,
1813                                      GNUNET_SECRETSHARING_ELGAMAL_P_HEX, 0, NULL));
1814   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_g, GCRYMPI_FMT_HEX,
1815                                      GNUNET_SECRETSHARING_ELGAMAL_G_HEX, 0, NULL));
1816 }
1817
1818
1819 static struct KeygenSession *
1820 keygen_session_get (struct GNUNET_SERVER_Client *client)
1821 {
1822   struct KeygenSession *ks;
1823   for (ks = keygen_sessions_head; NULL != ks; ks = ks->next)
1824     if (ks->client == client)
1825       return ks;
1826   return NULL;
1827 }
1828
1829 static struct DecryptSession *
1830 decrypt_session_get (struct GNUNET_SERVER_Client *client)
1831 {
1832   struct DecryptSession *ds;
1833   for (ds = decrypt_sessions_head; NULL != ds; ds = ds->next)
1834     if (ds->client == client)
1835       return ds;
1836   return NULL;
1837 }
1838
1839
1840 /**
1841  * Clean up after a client has disconnected
1842  *
1843  * @param cls closure, unused
1844  * @param client the client to clean up after
1845  */
1846 static void
1847 handle_client_disconnect (void *cls, struct GNUNET_SERVER_Client *client)
1848 {
1849   struct KeygenSession *ks;
1850   struct DecryptSession *ds;
1851
1852   GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "handling client disconnect\n");
1853
1854   ks = keygen_session_get (client);
1855   if (NULL != ks)
1856     keygen_session_destroy (ks);
1857
1858   ds = decrypt_session_get (client);
1859   if (NULL != ds)
1860     decrypt_session_destroy (ds);
1861 }
1862
1863
1864 /**
1865  * Process template requests.
1866  *
1867  * @param cls closure
1868  * @param server the initialized server
1869  * @param c configuration to use
1870  */
1871 static void
1872 run (void *cls, struct GNUNET_SERVER_Handle *server,
1873      const struct GNUNET_CONFIGURATION_Handle *c)
1874 {
1875   static const struct GNUNET_SERVER_MessageHandler handlers[] = {
1876     {handle_client_keygen, NULL, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_GENERATE, 0},
1877     {handle_client_decrypt, NULL, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT, 0},
1878     {NULL, NULL, 0, 0}
1879   };
1880   cfg = c;
1881   srv = server;
1882   my_peer_private_key = GNUNET_CRYPTO_eddsa_key_create_from_configuration (c);
1883   if (NULL == my_peer_private_key)
1884   {
1885     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not access host private key\n");
1886     GNUNET_break (0);
1887     GNUNET_SCHEDULER_shutdown ();
1888     return;
1889   }
1890   init_crypto_constants ();
1891   if (GNUNET_OK != GNUNET_CRYPTO_get_peer_identity (cfg, &my_peer))
1892   {
1893     GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "could not retrieve host identity\n");
1894     GNUNET_break (0);
1895     GNUNET_SCHEDULER_shutdown ();
1896     return;
1897   }
1898   GNUNET_SERVER_add_handlers (server, handlers);
1899   GNUNET_SERVER_disconnect_notify (server, &handle_client_disconnect, NULL);
1900   GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &cleanup_task,
1901                                 NULL);
1902 }
1903
1904
1905 /**
1906  * The main function for the template service.
1907  *
1908  * @param argc number of arguments from the command line
1909  * @param argv command line arguments
1910  * @return 0 ok, 1 on error
1911  */
1912 int
1913 main (int argc, char *const *argv)
1914 {
1915   return (GNUNET_OK ==
1916           GNUNET_SERVICE_run (argc, argv, "secretsharing",
1917                               GNUNET_SERVICE_OPTION_NONE, &run, NULL)) ? 0 : 1;
1918 }
1919