d46d24e9d70aee2cae4ee95180be8e732ab3e5a5
[oweals/gnunet.git] / src / secretsharing / secretsharing_api.c
1 /*
2      This file is part of GNUnet.
3      (C) 2012 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/secretsharing_api.c
23  * @brief
24  * @author Florian Dold
25  */
26 #include "platform.h"
27 #include "gnunet_util_lib.h"
28 #include "gnunet_secretsharing_service.h"
29 #include "secretsharing.h"
30 #include <gcrypt.h>
31
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "secretsharing-api",__VA_ARGS__)
34
35 /**
36  * Session that will eventually establish a shared secred between
37  * the involved peers and allow encryption and cooperative decryption.
38  */
39 struct GNUNET_SECRETSHARING_Session
40 {
41   /**
42    * Client connected to the secretsharing service.
43    */
44   struct GNUNET_CLIENT_Connection *client;
45
46   /**
47    * Message queue for 'client'.
48    */
49   struct GNUNET_MQ_Handle *mq;
50
51   /**
52    * Called when the secret sharing is done.
53    */
54   GNUNET_SECRETSHARING_SecretReadyCallback secret_ready_cb;
55
56   /**
57    * Closure for 'secret_ready_cb'.
58    */
59   void *secret_ready_cls;
60 };
61
62
63 struct GNUNET_SECRETSHARING_DecryptionHandle
64 {
65   /**
66    * Client connected to the secretsharing service.
67    */
68   struct GNUNET_CLIENT_Connection *client;
69
70   /**
71    * Message queue for 'client'.
72    */
73   struct GNUNET_MQ_Handle *mq;
74
75   /**
76    * Called when the secret sharing is done.
77    */
78   GNUNET_SECRETSHARING_DecryptCallback decrypt_cb;
79
80   /**
81    * Closure for 'decrypt_cb'.
82    */
83   void *decrypt_cls;
84 };
85
86
87 /**
88  * The ElGamal prime field order as libgcrypt mpi.
89  * Initialized in #init_crypto_constants.
90  */
91 static gcry_mpi_t elgamal_q;
92
93 /**
94  * Modulus of the prime field used for ElGamal.
95  * Initialized in #init_crypto_constants.
96  */
97 static gcry_mpi_t elgamal_p;
98
99 /**
100  * Generator for prime field of order 'elgamal_q'.
101  * Initialized in #init_crypto_constants.
102  */
103 static gcry_mpi_t elgamal_g;
104
105
106 static void
107 ensure_elgamal_initialized (void)
108 {
109   if (NULL != elgamal_q)
110     return; /* looks like crypto is already initialized */
111
112   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_q, GCRYMPI_FMT_HEX,
113                                      GNUNET_SECRETSHARING_ELGAMAL_Q_HEX, 0, NULL));
114   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_p, GCRYMPI_FMT_HEX,
115                                      GNUNET_SECRETSHARING_ELGAMAL_P_HEX, 0, NULL));
116   GNUNET_assert (0 == gcry_mpi_scan (&elgamal_g, GCRYMPI_FMT_HEX,
117                                      GNUNET_SECRETSHARING_ELGAMAL_G_HEX, 0, NULL));
118 }
119
120
121 static void
122 handle_session_client_error (void *cls, enum GNUNET_MQ_Error error)
123 {
124   struct GNUNET_SECRETSHARING_Session *s = cls;
125
126   s->secret_ready_cb (s->secret_ready_cls, NULL, NULL, 0, NULL);
127 }
128
129
130 static void
131 handle_decrypt_client_error (void *cls, enum GNUNET_MQ_Error error)
132 {
133   struct GNUNET_SECRETSHARING_DecryptionHandle *dh = cls;
134   
135   dh->decrypt_cb (dh->decrypt_cls, NULL);
136 }
137
138
139 static void
140 handle_secret_ready (void *cls, const struct GNUNET_MessageHeader *msg)
141 {
142   struct GNUNET_SECRETSHARING_Session *session = cls;
143   struct GNUNET_SECRETSHARING_Share *share;
144   const struct GNUNET_SECRETSHARING_SecretReadyMessage *m = (const void *) msg;
145   size_t share_size;
146
147   share_size = ntohs (m->header.size) - sizeof *m;
148
149   share = GNUNET_SECRETSHARING_share_read (&m[1], share_size, NULL);
150
151   session->secret_ready_cb (session->secret_ready_cls,
152                       share, /* FIXME */
153                       &share->public_key,
154                       share->num_peers,
155                       (struct GNUNET_PeerIdentity *) &m[1]);
156
157   GNUNET_SECRETSHARING_session_destroy (session);
158 }
159
160
161 void
162 GNUNET_SECRETSHARING_session_destroy (struct GNUNET_SECRETSHARING_Session *session)
163 {
164   GNUNET_MQ_destroy (session->mq);
165   session->mq = NULL;
166   GNUNET_CLIENT_disconnect (session->client);
167   session->client = NULL;
168   GNUNET_free (session);
169 }
170
171
172 struct GNUNET_SECRETSHARING_Session *
173 GNUNET_SECRETSHARING_create_session (const struct GNUNET_CONFIGURATION_Handle *cfg,
174                                      unsigned int num_peers,
175                                      const struct GNUNET_PeerIdentity *peers,
176                                      const struct GNUNET_HashCode *session_id,
177                                      struct GNUNET_TIME_Absolute start,
178                                      struct GNUNET_TIME_Absolute deadline,
179                                      unsigned int threshold,
180                                      GNUNET_SECRETSHARING_SecretReadyCallback cb,
181                                      void *cls)
182 {
183   struct GNUNET_SECRETSHARING_Session *s;
184   struct GNUNET_MQ_Envelope *ev;
185   struct GNUNET_SECRETSHARING_CreateMessage *msg;
186   static const struct GNUNET_MQ_MessageHandler mq_handlers[] = {
187     {handle_secret_ready, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_SECRET_READY, 0},
188     GNUNET_MQ_HANDLERS_END
189   };
190
191
192   s = GNUNET_new (struct GNUNET_SECRETSHARING_Session);
193   s->client = GNUNET_CLIENT_connect ("secretsharing", cfg);
194   s->secret_ready_cb = cb;
195   s->secret_ready_cls = cls;
196   GNUNET_assert (NULL != s->client);
197
198   s->mq = GNUNET_MQ_queue_for_connection_client (s->client, mq_handlers,
199                                                    handle_session_client_error, s);
200   GNUNET_assert (NULL != s->mq);
201
202   ev = GNUNET_MQ_msg_extra (msg,
203                             num_peers * sizeof (struct GNUNET_PeerIdentity),
204                             GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_GENERATE);
205
206   msg->threshold = htons (threshold);
207   msg->num_peers = htons (num_peers);
208   msg->session_id = *session_id;
209   msg->start = GNUNET_TIME_absolute_hton (start);
210   msg->deadline = GNUNET_TIME_absolute_hton (deadline);
211   memcpy (&msg[1], peers, num_peers * sizeof (struct GNUNET_PeerIdentity));
212
213   GNUNET_MQ_send (s->mq, ev);
214
215   LOG (GNUNET_ERROR_TYPE_DEBUG, "secretsharing session created with %u peers\n",
216        num_peers);
217   return s;
218 }
219
220
221 static void
222 handle_decrypt_done (void *cls, const struct GNUNET_MessageHeader *msg)
223 {
224   struct GNUNET_SECRETSHARING_DecryptionHandle *dh = cls;
225   const struct GNUNET_SECRETSHARING_DecryptResponseMessage *m =
226       (const void *) msg;
227
228   const struct GNUNET_SECRETSHARING_Plaintext *plaintext;
229
230   if (m->success == 0)
231     plaintext = NULL;
232   else
233     plaintext = (void *) &m->plaintext;
234
235   dh->decrypt_cb (dh->decrypt_cls, plaintext);
236
237   GNUNET_SECRETSHARING_decrypt_cancel (dh);
238 }
239
240
241 /**
242  * Publish the given ciphertext for decryption.  Once a sufficient (>=k) number of peers has
243  * published the same value, it will be decrypted.
244  *
245  * When the operation is canceled, the decrypt_cb is not called anymore, but the calling
246  * peer may already have irrevocably contributed his share for the decryption of the value.
247  *
248  * @param share our secret share to use for decryption
249  * @param ciphertext ciphertext to publish in order to decrypt it (if enough peers agree)
250  * @param decrypt_cb callback called once the decryption succeeded
251  * @param decrypt_cb_cls closure for @a decrypt_cb
252  * @return handle to cancel the operation
253  */
254 struct GNUNET_SECRETSHARING_DecryptionHandle *
255 GNUNET_SECRETSHARING_decrypt (const struct GNUNET_CONFIGURATION_Handle *cfg,
256                               struct GNUNET_SECRETSHARING_Share *share,
257                               const struct GNUNET_SECRETSHARING_Ciphertext *ciphertext,
258                               struct GNUNET_TIME_Absolute start,
259                               struct GNUNET_TIME_Absolute deadline,
260                               GNUNET_SECRETSHARING_DecryptCallback decrypt_cb,
261                               void *decrypt_cb_cls)
262 {
263   struct GNUNET_SECRETSHARING_DecryptionHandle *s;
264   struct GNUNET_MQ_Envelope *ev;
265   struct GNUNET_SECRETSHARING_DecryptRequestMessage *msg;
266   static const struct GNUNET_MQ_MessageHandler mq_handlers[] = {
267     {handle_decrypt_done, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT_DONE, 0},
268     GNUNET_MQ_HANDLERS_END
269   };
270   size_t share_size;
271
272
273   s = GNUNET_new (struct GNUNET_SECRETSHARING_DecryptionHandle);
274   s->client = GNUNET_CLIENT_connect ("secretsharing", cfg);
275   s->decrypt_cb = decrypt_cb;
276   s->decrypt_cls = decrypt_cb_cls;
277   GNUNET_assert (NULL != s->client);
278
279   s->mq = GNUNET_MQ_queue_for_connection_client (s->client, mq_handlers,
280                                                  handle_decrypt_client_error, s);
281   GNUNET_assert (NULL != s->mq);
282
283   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, NULL, 0, &share_size));
284
285   ev = GNUNET_MQ_msg_extra (msg,
286                             share_size,
287                             GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT);
288
289   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, &msg[1], share_size, NULL));
290
291   msg->start = GNUNET_TIME_absolute_hton (start);
292   msg->deadline = GNUNET_TIME_absolute_hton (deadline);
293   msg->ciphertext = *ciphertext;
294
295   GNUNET_MQ_send (s->mq, ev);
296
297   LOG (GNUNET_ERROR_TYPE_DEBUG, "decrypt session created\n");
298   return s;
299 }
300
301
302 int
303 GNUNET_SECRETSHARING_plaintext_generate_i (struct GNUNET_SECRETSHARING_Plaintext *plaintext,
304                                            int64_t exponent)
305 {
306   int negative;
307   gcry_mpi_t x;
308
309   ensure_elgamal_initialized ();
310
311   GNUNET_assert (NULL != (x = gcry_mpi_new (0)));
312
313   negative = GNUNET_NO;
314   if (exponent < 0)
315   {
316     negative = GNUNET_YES;
317     exponent = -exponent;
318   }
319
320   gcry_mpi_set_ui (x, exponent);
321
322   gcry_mpi_powm (x, elgamal_g, x, elgamal_p);
323
324   if (GNUNET_YES == negative)
325   {
326     int res;
327     res = gcry_mpi_invm (x, x, elgamal_p);
328     if (0 == res)
329       return GNUNET_SYSERR;
330   }
331
332   GNUNET_CRYPTO_mpi_print_unsigned (plaintext, sizeof (struct GNUNET_SECRETSHARING_Plaintext), x);
333
334   return GNUNET_OK;
335 }
336
337
338 /**
339  * Encrypt a value.  This operation is executed locally, no communication is
340  * necessary.
341  *
342  * This is a helper function, encryption can be done soley with a session's public key
343  * and the crypto system parameters.
344  *
345  * @param public_key public key to use for decryption
346  * @param message message to encrypt
347  * @param message_size number of bytes in @a message
348  * @param result_ciphertext pointer to store the resulting ciphertext
349  * @return #GNUNET_YES on succes, #GNUNET_SYSERR if the message is invalid (invalid range)
350  */
351 int
352 GNUNET_SECRETSHARING_encrypt (const struct GNUNET_SECRETSHARING_PublicKey *public_key,
353                               const struct GNUNET_SECRETSHARING_Plaintext *plaintext,
354                               struct GNUNET_SECRETSHARING_Ciphertext *result_ciphertext)
355 {
356   /* pubkey */
357   gcry_mpi_t h;
358   /* nonce */
359   gcry_mpi_t y;
360   /* plaintext message */
361   gcry_mpi_t m;
362   /* temp value */
363   gcry_mpi_t tmp;
364
365   ensure_elgamal_initialized ();
366
367   GNUNET_assert (NULL != (h = gcry_mpi_new (0)));
368   GNUNET_assert (NULL != (y = gcry_mpi_new (0)));
369   GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
370
371   GNUNET_CRYPTO_mpi_scan_unsigned (&h, public_key, sizeof *public_key);
372   GNUNET_CRYPTO_mpi_scan_unsigned (&m, plaintext, sizeof *plaintext);
373
374   // Randomize y such that 0 < y < elgamal_q.
375   // The '- 1' is necessary as bitlength(q) = bitlength(p) - 1.
376   do 
377   {
378     gcry_mpi_randomize (y, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
379   } while ((gcry_mpi_cmp_ui (y, 0) == 0) || (gcry_mpi_cmp (y, elgamal_q) >= 0));
380
381   // tmp <- g^y
382   gcry_mpi_powm (tmp, elgamal_g, y, elgamal_p);
383   // write tmp to c1
384   GNUNET_CRYPTO_mpi_print_unsigned (&result_ciphertext->c1_bits,
385                                     GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
386   
387   // tmp <- h^y
388   gcry_mpi_powm (tmp, h, y, elgamal_p);
389   // tmp <- tmp * m 
390   gcry_mpi_mulm (tmp, tmp, m, elgamal_p);
391   // write tmp to c2
392   GNUNET_CRYPTO_mpi_print_unsigned (&result_ciphertext->c2_bits,
393                                     GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
394
395   return GNUNET_OK;
396 }
397
398
399 void
400 GNUNET_SECRETSHARING_decrypt_cancel (struct GNUNET_SECRETSHARING_DecryptionHandle *h)
401 {
402   GNUNET_MQ_destroy (h->mq);
403   h->mq = NULL;
404   GNUNET_CLIENT_disconnect (h->client);
405   h->client = NULL;
406   GNUNET_free (h);
407 }
408
409
410