- re-added testcase for crypto-paillier
[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 deadline,
178                                      unsigned int threshold,
179                                      GNUNET_SECRETSHARING_SecretReadyCallback cb,
180                                      void *cls)
181 {
182   struct GNUNET_SECRETSHARING_Session *s;
183   struct GNUNET_MQ_Envelope *ev;
184   struct GNUNET_SECRETSHARING_CreateMessage *msg;
185   static const struct GNUNET_MQ_MessageHandler mq_handlers[] = {
186     {handle_secret_ready, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_SECRET_READY, 0},
187     GNUNET_MQ_HANDLERS_END
188   };
189
190
191   s = GNUNET_new (struct GNUNET_SECRETSHARING_Session);
192   s->client = GNUNET_CLIENT_connect ("secretsharing", cfg);
193   s->secret_ready_cb = cb;
194   s->secret_ready_cls = cls;
195   GNUNET_assert (NULL != s->client);
196
197   s->mq = GNUNET_MQ_queue_for_connection_client (s->client, mq_handlers,
198                                                    handle_session_client_error, s);
199   GNUNET_assert (NULL != s->mq);
200
201   ev = GNUNET_MQ_msg_extra (msg,
202                             num_peers * sizeof (struct GNUNET_PeerIdentity),
203                             GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_GENERATE);
204
205   msg->threshold = htons (threshold);
206   msg->num_peers = htons (num_peers);
207   msg->session_id = *session_id;
208   msg->deadline = GNUNET_TIME_absolute_hton (deadline);
209   memcpy (&msg[1], peers, num_peers * sizeof (struct GNUNET_PeerIdentity));
210
211   GNUNET_MQ_send (s->mq, ev);
212
213   LOG (GNUNET_ERROR_TYPE_DEBUG, "secretsharing session created with %u peers\n",
214        num_peers);
215   return s;
216 }
217
218
219 static void
220 handle_decrypt_done (void *cls, const struct GNUNET_MessageHeader *msg)
221 {
222   struct GNUNET_SECRETSHARING_DecryptionHandle *dh = cls;
223   const struct GNUNET_SECRETSHARING_DecryptResponseMessage *m =
224       (const void *) msg;
225
226   const struct GNUNET_SECRETSHARING_Plaintext *plaintext;
227
228   if (m->success == 0)
229     plaintext = NULL;
230   else
231     plaintext = (void *) &m->plaintext;
232
233   dh->decrypt_cb (dh->decrypt_cls, plaintext);
234
235   GNUNET_SECRETSHARING_decrypt_cancel (dh);
236 }
237
238
239 /**
240  * Publish the given ciphertext for decryption.  Once a sufficient (>=k) number of peers has
241  * published the same value, it will be decrypted.
242  *
243  * When the operation is canceled, the decrypt_cb is not called anymore, but the calling
244  * peer may already have irrevocably contributed his share for the decryption of the value.
245  *
246  * @param share our secret share to use for decryption
247  * @param ciphertext ciphertext to publish in order to decrypt it (if enough peers agree)
248  * @param decrypt_cb callback called once the decryption succeeded
249  * @param decrypt_cb_cls closure for @a decrypt_cb
250  * @return handle to cancel the operation
251  */
252 struct GNUNET_SECRETSHARING_DecryptionHandle *
253 GNUNET_SECRETSHARING_decrypt (const struct GNUNET_CONFIGURATION_Handle *cfg,
254                               struct GNUNET_SECRETSHARING_Share *share,
255                               const struct GNUNET_SECRETSHARING_Ciphertext *ciphertext,
256                               struct GNUNET_TIME_Absolute deadline,
257                               GNUNET_SECRETSHARING_DecryptCallback decrypt_cb,
258                               void *decrypt_cb_cls)
259 {
260   struct GNUNET_SECRETSHARING_DecryptionHandle *s;
261   struct GNUNET_MQ_Envelope *ev;
262   struct GNUNET_SECRETSHARING_DecryptRequestMessage *msg;
263   static const struct GNUNET_MQ_MessageHandler mq_handlers[] = {
264     {handle_decrypt_done, GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT_DONE, 0},
265     GNUNET_MQ_HANDLERS_END
266   };
267   size_t share_size;
268
269
270   s = GNUNET_new (struct GNUNET_SECRETSHARING_DecryptionHandle);
271   s->client = GNUNET_CLIENT_connect ("secretsharing", cfg);
272   s->decrypt_cb = decrypt_cb;
273   s->decrypt_cls = decrypt_cb_cls;
274   GNUNET_assert (NULL != s->client);
275
276   s->mq = GNUNET_MQ_queue_for_connection_client (s->client, mq_handlers,
277                                                  handle_decrypt_client_error, s);
278   GNUNET_assert (NULL != s->mq);
279
280   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, NULL, 0, &share_size));
281
282   ev = GNUNET_MQ_msg_extra (msg,
283                             share_size,
284                             GNUNET_MESSAGE_TYPE_SECRETSHARING_CLIENT_DECRYPT);
285
286   GNUNET_assert (GNUNET_OK == GNUNET_SECRETSHARING_share_write (share, &msg[1], share_size, NULL));
287
288   msg->deadline = GNUNET_TIME_absolute_hton (deadline);
289   msg->ciphertext = *ciphertext;
290
291   GNUNET_MQ_send (s->mq, ev);
292
293   LOG (GNUNET_ERROR_TYPE_DEBUG, "decrypt session created\n");
294   return s;
295 }
296
297
298 int
299 GNUNET_SECRETSHARING_plaintext_generate_i (struct GNUNET_SECRETSHARING_Plaintext *plaintext,
300                                            int64_t exponent)
301 {
302   int negative;
303   gcry_mpi_t x;
304
305   ensure_elgamal_initialized ();
306
307   GNUNET_assert (NULL != (x = gcry_mpi_new (0)));
308
309   negative = GNUNET_NO;
310   if (exponent < 0)
311   {
312     negative = GNUNET_YES;
313     exponent = -exponent;
314   }
315
316   gcry_mpi_set_ui (x, exponent);
317
318   gcry_mpi_powm (x, elgamal_g, x, elgamal_p);
319
320   if (GNUNET_YES == negative)
321   {
322     int res;
323     res = gcry_mpi_invm (x, x, elgamal_p);
324     if (0 == res)
325       return GNUNET_SYSERR;
326   }
327
328   GNUNET_CRYPTO_mpi_print_unsigned (plaintext, sizeof (struct GNUNET_SECRETSHARING_Plaintext), x);
329
330   return GNUNET_OK;
331 }
332
333
334 /**
335  * Encrypt a value.  This operation is executed locally, no communication is
336  * necessary.
337  *
338  * This is a helper function, encryption can be done soley with a session's public key
339  * and the crypto system parameters.
340  *
341  * @param public_key public key to use for decryption
342  * @param message message to encrypt
343  * @param message_size number of bytes in @a message
344  * @param result_ciphertext pointer to store the resulting ciphertext
345  * @return #GNUNET_YES on succes, #GNUNET_SYSERR if the message is invalid (invalid range)
346  */
347 int
348 GNUNET_SECRETSHARING_encrypt (const struct GNUNET_SECRETSHARING_PublicKey *public_key,
349                               const struct GNUNET_SECRETSHARING_Plaintext *plaintext,
350                               struct GNUNET_SECRETSHARING_Ciphertext *result_ciphertext)
351 {
352   /* pubkey */
353   gcry_mpi_t h;
354   /* nonce */
355   gcry_mpi_t y;
356   /* plaintext message */
357   gcry_mpi_t m;
358   /* temp value */
359   gcry_mpi_t tmp;
360
361   ensure_elgamal_initialized ();
362
363   GNUNET_assert (NULL != (h = gcry_mpi_new (0)));
364   GNUNET_assert (NULL != (y = gcry_mpi_new (0)));
365   GNUNET_assert (NULL != (tmp = gcry_mpi_new (0)));
366
367   GNUNET_CRYPTO_mpi_scan_unsigned (&h, public_key, sizeof *public_key);
368   GNUNET_CRYPTO_mpi_scan_unsigned (&m, plaintext, sizeof *plaintext);
369
370   // Randomize y such that 0 < y < elgamal_q.
371   // The '- 1' is necessary as bitlength(q) = bitlength(p) - 1.
372   do 
373   {
374     gcry_mpi_randomize (y, GNUNET_SECRETSHARING_ELGAMAL_BITS - 1, GCRY_WEAK_RANDOM);
375   } while ((gcry_mpi_cmp_ui (y, 0) == 0) || (gcry_mpi_cmp (y, elgamal_q) >= 0));
376
377   // tmp <- g^y
378   gcry_mpi_powm (tmp, elgamal_g, y, elgamal_p);
379   // write tmp to c1
380   GNUNET_CRYPTO_mpi_print_unsigned (&result_ciphertext->c1_bits,
381                                     GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
382   
383   // tmp <- h^y
384   gcry_mpi_powm (tmp, h, y, elgamal_p);
385   // tmp <- tmp * m 
386   gcry_mpi_mulm (tmp, tmp, m, elgamal_p);
387   // write tmp to c2
388   GNUNET_CRYPTO_mpi_print_unsigned (&result_ciphertext->c2_bits,
389                                     GNUNET_SECRETSHARING_ELGAMAL_BITS / 8, tmp);
390
391   return GNUNET_OK;
392 }
393
394
395 void
396 GNUNET_SECRETSHARING_decrypt_cancel (struct GNUNET_SECRETSHARING_DecryptionHandle *h)
397 {
398   GNUNET_MQ_destroy (h->mq);
399   h->mq = NULL;
400   GNUNET_CLIENT_disconnect (h->client);
401   h->client = NULL;
402   GNUNET_free (h);
403 }
404
405
406