chiark / gitweb /
02ce2cfe4931e3899bc59826fd8b1d7edf2b8c5f
[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 - 1);
105   st = Z;
106 #endif
107
108   for (i = 0, mp_scan(&sc, p); i < d && mp_step(&sc); i++) {
109     switch (st | mp_bit(&sc)) {
110       case  Z | 1: st = Z1; break;
111       case Z1 | 0: st =  Z; op = MPRI_SUB; goto instr;
112       case Z1 | 1: st =  X; op = MPRI_ADD; goto instr;
113       case  X | 0: st = X0; break;
114       case X0 | 1: st =  X; op = MPRI_ADD; goto instr;
115       case X0 | 0: st =  Z; op = MPRI_SUB; goto instr;
116       instr:
117         w = (d - i)/MPW_BITS + 1;
118         b = (MPW_BITS + i - d - 1)%MPW_BITS;
119         INSTR(op | !!b, w, b);
120     }
121   }
122   if ((DA(&iv)[DA_LEN(&iv) - 1].op & ~1u) == MPRI_SUB) {
123     mp_drop(r->p);
124     DA_DESTROY(&iv);
125     return (-1);
126   }
127
128 #undef INSTR
129
130   /* --- Wrap up --- */
131
132   r->in = DA_LEN(&iv);
133   if (!r->s) {
134     r->iv = xmalloc(r->in * sizeof(mpreduce_instr));
135     memcpy(r->iv, DA(&iv), r->in * sizeof(mpreduce_instr));
136   } else {
137     r->iv = xmalloc(r->in * 2 * sizeof(mpreduce_instr));
138     for (i = 0; i < r->in; i++) {
139       r->iv[i] = DA(&iv)[i];
140       op = r->iv[i].op & ~1u;
141       w = r->iv[i].argx;
142       b = r->iv[i].argy;
143       b += r->s;
144       if (b >= MPW_BITS) {
145         b -= MPW_BITS;
146         w--;
147       }
148       if (b) op |= 1;
149       r->iv[i + r->in].op = op;
150       r->iv[i + r->in].argx = w;
151       r->iv[i + r->in].argy = b;
152     }
153   }
154   DA_DESTROY(&iv);
155   return (0);
156 }
157
158 /* --- @mpreduce_destroy@ --- *
159  *
160  * Arguments:   @mpreduce *r@ = structure to free
161  *
162  * Returns:     ---
163  *
164  * Use:         Reclaims the resources from a reduction context.
165  */
166
167 void mpreduce_destroy(mpreduce *r)
168 {
169   mp_drop(r->p);
170   xfree(r->iv);
171 }
172
173 /* --- @mpreduce_dump@ --- *
174  *
175  * Arguments:   @mpreduce *r@ = structure to dump
176  *              @FILE *fp@ = file to dump on
177  *
178  * Returns:     ---
179  *
180  * Use:         Dumps a reduction context.
181  */
182
183 void mpreduce_dump(mpreduce *r, FILE *fp)
184 {
185   size_t i;
186   static const char *opname[] = { "add", "addshift", "sub", "subshift" };
187
188   fprintf(fp, "mod = "); mp_writefile(r->p, fp, 16);
189   fprintf(fp, "\n  lim = %lu; s = %d\n", (unsigned long)r->lim, r->s);
190   for (i = 0; i < r->in; i++) {
191     assert(r->iv[i].op < N(opname));
192     fprintf(fp, "  %s %lu %lu\n",
193             opname[r->iv[i].op],
194             (unsigned long)r->iv[i].argx,
195             (unsigned long)r->iv[i].argy);
196   }
197   if (r->s) {
198     fprintf(fp, "tail end charlie\n");
199     for (i = r->in; i < 2 * r->in; i++) {
200       assert(r->iv[i].op < N(opname));
201       fprintf(fp, "  %s %lu %lu\n",
202               opname[r->iv[i].op],
203               (unsigned long)r->iv[i].argx,
204               (unsigned long)r->iv[i].argy);
205     }
206   }
207 }
208
209 /* --- @mpreduce_do@ --- *
210  *
211  * Arguments:   @mpreduce *r@ = reduction context
212  *              @mp *d@ = destination
213  *              @mp *x@ = source
214  *
215  * Returns:     Destination, @x@ reduced modulo the reduction poly.
216  */
217
218 static void run(const mpreduce_instr *i, const mpreduce_instr *il,
219                 mpw *v, mpw z)
220 {
221   for (; i < il; i++) {
222 #ifdef DEBUG
223     mp vv;
224     mp_build(&vv, v - i->argx, v + 1);
225     printf("  0x"); mp_writefile(&vv, stdout, 16);
226     printf(" %c (0x%lx << %u) == 0x",
227            (i->op & ~1u) == MPRI_ADD ? '+' : '-',
228            (unsigned long)z,
229            i->argy);
230 #endif
231     switch (i->op) {
232       case MPRI_ADD: MPX_UADDN(v - i->argx, v + 1, z); break;
233       case MPRI_ADDLSL: mpx_uaddnlsl(v - i->argx, v + 1, z, i->argy); break;
234       case MPRI_SUB: MPX_USUBN(v - i->argx, v + 1, z); break;
235       case MPRI_SUBLSL: mpx_usubnlsl(v - i->argx, v + 1, z, i->argy); break;
236       default:
237         abort();
238     }
239 #ifdef DEBUG
240     mp_build(&vv, v - i->argx, v + 1);
241     mp_writefile(&vv, stdout, 16);
242     printf("\n");
243 #endif
244   }
245 }
246
247 mp *mpreduce_do(mpreduce *r, mp *d, mp *x)
248 {
249   mpw *v, *vl;
250   const mpreduce_instr *il;
251   mpw z;
252
253 #ifdef DEBUG
254   mp *_r = 0, *_rr = 0;
255 #endif
256
257   /* --- If source is negative, divide --- */
258
259   if (MP_NEGP(x)) {
260     mp_div(0, &d, x, r->p);
261     return (d);
262   }
263
264   /* --- Try to reuse the source's space --- */
265
266   MP_COPY(x);
267   if (d) MP_DROP(d);
268   MP_DEST(x, MP_LEN(x), x->f);
269
270   /* --- Do the reduction --- */
271
272 #ifdef DEBUG
273   _r = MP_NEW;
274   mp_div(0, &_r, x, r->p);
275   MP_PRINTX("x", x);
276   _rr = 0;
277 #endif
278
279   il = r->iv + r->in;
280   if (MP_LEN(x) >= r->lim) {
281     v = x->v + r->lim;
282     vl = x->vl;
283     while (vl-- > v) {
284       while (*vl) {
285         z = *vl;
286         *vl = 0;
287         run(r->iv, il, vl, z);
288 #ifdef DEBUG
289         MP_PRINTX("x", x);
290         mp_div(0, &_rr, x, r->p);
291         assert(MP_EQ(_r, _rr));
292 #endif
293       }
294     }
295     if (r->s) {
296       while (*vl >> r->s) {
297         z = *vl >> r->s;
298         *vl &= ((1 << r->s) - 1);
299         run(r->iv + r->in, il + r->in, vl, z);
300 #ifdef DEBUG
301         MP_PRINTX("x", x);
302         mp_div(0, &_rr, x, r->p);
303         assert(MP_EQ(_r, _rr));
304 #endif
305       }
306     }
307   }
308
309   /* --- Finishing touches --- */
310
311   MP_SHRINK(x);
312   if (MP_CMP(x, >=, r->p))
313     x = mp_sub(x, x, r->p);
314
315   /* --- Done --- */
316
317 #ifdef DEBUG
318   assert(MP_EQ(_r, x));
319   mp_drop(_r);
320   mp_drop(_rr);
321 #endif
322   return (x);
323 }
324
325 /* --- @mpreduce_exp@ --- *
326  *
327  * Arguments:   @mpreduce *mr@ = pointer to reduction context
328  *              @mp *d@ = fake destination
329  *              @mp *a@ = base
330  *              @mp *e@ = exponent
331  *
332  * Returns:     Result, %$a^e \bmod m$%.
333  */
334
335 mp *mpreduce_exp(mpreduce *mr, mp *d, mp *a, mp *e)
336 {
337   mp *x = MP_ONE;
338   mp *spare = (e->f & MP_BURN) ? MP_NEWSEC : MP_NEW;
339
340   MP_SHRINK(e);
341   MP_COPY(a);
342   if (MP_ZEROP(e))
343     ;
344   else {
345     if (MP_NEGP(e))
346       a = mp_modinv(a, a, mr->p);
347     if (MP_LEN(e) < EXP_THRESH)
348       EXP_SIMPLE(x, a, e);
349     else
350       EXP_WINDOW(x, a, e);
351   }
352   mp_drop(a);
353   mp_drop(d);
354   mp_drop(spare);
355   return (x);
356 }
357
358 /*----- Test rig ----------------------------------------------------------*/
359
360
361 #ifdef TEST_RIG
362
363 #define MP(x) mp_readstring(MP_NEW, #x, 0, 0)
364
365 static int vreduce(dstr *v)
366 {
367   mp *d = *(mp **)v[0].buf;
368   mp *n = *(mp **)v[1].buf;
369   mp *r = *(mp **)v[2].buf;
370   mp *c;
371   int ok = 1;
372   mpreduce rr;
373
374   mpreduce_create(&rr, d);
375   c = mpreduce_do(&rr, MP_NEW, n);
376   if (!MP_EQ(c, r)) {
377     fprintf(stderr, "\n*** reduction failed\n*** ");
378     mpreduce_dump(&rr, stderr);
379     fprintf(stderr, "\n*** n = "); mp_writefile(n, stderr, 10);
380     fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
381     fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
382     fprintf(stderr, "\n");
383     ok = 0;
384   }
385   mpreduce_destroy(&rr);
386   mp_drop(n); mp_drop(d); mp_drop(r); mp_drop(c);
387   assert(mparena_count(MPARENA_GLOBAL) == 0);
388   return (ok);
389 }
390
391 static int vmodexp(dstr *v)
392 {
393   mp *p = *(mp **)v[0].buf;
394   mp *g = *(mp **)v[1].buf;
395   mp *x = *(mp **)v[2].buf;
396   mp *r = *(mp **)v[3].buf;
397   mp *c;
398   int ok = 1;
399   mpreduce rr;
400
401   mpreduce_create(&rr, p);
402   c = mpreduce_exp(&rr, MP_NEW, g, x);
403   if (!MP_EQ(c, r)) {
404     fprintf(stderr, "\n*** modexp failed\n*** ");
405     fprintf(stderr, "\n*** p = "); mp_writefile(p, stderr, 10);
406     fprintf(stderr, "\n*** g = "); mp_writefile(g, stderr, 10);
407     fprintf(stderr, "\n*** x = "); mp_writefile(x, stderr, 10);
408     fprintf(stderr, "\n*** c = "); mp_writefile(c, stderr, 10);
409     fprintf(stderr, "\n*** r = "); mp_writefile(r, stderr, 10);
410     fprintf(stderr, "\n");
411     ok = 0;
412   }
413   mpreduce_destroy(&rr);
414   mp_drop(p); mp_drop(g); mp_drop(r); mp_drop(x); mp_drop(c);
415   assert(mparena_count(MPARENA_GLOBAL) == 0);
416   return (ok);
417 }
418
419 static test_chunk defs[] = {
420   { "reduce", vreduce, { &type_mp, &type_mp, &type_mp, 0 } },
421   { "modexp", vmodexp, { &type_mp, &type_mp, &type_mp, &type_mp, 0 } },
422   { 0, 0, { 0 } }
423 };
424
425 int main(int argc, char *argv[])
426 {
427   test_run(argc, argv, defs, SRCDIR"/tests/mpreduce");
428   return (0);
429 }
430
431 #endif
432
433 /*----- That's all, folks -------------------------------------------------*/