]> de.git.xonotic.org Git - xonotic/d0_blind_id.git/blob - d0_bignum-gmp.c
export setmallocfuncs properly
[xonotic/d0_blind_id.git] / d0_bignum-gmp.c
1 /*
2  * FILE:        d0_bignum-gmp.c
3  * AUTHOR:      Rudolf Polzer - divVerent@xonotic.org
4  * 
5  * Copyright (c) 2010, Rudolf Polzer
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the copyright holder nor the names of contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  * 
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTOR(S) ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTOR(S) BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  * $Format:commit %H$
33  * $Id$
34  */
35
36 /* NOTE: this file links against libgmp (http://gmplib.org), which is under the
37  * Lesser General Public License 2.1 or later. You may have to abide to its
38  * terms too if you use this file.
39  * To alternatively link to OpenSSL, provide the option --with-openssl to
40  * ./configure.
41  */
42
43 #ifdef WIN32
44 #include <windows.h>
45 #include <wincrypt.h>
46 #endif
47
48 #include "d0_bignum.h"
49
50 #include <gmp.h>
51 #include <string.h>
52 #include <stdlib.h>
53
54 struct d0_bignum_s
55 {
56         mpz_t z;
57 };
58
59 static gmp_randstate_t RANDSTATE;
60 static d0_bignum_t temp;
61 static void *tempmutex = NULL; // hold this mutex when using RANDSTATE or temp
62
63 #include <time.h>
64 #include <stdio.h>
65
66 D0_WARN_UNUSED_RESULT D0_BOOL d0_bignum_INITIALIZE(void)
67 {
68         FILE *f;
69         D0_BOOL ret = 1;
70         unsigned char buf[256];
71
72         tempmutex = d0_createmutex();
73         d0_lockmutex(tempmutex);
74
75         d0_bignum_init(&temp);
76         gmp_randinit_mt(RANDSTATE);
77         gmp_randseed_ui(RANDSTATE, time(NULL));
78         * (time_t *) (&buf[0]) = time(0); // if everything else fails, we use the current time + uninitialized data
79 #ifdef WIN32
80         {
81                 HCRYPTPROV hCryptProv;
82                 if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT))
83                 {
84                         if(!CryptGenRandom(hCryptProv, sizeof(buf), (PBYTE) &buf[0]))
85                         {
86                                 fprintf(stderr, "WARNING: could not initialize random number generator (CryptGenRandom failed)\n");
87                                 ret = 0;
88                         }
89                         CryptReleaseContext(hCryptProv, 0);
90                 }
91                 else if(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET))
92                 {
93                         if(!CryptGenRandom(hCryptProv, sizeof(buf), (PBYTE) &buf[0]))
94                         {
95                                 fprintf(stderr, "WARNING: could not initialize random number generator (CryptGenRandom failed)\n");
96                                 ret = 0;
97                         }
98                         CryptReleaseContext(hCryptProv, 0);
99                 }
100                 else
101                 {
102                         fprintf(stderr, "WARNING: could not initialize random number generator (CryptAcquireContext failed)\n");
103                         ret = 0;
104                 }
105         }
106 #else
107         f = fopen("/dev/urandom", "rb");
108         if(!f)
109                 f = fopen("/dev/random", "rb");
110         if(f)
111         {
112                 setbuf(f, NULL);
113                 if(fread(buf, sizeof(buf), 1, f) != 1)
114                 {
115                         fprintf(stderr, "WARNING: could not initialize random number generator (read from random device failed)\n");
116                         ret = 0;
117                 }
118                 fclose(f);
119         }
120         else
121         {
122                 fprintf(stderr, "WARNING: could not initialize random number generator (no random device found)\n");
123                 ret = 0;
124         }
125 #endif
126
127         mpz_import(temp.z, sizeof(buf), 1, 1, 0, 0, buf);
128         gmp_randseed(RANDSTATE, temp.z);
129
130         d0_unlockmutex(tempmutex);
131
132         return ret;
133 }
134
135 void d0_bignum_SHUTDOWN(void)
136 {
137         d0_lockmutex(tempmutex);
138
139         d0_bignum_clear(&temp);
140         gmp_randclear(RANDSTATE);
141
142         d0_unlockmutex(tempmutex);
143         d0_destroymutex(tempmutex);
144         tempmutex = NULL;
145 }
146
147 D0_BOOL d0_iobuf_write_bignum(d0_iobuf_t *buf, const d0_bignum_t *bignum)
148 {
149         static __thread unsigned char numbuf[65536];
150         size_t count = 0;
151         numbuf[0] = mpz_sgn(bignum->z) & 3;
152         if((numbuf[0] & 3) != 0) // nonzero
153         {
154                 count = (mpz_sizeinbase(bignum->z, 2) + 7) / 8;
155                 if(count > sizeof(numbuf) - 1)
156                         return 0;
157                 mpz_export(numbuf+1, &count, 1, 1, 0, 0, bignum->z);
158         }
159         return d0_iobuf_write_packet(buf, numbuf, count + 1);
160 }
161
162 d0_bignum_t *d0_iobuf_read_bignum(d0_iobuf_t *buf, d0_bignum_t *bignum)
163 {
164         static __thread unsigned char numbuf[65536];
165         size_t count = sizeof(numbuf);
166         if(!d0_iobuf_read_packet(buf, numbuf, &count))
167                 return NULL;
168         if(count < 1)
169                 return NULL;
170         if(!bignum) bignum = d0_bignum_new(); if(!bignum) return NULL;
171         if(numbuf[0] & 3) // nonzero
172         {
173                 mpz_import(bignum->z, count-1, 1, 1, 0, 0, numbuf+1);
174                 if(numbuf[0] & 2) // negative
175                         mpz_neg(bignum->z, bignum->z);
176         }
177         else // zero
178         {
179                 mpz_set_ui(bignum->z, 0);
180         }
181         return bignum;
182 }
183
184 ssize_t d0_bignum_export_unsigned(const d0_bignum_t *bignum, void *buf, size_t bufsize)
185 {
186         size_t count;
187         count = (mpz_sizeinbase(bignum->z, 2) + 7) / 8;
188         if(count > bufsize)
189                 return -1;
190         if(bufsize > count)
191         {
192                 // pad from left (big endian numbers!)
193                 memset(buf, 0, bufsize - count);
194                 buf += bufsize - count;
195         }
196         bufsize = count;
197         mpz_export(buf, &bufsize, 1, 1, 0, 0, bignum->z);
198         if(bufsize > count)
199         {
200                 // REALLY BAD
201                 // mpz_sizeinbase lied to us
202                 // buffer overflow
203                 // there is no sane way whatsoever to handle this
204                 abort();
205         }
206         if(bufsize < count)
207         {
208                 // BAD
209                 // mpz_sizeinbase lied to us
210                 // move the number
211                 if(count == 0)
212                 {
213                         memset(buf, 0, count);
214                 }
215                 else
216                 {
217                         memmove(buf + count - bufsize, buf, bufsize);
218                         memset(buf, 0, count - bufsize);
219                 }
220         }
221         return bufsize;
222 }
223
224 d0_bignum_t *d0_bignum_import_unsigned(d0_bignum_t *bignum, const void *buf, size_t bufsize)
225 {
226         size_t count;
227         if(!bignum) bignum = d0_bignum_new(); if(!bignum) return NULL;
228         mpz_import(bignum->z, bufsize, 1, 1, 0, 0, buf);
229         return bignum;
230 }
231
232 d0_bignum_t *d0_bignum_new(void)
233 {
234         d0_bignum_t *b = d0_malloc(sizeof(d0_bignum_t));
235         mpz_init(b->z);
236         return b;
237 }
238
239 void d0_bignum_free(d0_bignum_t *a)
240 {
241         mpz_clear(a->z);
242         d0_free(a);
243 }
244
245 void d0_bignum_init(d0_bignum_t *b)
246 {
247         mpz_init(b->z);
248 }
249
250 void d0_bignum_clear(d0_bignum_t *a)
251 {
252         mpz_clear(a->z);
253 }
254
255 size_t d0_bignum_size(const d0_bignum_t *r)
256 {
257         return mpz_sizeinbase(r->z, 2);
258 }
259
260 int d0_bignum_cmp(const d0_bignum_t *a, const d0_bignum_t *b)
261 {
262         return mpz_cmp(a->z, b->z);
263 }
264
265 d0_bignum_t *d0_bignum_rand_range(d0_bignum_t *r, const d0_bignum_t *min, const d0_bignum_t *max)
266 {
267         if(!r) r = d0_bignum_new(); if(!r) return NULL;
268         d0_lockmutex(tempmutex);
269         mpz_sub(temp.z, max->z, min->z);
270         mpz_urandomm(r->z, RANDSTATE, temp.z);
271         d0_unlockmutex(tempmutex);
272         mpz_add(r->z, r->z, min->z);
273         return r;
274 }
275
276 d0_bignum_t *d0_bignum_rand_bit_atmost(d0_bignum_t *r, size_t n)
277 {
278         if(!r) r = d0_bignum_new(); if(!r) return NULL;
279         d0_lockmutex(tempmutex);
280         mpz_urandomb(r->z, RANDSTATE, n);
281         d0_unlockmutex(tempmutex);
282         return r;
283 }
284
285 d0_bignum_t *d0_bignum_rand_bit_exact(d0_bignum_t *r, size_t n)
286 {
287         if(!r) r = d0_bignum_new(); if(!r) return NULL;
288         d0_lockmutex(tempmutex);
289         mpz_urandomb(r->z, RANDSTATE, n-1);
290         d0_unlockmutex(tempmutex);
291         mpz_setbit(r->z, n-1);
292         return r;
293 }
294
295 d0_bignum_t *d0_bignum_zero(d0_bignum_t *r)
296 {
297         return d0_bignum_int(r, 0);
298 }
299
300 d0_bignum_t *d0_bignum_one(d0_bignum_t *r)
301 {
302         return d0_bignum_int(r, 1);
303 }
304
305 d0_bignum_t *d0_bignum_int(d0_bignum_t *r, int n)
306 {
307         if(!r) r = d0_bignum_new(); if(!r) return NULL;
308         mpz_set_si(r->z, n);
309         return r;
310 }
311
312 d0_bignum_t *d0_bignum_mov(d0_bignum_t *r, const d0_bignum_t *a)
313 {
314         if(r == a)
315                 return r; // trivial
316         if(!r) r = d0_bignum_new(); if(!r) return NULL;
317         mpz_set(r->z, a->z);
318         return r;
319 }
320
321 d0_bignum_t *d0_bignum_neg(d0_bignum_t *r, const d0_bignum_t *a)
322 {
323         if(!r) r = d0_bignum_new(); if(!r) return NULL;
324         mpz_neg(r->z, a->z);
325         return r;
326 }
327
328 d0_bignum_t *d0_bignum_shl(d0_bignum_t *r, const d0_bignum_t *a, ssize_t n)
329 {
330         if(!r) r = d0_bignum_new(); if(!r) return NULL;
331         if(n > 0)
332                 mpz_mul_2exp(r->z, a->z, n);
333         else if(n < 0)
334                 mpz_fdiv_q_2exp(r->z, a->z, -n);
335         else
336                 mpz_set(r->z, a->z);
337         return r;
338 }
339
340 d0_bignum_t *d0_bignum_add(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
341 {
342         if(!r) r = d0_bignum_new(); if(!r) return NULL;
343         mpz_add(r->z, a->z, b->z);
344         return r;
345 }
346
347 d0_bignum_t *d0_bignum_sub(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
348 {
349         if(!r) r = d0_bignum_new(); if(!r) return NULL;
350         mpz_sub(r->z, a->z, b->z);
351         return r;
352 }
353
354 d0_bignum_t *d0_bignum_mul(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b)
355 {
356         if(!r) r = d0_bignum_new(); if(!r) return NULL;
357         mpz_mul(r->z, a->z, b->z);
358         return r;
359 }
360
361 d0_bignum_t *d0_bignum_divmod(d0_bignum_t *q, d0_bignum_t *m, const d0_bignum_t *a, const d0_bignum_t *b)
362 {
363         if(!q && !m)
364                 m = d0_bignum_new();
365         if(q)
366                 if(m)
367                         mpz_fdiv_qr(q->z, m->z, a->z, b->z);
368                 else
369                         mpz_fdiv_q(q->z, a->z, b->z);
370         else
371                 mpz_fdiv_r(m->z, a->z, b->z);
372         if(m)
373                 return m;
374         else
375                 return q;
376 }
377
378 d0_bignum_t *d0_bignum_mod_add(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
379 {
380         r = d0_bignum_add(r, a, b);
381         mpz_fdiv_r(r->z, r->z, m->z);
382         return r;
383 }
384
385 d0_bignum_t *d0_bignum_mod_sub(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
386 {
387         r = d0_bignum_sub(r, a, b);
388         mpz_fdiv_r(r->z, r->z, m->z);
389         return r;
390 }
391
392 d0_bignum_t *d0_bignum_mod_mul(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
393 {
394         r = d0_bignum_mul(r, a, b);
395         mpz_fdiv_r(r->z, r->z, m->z);
396         return r;
397 }
398
399 d0_bignum_t *d0_bignum_mod_pow(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *b, const d0_bignum_t *m)
400 {
401         if(!r) r = d0_bignum_new(); if(!r) return NULL;
402         mpz_powm(r->z, a->z, b->z, m->z);
403         return r;
404 }
405
406 D0_BOOL d0_bignum_mod_inv(d0_bignum_t *r, const d0_bignum_t *a, const d0_bignum_t *m)
407 {
408         // here, r MUST be set, as otherwise we cannot return error state!
409         return mpz_invert(r->z, a->z, m->z);
410 }
411
412 int d0_bignum_isprime(const d0_bignum_t *r, int param)
413 {
414         return mpz_probab_prime_p(r->z, param);
415 }
416
417 d0_bignum_t *d0_bignum_gcd(d0_bignum_t *r, d0_bignum_t *s, d0_bignum_t *t, const d0_bignum_t *a, const d0_bignum_t *b)
418 {
419         if(!r) r = d0_bignum_new(); if(!r) return NULL;
420         if(s)
421                 mpz_gcdext(r->z, s->z, t ? t->z : NULL, a->z, b->z);
422         else if(t)
423                 mpz_gcdext(r->z, t->z, NULL, b->z, a->z);
424         else
425                 mpz_gcd(r->z, a->z, b->z);
426         return r;
427 }
428
429 char *d0_bignum_tostring(const d0_bignum_t *x, unsigned int base)
430 {
431         return mpz_get_str(NULL, base, x->z);
432 }