chiark / gitweb /
cleanup: Various aesthetic fiddlings of little consequence.
[catacomb] / mpreduce.c
1 /* -*-c-*-
2  *
3  * $Id$
4  *
5  * Efficient reduction modulo nice primes
6  *
7  * (c) 2004 Straylight/Edgeware
8  */
9
10 /*----- Licensing notice --------------------------------------------------* 
11  *
12  * This file is part of Catacomb.
13  *
14  * Catacomb is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU Library General Public License as
16  * published by the Free Software Foundation; either version 2 of the
17  * License, or (at your option) any later version.
18  * 
19  * Catacomb is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22  * GNU Library General Public License for more details.
23  * 
24  * You should have received a copy of the GNU Library General Public
25  * License along with Catacomb; if not, write to the Free
26  * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
27  * MA 02111-1307, USA.
28  */
29
30 /*----- Header files ------------------------------------------------------*/
31
32 #include <mLib/darray.h>
33 #include <mLib/macros.h>
34
35 #include "mp.h"
36 #include "mpreduce.h"
37 #include "mpreduce-exp.h"
38
39 /*----- Data structures ---------------------------------------------------*/
40
41 DA_DECL(instr_v, mpreduce_instr);
42
43 /*----- Main code ---------------------------------------------------------*/
44
45 /* --- @mpreduce_create@ --- *
46  *
47  * Arguments:   @gfreduce *r@ = structure to fill in
48  *              @mp *x@ = an integer
49  *
50  * Returns:     Zero if successful; nonzero on failure.
51  *
52  * Use:         Initializes a context structure for reduction.
53  */
54
55 int mpreduce_create(mpreduce *r, mp *p)
56 {
57   mpscan sc;
58   enum { Z = 0, Z1 = 2, X = 4, X0 = 6 };
59   unsigned st = Z;
60   instr_v iv = DA_INIT;
61   unsigned long d, i;
62   unsigned op;
63   size_t w, b;
64
65   /* --- Fill in the easy stuff --- */
66
67   if (!MP_POSP(p))
68     return (-1);
69   d = mp_bits(p);
70   r->lim = d/MPW_BITS;
71   r->s = d%MPW_BITS;
72   if (r->s)
73     r->lim++;
74   r->p = mp_copy(p);
75
76   /* --- Stash a new instruction --- */
77
78 #define INSTR(op_, argx_, argy_) do {                                   \
79   DA_ENSURE(&iv, 1);                                                    \
80   DA(&iv)[DA_LEN(&iv)].op = (op_);                                      \
81   DA(&iv)[DA_LEN(&iv)].argx = (argx_);                                  \
82   DA(&iv)[DA_LEN(&iv)].argy = (argy_);                                  \
83   DA_EXTEND(&iv, 1);                                                    \
84 } while (0)
85
86   /* --- Main loop --- *
87    *
88    * A simple state machine decomposes @p@ conveniently into positive and
89    * negative powers of 2.  The pure form of the state machine is left below
90    * for reference (and in case I need inspiration for a NAF exponentiator).
91    */
92
93 #ifdef DEBUG
94   for (i = 0, mp_scan(&sc, p); mp_step(&sc); i++) {
95     switch (st | mp_bit(&sc)) {
96       case  Z | 1: st = Z1; break;
97       case Z1 | 0: st =  Z; printf("+ %lu\n", i - 1); break;
98       case Z1 | 1: st =  X; printf("- %lu\n", i - 1); break;
99       case  X | 0: st = X0; break;
100       case X0 | 1: st =  X; printf("- %lu\n", i - 1); break;
101       case X0 | 0: st =  Z; printf("+ %lu\n", i - 1); break;
102     }
103   }
104   if (st >= X) printf("+ %lu\n", i);
105 #endif
106
107   for (i = 0, mp_scan(&sc, p); i < d  - 1 && mp_step(&sc); i++) {
108     switch (st | mp_bit(&sc)) {
109       case  Z | 1: st = Z1; break;
110       case Z1 | 0: st =  Z; op = MPRI_SUB; goto instr;
111       case Z1 | 1: st =  X; op = MPRI_ADD; goto instr;
112       case  X | 0: st = X0; break;
113       case X0 | 1: st =  X; op = MPRI_ADD; goto instr;
114       case X0 | 0: st =  Z; op = MPRI_SUB; goto instr;
115       instr:
116         w = (d - i)/MPW_BITS + 1;
117         b = (MPW_BITS + i - d - 1)%MPW_BITS;
118         INSTR(op | !!b, w, b);
119     }
120   }
121   if ((DA(&iv)[DA_LEN(&iv) - 1].op & ~1u) == MPRI_SUB) {
122     mp_drop(r->p);
123     DA_DESTROY(&iv);
124     return (-1);
125   }
126
127 #undef INSTR
128
129   /* --- Wrap up --- */
130
131   r->in = DA_LEN(&iv);
132   if (!r->s) {
133     r->iv = xmalloc(r->in * sizeof(mpreduce_instr));
134     memcpy(r->iv, DA(&iv), r->in * sizeof(mpreduce_instr));
135   } else {
136     r->iv = xmalloc(r->in * 2 * sizeof(mpreduce_instr));
137     for (i = 0; i < r->in; i++) {
138       r->iv[i] = DA(&iv)[i];
139       op = r->iv[i].op & ~1u;
140       w = r->iv[i].argx;
141       b = r->iv[i].argy;
142       b += r->s;
143       if (b >= MPW_BITS) {
144         b -= MPW_BITS;
145         w--;
146       }
147       if (b) op |= 1;
148       r->iv[i + r->in].op = op;
149       r->iv[i + r->in].argx = w;
150       r->iv[i + r->in].argy = b;
151     }
152   }
153   DA_DESTROY(&iv);
154   return (0);
155 }
156
157 /* --- @mpreduce_destroy@ --- *
158  *
159  * Arguments:   @mpreduce *r@ = structure to free
160  *
161  * Returns:     ---
162  *
163  * Use:         Reclaims the resources from a reduction context.
164  */
165
166 void mpreduce_destroy(mpreduce *r)
167 {
168   mp_drop(r->p);
169   xfree(r->iv);
170 }
171
172 /* --- @mpreduce_dump@ --- *
173  *
174  * Arguments:   @mpreduce *r@ = structure to dump
175  *              @FILE *fp@ = file to dump on
176  *
177  * Returns:     ---
178  *
179  * Use:         Dumps a reduction context.
180  */
181
182 void mpreduce_dump(mpreduce *r, FILE *fp)
183 {
184   size_t i;
185   static const char *opname[] = { "add", "addshift", "sub", "subshift" };
186
187   fprintf(fp, "mod = "); mp_writefile(r->p, fp, 16);
188   fprintf(fp, "\n  lim = %lu; s = %d\n", (unsigned long)r->lim, r->s);
189   for (i = 0; i < r->in; i++) {
190     assert(r->iv[i].op < N(opname));
191     fprintf(fp, "  %s %lu %lu\n",
192             opname[r->iv[i].op],
193             (unsigned long)r->iv[i].argx,
194             (unsigned long)r->iv[i].argy);
195   }
196   if (r->s) {
197     fprintf(fp, "tail end charlie\n");
198     for (i = r->in; i < 2 * r->in; i++) {
199       assert(r->iv[i].op < N(opname));
200       fprintf(fp, "  %s %lu %lu\n",
201               opname[r->iv[i].op],
202               (unsigned long)r->iv[i].argx,
203               (unsigned long)r->iv[i].argy);
204     }
205   }
206 }
207
208 /* --- @mpreduce_do@ --- *
209  *
210  * Arguments:   @mpreduce *r@ = reduction context
211  *              @mp *d@ = destination
212  *              @mp *x@ = source
213  *
214  * Returns:     Destination, @x@ reduced modulo the reduction poly.
215  */
216
217 static void run(const mpreduce_instr *i, const mpreduce_instr *il,
218                 mpw *v, mpw z)
219 {
220   for (; i < il; i++) {
221 #ifdef DEBUG
222     mp vv;
223     mp_build(&vv, v - i->argx, v + 1);
224     printf("  0x"); mp_writefile(&vv, stdout, 16);
225     printf(" %c (0x%lx << %u) == 0x",
226            (i->op & ~1u) == MPRI_ADD ? '+' : '-',
227            (unsigned long)z,
228            i->argy);
229 #endif
230     switch (i->op) {
231       case MPRI_ADD: MPX_UADDN(v - i->argx, v + 1, z); break;
232       case MPRI_ADDLSL: mpx_uaddnlsl(v - i->argx, v + 1, z, i->argy); break;
233       case MPRI_SUB: MPX_USUBN(v - i->argx, v + 1, z); break;
234       case MPRI_SUBLSL: mpx_usubnlsl(v - i->argx, v + 1, z, i->argy); break;
235       default:
236         abort();
237     }
238 #ifdef DEBUG
239     mp_build(&vv, v - i->argx, v + 1);
240     mp_writefile(&vv, stdout, 16);
241     printf("\n");
242 #endif
243   }
244 }
245
246 mp *mpreduce_do(mpreduce *r, mp *d, mp *x)
247 {
248   mpw *v, *vl;
249   const mpreduce_instr *il;
250   mpw z;
251
252 #ifdef DEBUG
253   mp *_r = 0, *_rr = 0;
254 #endif
255
256   /* --- If source is negative, divide --- */
257
258   if (MP_NEGP(x)) {
259     mp_div(0, &d, x, r->p);
260     return (d);
261   }
262
263   /* --- Try to reuse the source's space --- */
264
265   MP_COPY(x);
266   if (d) MP_DROP(d);
267   MP_DEST(x, MP_LEN(x), x->f);
268
269   /* --- Do the reduction --- */
270
271 #ifdef DEBUG
272   _r = MP_NEW;
273   mp_div(0, &_r, x, r->p);
274   MP_PRINTX("x", x);
275   _rr = 0;
276 #endif
277
278   il = r->iv + r->in;
279   if (MP_LEN(x) >= r->lim) {
280     v = x->v + r->lim;
281     vl = x->vl;
282     while (vl-- > v) {
283       while (*vl) {
284         z = *vl;
285         *vl = 0;
286         run(r->iv, il, vl, z);
287 #ifdef DEBUG
288         MP_PRINTX("x", x);
289         mp_div(0, &_rr, x, r->p);
290         assert(MP_EQ(_r, _rr));
291 #endif
292       }
293     }
294     if (r->s) {
295       while (*vl >> r->s) {
296         z = *vl >> r->s;
297         *vl &= ((1 << r->s) - 1);
298         run(r->iv + r->in, il + r->in, vl, z);
299 #ifdef DEBUG
300         MP_PRINTX("x", x);
301         mp_div(0, &_rr, x, r->p);
302         assert(MP_EQ(_r, _rr));
303 #endif
304       }
305     }
306   }
307
308   /* --- Finishing touches --- */
309
310   MP_SHRINK(x);
311   if (MP_CMP(x, >=, r->p))
312     x = mp_sub(x, x, r->p);
313
314   /* --- Done --- */
315
316 #ifdef DEBUG
317   assert(MP_EQ(_r, x));
318   mp_drop(_r);
319   mp_drop(_rr);
320 #endif
321   return (x);
322 }
323
324 /* --- @mpreduce_exp@ --- *
325  *
326  * Arguments:   @mpreduce *mr@ = pointer to reduction context
327  *              @mp *d@ = fake destination
328  *              @mp *a@ = base
329  *              @mp *e@ = exponent
330  *
331  * Returns:     Result, %$a^e \bmod m$%.
332  */
333
334 mp *mpreduce_exp(mpreduce *mr, mp *d, mp *a, mp *e)
335 {
336   mp *x = MP_ONE;
337   mp *spare = (e->f & MP_BURN) ? MP_NEWSEC : MP_NEW;
338
339   MP_SHRINK(e);
340   MP_COPY(a);
341   if (MP_ZEROP(e))
342     ;
343   else {
344     if (MP_NEGP(e))
345       a = mp_modinv(a, a, mr->p);
346     if (MP_LEN(e) < EXP_THRESH)
347       EXP_SIMPLE(x, a, e);
348     else
349       EXP_WINDOW(x, a, e);
350   }
351   mp_drop(a);
352   mp_drop(d);
353   mp_drop(spare);
354   return (x);
355 }
356
357 /*----- Test rig ----------------------------------------------------------*/
358
359
360 #ifdef TEST_RIG
361
362 #define MP(x) mp_readstring(MP_NEW, #x, 0, 0)
363
364 static int vreduce(dstr *v)
365 {
366   mp *d = *(mp **)v[0].buf;
367   mp *n = *(mp **)v[1].buf;
368   mp *r = *(mp **)v[2].buf;
369   mp *c;
370   int ok = 1;
371   mpreduce rr;
372
373   mpreduce_create(&rr, d);
374   c = mpreduce_do(&rr, MP_NEW, n);
375   if (!MP_EQ(c, r)) {
376     fprintf(stderr, "\n*** reduction failed\n*** ");
377     mpreduce_dump(&rr, stderr);
378     fprintf(stderr, "\n*** n = "); mp_writefile(n, stderr, 10);
379     fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
380     fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
381     fprintf(stderr, "\n");
382     ok = 0;
383   }
384   mpreduce_destroy(&rr);
385   mp_drop(n); mp_drop(d); mp_drop(r); mp_drop(c);
386   assert(mparena_count(MPARENA_GLOBAL) == 0);
387   return (ok);
388 }
389
390 static int vmodexp(dstr *v)
391 {
392   mp *p = *(mp **)v[0].buf;
393   mp *g = *(mp **)v[1].buf;
394   mp *x = *(mp **)v[2].buf;
395   mp *r = *(mp **)v[3].buf;
396   mp *c;
397   int ok = 1;
398   mpreduce rr;
399
400   mpreduce_create(&rr, p);
401   c = mpreduce_exp(&rr, MP_NEW, g, x);
402   if (!MP_EQ(c, r)) {
403     fprintf(stderr, "\n*** modexp failed\n*** ");
404     fprintf(stderr, "\n*** p = "); mp_writefile(p, stderr, 10);
405     fprintf(stderr, "\n*** g = "); mp_writefile(g, stderr, 10);
406     fprintf(stderr, "\n*** x = "); mp_writefile(x, stderr, 10);
407     fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
408     fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
409     fprintf(stderr, "\n");
410     ok = 0;
411   }
412   mpreduce_destroy(&rr);
413   mp_drop(p); mp_drop(g); mp_drop(r); mp_drop(x); mp_drop(c);
414   assert(mparena_count(MPARENA_GLOBAL) == 0);
415   return (ok);
416 }
417
418 static test_chunk defs[] = {
419   { "reduce", vreduce, { &type_mp, &type_mp, &type_mp, 0 } },
420   { "modexp", vmodexp, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
421   { 0, 0, { 0 } }
422 };
423
424 int main(int argc, char *argv[])
425 {
426   test_run(argc, argv, defs, SRCDIR"/tests/mpreduce");
427   return (0);
428 }
429
430 #endif
431
432 /*----- That's all, folks -------------------------------------------------*/