field.c, mp.c: Implement the `nb_index' conversion.
[catacomb-python] / mp.c
1 /* -*-c-*-
2 *
3 * Multiprecision arithmetic
4 *
5 * (c) 2004 Straylight/Edgeware
6 */
7
8 /*----- Licensing notice --------------------------------------------------*
9 *
10 * This file is part of the Python interface to Catacomb.
11 *
12 * Catacomb/Python is free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * Catacomb/Python is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with Catacomb/Python; if not, write to the Free Software Foundation,
24 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25 */
26
27 /*----- Header files ------------------------------------------------------*/
28
29 #include "catacomb-python.h"
30
31 /*----- General utilities -------------------------------------------------*/
32
33 PyTypeObject *mp_pytype = 0;
34 PyTypeObject *gf_pytype = 0;
35
36 #ifndef PyLong_SHIFT
37 # define PyLong_SHIFT SHIFT
38 #endif
39
40 #ifndef PyLong_MASK
41 # define PyLong_MASK MASK
42 #endif
43
44 STATIC_ASSERT(MPW_BITS >= PyLong_SHIFT,
45 "Catacomb's limbs are now narrower than than Python's!");
46
47 mp *mp_frompylong(PyObject *obj)
48 {
49 unsigned long bits;
50 PyLongObject *l = (PyLongObject *)obj;
51 int sz;
52 size_t w;
53 mpd r = 0;
54 int b = 0;
55 int i;
56 mp *x;
57 mpw *p;
58
59 sz = Py_SIZE(l);
60 if (sz < 0) sz = -sz;
61 bits = (unsigned long)sz * PyLong_SHIFT;
62 w = (bits + MPW_BITS - 1)/MPW_BITS;
63 x = mp_new(w, Py_SIZE(l) < 0 ? MP_NEG : 0);
64 p = x->v;
65 for (i = 0; i < sz; i++) {
66 r |= (mpd)l->ob_digit[i] << b;
67 b += PyLong_SHIFT;
68 while (b >= MPW_BITS) {
69 *p++ = MPW(r);
70 r >>= MPW_BITS;
71 b -= MPW_BITS;
72 }
73 }
74 while (r) {
75 *p++ = MPW(r);
76 r >>= MPW_BITS;
77 }
78 x->vl = p;
79 MP_SHRINK(x);
80 return (x);
81 }
82
83 PyObject *mp_topylong(mp *x)
84 {
85 unsigned long bits = mp_bits(x);
86 int sz = (bits + PyLong_SHIFT - 1)/PyLong_SHIFT;
87 PyLongObject *l = _PyLong_New(sz);
88 mpd r = 0;
89 int b = 0;
90 mpw *p = x->v;
91 int i = 0;
92
93 while (i < sz && p < x->vl) {
94 r |= (mpd)*p++ << b;
95 b += MPW_BITS;
96 while (i < sz && b >= PyLong_SHIFT) {
97 l->ob_digit[i++] = r & PyLong_MASK;
98 r >>= PyLong_SHIFT;
99 b -= PyLong_SHIFT;
100 }
101 }
102 while (i < sz && r) {
103 l->ob_digit[i++] = r & PyLong_MASK;
104 r >>= PyLong_SHIFT;
105 }
106 Py_SIZE(l) = (x->f & MP_NEG) ? -sz : sz;
107 return ((PyObject *)l);
108 }
109
110 mp *mp_frompyobject(PyObject *o, int radix)
111 {
112 mp *x;
113
114 if (TEXT_CHECK(o)) {
115 mptext_stringctx sc;
116 mp *x;
117 size_t sz;
118 TEXT_PTRLEN(o, sc.buf, sz); sc.lim = sc.buf + sz;
119 x = mp_read(MP_NEW, radix, &mptext_stringops, &sc);
120 if (!x) return (0);
121 if (sc.buf < sc.lim) { MP_DROP(x); return (0); }
122 return (x);
123 }
124 if ((x = tomp(o)) != 0)
125 return (x);
126 return (0);
127 }
128
129 PyObject *mp_topystring(mp *x, int radix, const char *xpre,
130 const char *pre, const char *post)
131 {
132 int len = mptext_len(x, radix) + 1;
133 mptext_stringctx sc;
134 PyObject *o;
135 size_t xprelen = xpre ? strlen(xpre) : 0;
136 size_t prelen = pre ? strlen(pre) : 0;
137 size_t postlen = post ? strlen(post) : 0;
138 char *p;
139 MP_COPY(x);
140 TEXT_PREPAREWRITE(o, p, len + 1 + xprelen + prelen + postlen);
141 sc.buf = p;
142 if (xpre) { memcpy(sc.buf, xpre, xprelen); sc.buf += xprelen; }
143 if (MP_NEGP(x)) { *sc.buf++ = '-'; x = mp_neg(x, x); }
144 if (pre) { memcpy(sc.buf, pre, prelen); sc.buf += prelen; }
145 sc.lim = sc.buf + len;
146 mp_write(x, radix, &mptext_stringops, &sc);
147 if (post) { memcpy(sc.buf, post, postlen); sc.buf += postlen; }
148 MP_DROP(x);
149 TEXT_DONEWRITE(o, sc.buf - p);
150 return (o);
151 }
152
153 static int good_radix_p(int r, int readp)
154 {
155 return ((r >= -255 && r <= -2) ||
156 (readp && r == 0) ||
157 (r >= 2 && r <= 62));
158 }
159
160 PyObject *mp_pywrap(mp *x)
161 {
162 mp_pyobj *z = PyObject_New(mp_pyobj, mp_pytype);
163 z->x = x;
164 return ((PyObject *)z);
165 }
166
167 PyObject *gf_pywrap(mp *x)
168 {
169 mp_pyobj *z = PyObject_New(mp_pyobj, gf_pytype);
170 z->x = x;
171 return ((PyObject *)z);
172 }
173
174 int mp_tolong_checked(mp *x, long *l, int must)
175 {
176 static mp *longmin = 0, *longmax = 0;
177 int rc = -1;
178
179 if (!longmax) {
180 longmin = mp_fromlong(MP_NEW, LONG_MIN);
181 longmax = mp_fromlong(MP_NEW, LONG_MAX);
182 }
183 if (MP_CMP(x, <, longmin) || MP_CMP(x, >, longmax)) {
184 if (must) VALERR("mp out of range for int");
185 else goto end;
186 }
187 *l = mp_tolong(x);
188 rc = 0;
189 end:
190 return (rc);
191 }
192
193 /*----- Python interface --------------------------------------------------*/
194
195 static void mp_pydealloc(PyObject *o)
196 {
197 MP_DROP(MP_X(o));
198 FREEOBJ(o);
199 }
200
201 static PyObject *mp_pyrepr(PyObject *o)
202 { return mp_topystring(MP_X(o), 10, "MP(", 0, ")"); }
203
204 static PyObject *mp_pystr(PyObject *o)
205 { return mp_topystring(MP_X(o), 10, 0, 0, 0); }
206
207 mp *tomp(PyObject *o)
208 {
209 PyObject *l;
210 mp *x;
211
212 if (!o || PyFloat_Check(o))
213 return (0);
214 else if (MP_PYCHECK(o) || GF_PYCHECK(o))
215 return (MP_COPY(MP_X(o)));
216 else if (FE_PYCHECK(o))
217 return (F_OUT(FE_F(o), MP_NEW, FE_X(o)));
218 else if (PFILT_PYCHECK(o))
219 return (MP_COPY(PFILT_F(o)->m));
220 else if (ECPT_PYCHECK(o)) {
221 ec p = EC_INIT;
222 if (EC_ATINF(ECPT_P(o))) return (0);
223 getecptout(&p, o);
224 x = MP_COPY(p.x);
225 EC_DESTROY(&p);
226 return (x);
227 } else if (GE_PYCHECK(o)) {
228 if ((x = G_TOINT(GE_G(o), MP_NEW, GE_X(o))) == 0)
229 return (0);
230 return (x);
231 } else if (PyInt_Check(o))
232 return (mp_fromlong(MP_NEW, PyInt_AS_LONG(o)));
233 else if ((l = PyNumber_Long(o)) != 0) {
234 x = mp_frompylong(l);
235 Py_DECREF(l);
236 return (x);
237 } else {
238 PyErr_Clear();
239 return (0);
240 }
241 }
242
243 mp *getmp(PyObject *o)
244 {
245 mp *x = 0;
246 if (!o) return (0);
247 if ((x = tomp(o)) == 0) {
248 PyErr_Format(PyExc_TypeError, "can't convert %.100s to mp",
249 Py_TYPE(o)->tp_name);
250 }
251 return (x);
252 }
253
254 int convmp(PyObject *o, void *p)
255 {
256 mp *x;
257 if ((x = getmp(o)) == 0) return (0);
258 *(mp **)p = x;
259 return (1);
260 }
261
262 mp *getgf(PyObject *o)
263 {
264 mp *x = 0;
265 if (!o) return (0);
266 if ((x = tomp(o)) == 0) {
267 PyErr_Format(PyExc_TypeError, "can't convert %.100s to gf",
268 Py_TYPE(o)->tp_name);
269 }
270 return (x);
271 }
272
273 int convgf(PyObject *o, void *p)
274 {
275 mp *x;
276 if ((x = getgf(o)) == 0) return (0);
277 *(mp **)p = x;
278 return (1);
279 }
280
281 static mp *implicitmp(PyObject *o)
282 {
283 if (!o ||
284 GF_PYCHECK(o) ||
285 ECPT_PYCHECK(o) ||
286 FE_PYCHECK(o) ||
287 GE_PYCHECK(o))
288 return (0);
289 return (tomp(o));
290 }
291
292 static mp *implicitgf(PyObject *o)
293 {
294 if (!o ||
295 MP_PYCHECK(o) ||
296 ECPT_PYCHECK(o) ||
297 FE_PYCHECK(o) ||
298 GE_PYCHECK(o))
299 return (0);
300 return (tomp(o));
301 }
302
303 static int mpbinop(PyObject *x, PyObject *y, mp **xx, mp **yy)
304 {
305 if ((*xx = implicitmp(x)) == 0)
306 return (-1);
307 if ((*yy = implicitmp(y)) == 0) {
308 MP_DROP(*xx);
309 return (-1);
310 }
311 return (0);
312 }
313
314 static int gfbinop(PyObject *x, PyObject *y, mp **xx, mp **yy)
315 {
316 if ((*xx = implicitgf(x)) == 0)
317 return (-1);
318 if ((*yy = implicitgf(y)) == 0) {
319 MP_DROP(*xx);
320 return (-1);
321 }
322 return (0);
323 }
324
325 #define FPBINOP(name, pyop) \
326 static PyObject *mp_py##name(PyObject *x, PyObject *y) { \
327 mp *xx, *yy, *zz; \
328 PyObject *l, *rc; \
329 if (PyFloat_Check(x)) { \
330 l = mp_topylong(MP_X(y)); rc = PyNumber_##pyop(x, l); \
331 Py_DECREF(l); return (rc); \
332 } else if (PyFloat_Check(y)) { \
333 l = mp_topylong(MP_X(x)); rc = PyNumber_##pyop(l, y); \
334 Py_DECREF(l); return (rc); \
335 } \
336 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
337 zz = mp_##name(MP_NEW, xx, yy); \
338 MP_DROP(xx); MP_DROP(yy); \
339 return (mp_pywrap(zz)); \
340 }
341 FPBINOP(add, Add)
342 FPBINOP(sub, Subtract)
343 FPBINOP(mul, Multiply)
344
345 #define gf_and mp_and
346 #define gf_or mp_or
347 #define gf_xor mp_xor
348 #define BINOP(pre, name) \
349 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
350 mp *xx, *yy, *zz; \
351 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
352 zz = pre##_##name(MP_NEW, xx, yy); \
353 MP_DROP(xx); MP_DROP(yy); \
354 return (pre##_pywrap(zz)); \
355 }
356 BINOP(mp, and2c)
357 BINOP(mp, or2c)
358 BINOP(mp, xor2c)
359 BINOP(gf, add)
360 BINOP(gf, sub)
361 BINOP(gf, mul)
362 BINOP(gf, and)
363 BINOP(gf, or)
364 BINOP(gf, xor)
365 #undef BINOP
366
367 static mp *mp_abs(mp *d, mp *x)
368 {
369 if (MP_NEGP(x))
370 return (mp_neg(d, x));
371 MP_COPY(x);
372 if (d) MP_DROP(d);
373 return (x);
374 }
375
376 #define UNOP(pre, name) \
377 static PyObject *pre##_py##name(PyObject *x) \
378 { return mp_pywrap(pre##_##name(MP_NEW, MP_X(x))); }
379 UNOP(mp, neg)
380 UNOP(mp, abs)
381 UNOP(mp, not2c)
382 #undef UNOP
383
384 static PyObject *mp_pyid(PyObject *x) { RETURN_OBJ(x); }
385
386 #define gf_lsr mp_lsr
387 #define SHIFTOP(pre, name, rname) \
388 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
389 mp *xx, *yy; \
390 PyObject *z = 0; \
391 long n; \
392 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
393 if (mp_tolong_checked(yy, &n, 1)) goto end; \
394 if (n < 0) \
395 z = pre##_pywrap(mp_##rname(MP_NEW, xx, -n)); \
396 else \
397 z = pre##_pywrap(mp_##name(MP_NEW, xx, n)); \
398 end: \
399 MP_DROP(xx); MP_DROP(yy); \
400 return (z); \
401 }
402 SHIFTOP(mp, lsl2c, lsr2c)
403 SHIFTOP(mp, lsr2c, lsl2c)
404 SHIFTOP(gf, lsl, lsr)
405 SHIFTOP(gf, lsr, lsl)
406 #undef SHIFTOP
407
408 #define DIVOP(pre, name, qq, rr, gather) \
409 static PyObject *pre##_py##name(PyObject *x, PyObject *y) { \
410 mp *xx, *yy; \
411 PyObject *z = 0; \
412 INIT_##qq(q) INIT_##rr(r) \
413 if (pre##binop(x, y, &xx, &yy)) RETURN_NOTIMPL; \
414 if (MP_ZEROP(yy)) \
415 ZDIVERR("division by zero"); \
416 pre##_div(ARG_##qq(q), ARG_##rr(r), xx, yy); \
417 z = gather; \
418 end: \
419 MP_DROP(xx); MP_DROP(yy); \
420 return (z); \
421 }
422 #define INIT_YES(p) mp *p = MP_NEW;
423 #define INIT_NO(p)
424 #define ARG_YES(p) &p
425 #define ARG_NO(p) 0
426 DIVOP(mp, divmod, YES, YES,
427 Py_BuildValue("(NN)", mp_pywrap(q), mp_pywrap(r)))
428 DIVOP(mp, div, YES, NO, mp_pywrap(q))
429 DIVOP(mp, mod, NO, YES, mp_pywrap(r))
430 DIVOP(gf, divmod, YES, YES,
431 Py_BuildValue("(NN)", gf_pywrap(q), gf_pywrap(r)))
432 DIVOP(gf, div, YES, NO, gf_pywrap(q))
433 DIVOP(gf, mod, NO, YES, gf_pywrap(r))
434 #undef INIT_YES
435 #undef INIT_NO
436 #undef ARG_YES
437 #undef ARG_NO
438 #undef DIVOP
439
440 static mp *mp_modinv_checked(mp *d, mp *x, mp *p)
441 {
442 mp *g = MP_NEW;
443 mp_gcd(&g, 0, &d, p, x);
444 if (!MP_EQ(g, MP_ONE)) {
445 MP_DROP(g); MP_DROP(d);
446 PyErr_SetString(PyExc_ZeroDivisionError, "no modular inverse");
447 return (0);
448 }
449 MP_DROP(g); return (d);
450 }
451
452 static PyObject *mp_pyexp(PyObject *x, PyObject *y, PyObject *z)
453 {
454 mp *xx = 0, *yy = 0, *zz = 0;
455 mp *r = 0;
456 PyObject *rc = 0;
457
458 if ((xx = implicitmp(x)) == 0 || (yy = implicitmp(y)) == 0 ||
459 (z && z != Py_None && (zz = tomp(z)) == 0)) {
460 mp_drop(xx); mp_drop(yy); mp_drop(zz);
461 RETURN_NOTIMPL;
462 }
463 if (!z || z == Py_None) {
464 if (MP_NEGP(yy)) VALERR("negative exponent");
465 r = mp_exp(MP_NEW, xx, yy);
466 } else {
467 if (!MP_POSP(zz)) VALERR("modulus must be positive");
468 if (MP_NEGP(yy)) {
469 if ((xx = mp_modinv_checked(xx, xx, zz)) == 0) goto end;
470 yy = mp_neg(yy, yy);
471 }
472 if (MP_ODDP(zz)) {
473 mpmont mm;
474 mpmont_create(&mm, zz);
475 r = mpmont_exp(&mm, MP_NEW, xx, yy);
476 mpmont_destroy(&mm);
477 } else {
478 mpbarrett mb;
479 mpbarrett_create(&mb, zz);
480 r = mpbarrett_exp(&mb, MP_NEW, xx, yy);
481 mpbarrett_destroy(&mb);
482 }
483 }
484 rc = mp_pywrap(r);
485 end:
486 mp_drop(xx); mp_drop(yy); mp_drop(zz);
487 return (rc);
488 }
489
490 static mp *gf_modinv_checked(mp *d, mp *x, mp *p)
491 {
492 mp *g = MP_NEW;
493 gf_gcd(&g, 0, &d, p, x);
494 if (!MP_EQ(g, MP_ONE)) {
495 MP_DROP(g); MP_DROP(d);
496 PyErr_SetString(PyExc_ZeroDivisionError, "no modular inverse");
497 return (0);
498 }
499 MP_DROP(g); return (d);
500 }
501
502 #define BASEOP(name, radix, pre) \
503 static PyObject *mp_py##name(PyObject *x) \
504 { return mp_topystring(MP_X(x), radix, 0, pre, 0); }
505 BASEOP(oct, 8, "0");
506 BASEOP(hex, 16, "0x");
507 #undef BASEOP
508
509 static int mp_pynonzerop(PyObject *x) { return !MP_ZEROP(MP_X(x)); }
510
511 static PyObject *mp_pyint(PyObject *x)
512 {
513 long l;
514 if (!mp_tolong_checked(MP_X(x), &l, 0)) return (PyInt_FromLong(l));
515 else return mp_topylong(MP_X(x));
516 }
517 static PyObject *mp_pylong(PyObject *x)
518 { return (mp_topylong(MP_X(x))); }
519 static PyObject *mp_pyfloat(PyObject *x)
520 {
521 PyObject *l = mp_topylong(MP_X(x));
522 double f = PyLong_AsDouble(l);
523 Py_DECREF(l);
524 return (PyFloat_FromDouble(f));
525 }
526
527 #define COERCE(pre, PRE) \
528 static int pre##_pycoerce(PyObject **x, PyObject **y) \
529 { \
530 mp *z; \
531 \
532 if (PRE##_PYCHECK(*y)) { \
533 Py_INCREF(*x); Py_INCREF(*y); \
534 return (0); \
535 } \
536 if ((z = tomp(*y)) != 0) { \
537 Py_INCREF(*x); \
538 *y = pre##_pywrap(z); \
539 return (0); \
540 } \
541 return (1); \
542 }
543 COERCE(mp, MP)
544 COERCE(gf, GF)
545 #undef COERCE
546
547 static PyObject *mp_pyrichcompare(PyObject *x, PyObject *y, int op)
548 {
549 mp *xx, *yy;
550 PyObject *l, *rc;
551 if (PyFloat_Check(y)) {
552 l = mp_topylong(MP_X(x)); rc = PyObject_RichCompare(l, y, op);
553 Py_DECREF(l); return (rc);
554 }
555 if (mpbinop(x, y, &xx, &yy)) RETURN_NOTIMPL;
556 rc = enrich_compare(op, mp_cmp(xx, yy));
557 MP_DROP(xx); MP_DROP(yy);
558 return (rc);
559 }
560
561 static int mp_pycompare(PyObject *x, PyObject *y)
562 { return mp_cmp(MP_X(x), MP_X(y)); }
563
564 static PyObject *mp_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
565 {
566 PyObject *x;
567 mp *z;
568 mp_pyobj *zz = 0;
569 int radix = 0;
570 static const char *const kwlist[] = { "x", "radix", 0 };
571
572 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|i:new", KWLIST, &x, &radix))
573 goto end;
574 if (MP_PYCHECK(x)) RETURN_OBJ(x);
575 if (!good_radix_p(radix, 1)) VALERR("bad radix");
576 if ((z = mp_frompyobject(x, radix)) == 0) {
577 PyErr_Format(PyExc_TypeError, "can't convert %.100s to mp",
578 Py_TYPE(x)->tp_name);
579 goto end;
580 }
581 zz = (mp_pyobj *)ty->tp_alloc(ty, 0);
582 zz->x = z;
583 end:
584 return ((PyObject *)zz);
585 }
586
587 Py_hash_t mphash(mp *x)
588 {
589 PyObject *l = mp_topylong(x);
590 Py_hash_t h = PyObject_Hash(l);
591 Py_DECREF(l); return (h);
592 }
593
594 static Py_hash_t mp_pyhash(PyObject *me) { return (mphash(MP_X(me))); }
595
596 static PyObject *mpmeth_jacobi(PyObject *me, PyObject *arg)
597 {
598 mp *y = 0;
599 PyObject *z = 0;
600
601 if (!PyArg_ParseTuple(arg, "O&:jacobi", convmp, &y)) goto end;
602 z = PyInt_FromLong(mp_jacobi(y, MP_X(me)));
603 end:
604 if (y) MP_DROP(y);
605 return (z);
606 }
607
608 #define BITOP(pre, name, c) \
609 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
610 { \
611 unsigned long i; \
612 if (!PyArg_ParseTuple(arg, "O&:" #name, convulong, &i)) return (0); \
613 return (pre##_pywrap(mp_##name##c(MP_NEW, MP_X(me), i))); \
614 }
615 BITOP(mp, setbit, 2c);
616 BITOP(mp, clearbit, 2c);
617 BITOP(gf, setbit, );
618 BITOP(gf, clearbit, );
619 #undef BITOP
620
621 static PyObject *mpmeth_testbit(PyObject *me, PyObject *arg)
622 {
623 unsigned long i;
624 if (!PyArg_ParseTuple(arg, "O&:testbit", convulong, &i)) return (0);
625 return (getbool(mp_testbit2c(MP_X(me), i)));
626 }
627
628 static PyObject *gfmeth_testbit(PyObject *me, PyObject *arg)
629 {
630 unsigned long i;
631 if (!PyArg_ParseTuple(arg, "O&:testbit", convulong, &i)) return (0);
632 return (getbool(mp_testbit(MP_X(me), i)));
633 }
634
635 static PyObject *mpmeth_odd(PyObject *me)
636 {
637 mp *t;
638 size_t s;
639
640 t = mp_odd(MP_NEW, MP_X(me), &s);
641 return (Py_BuildValue("(lN)", (long)s, mp_pywrap(t)));
642 }
643
644 static PyObject *mpmeth_sqr(PyObject *me)
645 { return (mp_pywrap(mp_sqr(MP_NEW, MP_X(me)))); }
646
647 static PyObject *mpmeth_sqrt(PyObject *me)
648 {
649 if (MP_NEGP(MP_X(me))) VALERR("negative root");
650 return (mp_pywrap(mp_sqrt(MP_NEW, MP_X(me))));
651 end:
652 return (0);
653 }
654
655 static PyObject *mpmeth_gcd(PyObject *me, PyObject *arg)
656 {
657 mp *y = 0, *zz = MP_NEW;
658 PyObject *z = 0;
659
660 if (!PyArg_ParseTuple(arg, "O&:gcd", convmp, &y)) goto end;
661 mp_gcd(&zz, 0, 0, MP_X(me), y);
662 z = mp_pywrap(zz);
663 end:
664 if (y) MP_DROP(y);
665 return (z);
666 }
667
668 static PyObject *mpmeth_gcdx(PyObject *me, PyObject *arg)
669 {
670 PyObject *z = 0;
671 mp *yy = 0, *zz = MP_NEW, *uu = MP_NEW, *vv = MP_NEW;
672
673 if (!PyArg_ParseTuple(arg, "O&:gcdx", convmp, &yy)) goto end;
674 mp_gcd(&zz, &uu, &vv, MP_X(me), yy);
675 z = Py_BuildValue("(NNN)",
676 mp_pywrap(zz), mp_pywrap(uu), mp_pywrap(vv));
677 end:
678 if (yy) MP_DROP(yy);
679 return (z);
680 }
681
682 static PyObject *mpmeth_modinv(PyObject *me, PyObject *arg)
683 {
684 PyObject *z = 0;
685 mp *yy = 0, *zz = MP_NEW;
686
687 if (!PyArg_ParseTuple(arg, "O&:modinv", convmp, &yy) ||
688 (zz = mp_modinv_checked(MP_NEW, yy, MP_X(me))) == 0)
689 goto end;
690 z = mp_pywrap(zz);
691 end:
692 if (yy) MP_DROP(yy);
693 return (z);
694 }
695
696 static PyObject *mpmeth_tostring(PyObject *me, PyObject *arg, PyObject *kw)
697 {
698 int radix = 10;
699 static const char *const kwlist[] = { "radix", 0 };
700 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|i:tostring", KWLIST, &radix))
701 goto end;
702 if (!good_radix_p(radix, 0)) VALERR("bad radix");
703 return (mp_topystring(MP_X(me), radix, 0, 0, 0));
704 end:
705 return (0);
706 }
707
708 static PyObject *mpmeth_modsqrt(PyObject *me, PyObject *arg)
709 {
710 PyObject *z = 0;
711 mp *yy = 0, *zz = MP_NEW;
712
713 if (!PyArg_ParseTuple(arg, "O&:modsqrt", convmp, &yy)) goto end;
714 if ((zz = mp_modsqrt(MP_NEW, yy, MP_X(me))) == 0)
715 VALERR("no modular square root");
716 z = mp_pywrap(zz);
717 end:
718 if (yy) MP_DROP(yy);
719 return (z);
720 }
721
722 static PyObject *mpmeth_leastcongruent(PyObject *me, PyObject *arg)
723 {
724 mp *z, *b, *m;
725 PyObject *rc = 0;
726
727 if (!PyArg_ParseTuple(arg, "O&O&:leastcongruent", convmp, &b, convmp, &m))
728 goto end;
729 z = mp_leastcongruent(MP_NEW, b, MP_X(me), m);
730 rc = mp_pywrap(z);
731 end:
732 return (rc);
733 }
734
735 #define STOREOP(name, c) \
736 static PyObject *mpmeth_##name(PyObject *me, \
737 PyObject *arg, PyObject *kw) \
738 { \
739 long len = -1; \
740 static const char *const kwlist[] = { "len", 0 }; \
741 PyObject *rc = 0; \
742 \
743 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|l:" #name, \
744 KWLIST, &len)) \
745 goto end; \
746 if (len < 0) { \
747 len = mp_octets##c(MP_X(me)); \
748 if (!len) len = 1; \
749 } \
750 rc = bytestring_pywrap(0, len); \
751 mp_##name(MP_X(me), BIN_PTR(rc), len); \
752 end: \
753 return (rc); \
754 }
755 STOREOP(storel, )
756 STOREOP(storeb, )
757 STOREOP(storel2c, 2c)
758 STOREOP(storeb2c, 2c)
759 #undef STOREOP
760
761 #define BUFOP(ty) \
762 static PyObject *ty##meth_frombuf(PyObject *me, PyObject *arg) \
763 { \
764 buf b; \
765 struct bin in; \
766 PyObject *rc = 0; \
767 mp *x; \
768 \
769 if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) goto end; \
770 buf_init(&b, (/*unconst*/ void *)in.p, in.sz); \
771 if ((x = buf_getmp(&b)) == 0) VALERR("malformed data"); \
772 rc = Py_BuildValue("(NN)", ty##_pywrap(x), \
773 bytestring_pywrapbuf(&b)); \
774 end: \
775 return (rc); \
776 }
777 BUFOP(mp)
778 BUFOP(gf)
779 #undef BUFOP
780
781 static PyObject *mpmeth_tobuf(PyObject *me)
782 {
783 buf b;
784 PyObject *rc;
785 mp *x;
786 size_t n;
787
788 x = MP_X(me);
789 n = mp_octets(x) + 3;
790 rc = bytestring_pywrap(0, n);
791 buf_init(&b, BIN_PTR(rc), n);
792 buf_putmp(&b, x);
793 assert(BOK(&b));
794 BIN_SETLEN(rc, BLEN(&b));
795 return (rc);
796 }
797
798 static PyObject *mpmeth_primep(PyObject *me, PyObject *arg, PyObject *kw)
799 {
800 grand *r = &rand_global;
801 static const char *const kwlist[] = { "rng", 0 };
802 PyObject *rc = 0;
803
804 if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&", KWLIST, convgrand, &r))
805 goto end;
806 rc = getbool(pgen_primep(MP_X(me), r));
807 end:
808 return (rc);
809 }
810
811 static PyObject *mpmeth_fromstring(PyObject *me,
812 PyObject *arg, PyObject *kw)
813 {
814 int r = 0;
815 char *p;
816 Py_ssize_t len;
817 PyObject *z = 0;
818 mp *zz;
819 mptext_stringctx sc;
820 static const char *const kwlist[] = { "x", "radix", 0 };
821
822 if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|i:fromstring", KWLIST,
823 &p, &len, &r))
824 goto end;
825 if (!good_radix_p(r, 1)) VALERR("bad radix");
826 sc.buf = p; sc.lim = p + len;
827 if ((zz = mp_read(MP_NEW, r, &mptext_stringops, &sc)) == 0)
828 VALERR("bad integer");
829 z = Py_BuildValue("(Ns#)", mp_pywrap(zz),
830 sc.buf, (Py_ssize_t)(sc.lim - sc.buf));
831 end:
832 return (z);
833 }
834
835 static PyObject *mpmeth_factorial(PyObject *me, PyObject *arg)
836 {
837 unsigned long i;
838 mp *x;
839 if (!PyArg_ParseTuple(arg, "O&:factorial", convulong, &i)) return (0);
840 x = mp_factorial(i);
841 return mp_pywrap(x);
842 }
843
844 static PyObject *mpmeth_fibonacci(PyObject *me, PyObject *arg)
845 {
846 long i;
847 mp *x;
848 if (!PyArg_ParseTuple(arg, "l:fibonacci", &i)) return (0);
849 x = mp_fibonacci(i);
850 return mp_pywrap(x);
851 }
852
853 #define LOADOP(pre, name) \
854 static PyObject *pre##meth_##name(PyObject *me, PyObject *arg) \
855 { \
856 struct bin in; \
857 if (!PyArg_ParseTuple(arg, "O&:" #name, convbin, &in)) return (0); \
858 return (pre##_pywrap(mp_##name(MP_NEW, in.p, in.sz))); \
859 }
860 LOADOP(mp, loadl)
861 LOADOP(mp, loadb)
862 LOADOP(mp, loadl2c)
863 LOADOP(mp, loadb2c)
864 LOADOP(gf, loadl)
865 LOADOP(gf, loadb)
866 #undef LOADOP
867
868 static PyObject *mpget_nbits(PyObject *me, void *hunoz)
869 { return (PyInt_FromLong(mp_bits(MP_X(me)))); }
870
871 static PyObject *mpget_noctets(PyObject *me, void *hunoz)
872 { return (PyInt_FromLong(mp_octets(MP_X(me)))); }
873
874 static PyObject *mpget_noctets2c(PyObject *me, void *hunoz)
875 { return (PyInt_FromLong(mp_octets2c(MP_X(me)))); }
876
877 static const PyGetSetDef mp_pygetset[] = {
878 #define GETSETNAME(op, func) mp##op##_##func
879 GET (nbits, "X.nbits -> bit length of X")
880 GET (noctets, "X.noctets -> octet length of X")
881 GET (noctets2c, "X.noctets2c -> two's complement octet length of X")
882 #undef GETSETNAME
883 { 0 }
884 };
885
886 static const PyMethodDef mp_pymethods[] = {
887 #define METHNAME(func) mpmeth_##func
888 METH (jacobi, "X.jacobi(Y) -> Jacobi symbol (Y|X) (NB inversion!)")
889 METH (setbit, "X.setbit(N) -> X with bit N set")
890 METH (clearbit, "X.clearbit(N) -> X with bit N clear")
891 METH (testbit, "X.testbit(N) -> true/false if bit N set/clear in X")
892 NAMETH(odd, "X.odd() -> S, T where X = 2^S T with T odd")
893 NAMETH(sqr, "X.sqr() -> X^2")
894 NAMETH(sqrt, "X.sqrt() -> largest integer <= sqrt(X)")
895 METH (gcd, "X.gcd(Y) -> gcd(X, Y)")
896 METH (gcdx, "X.gcdx(Y) -> (gcd(X, Y), U, V) "
897 "with X U + Y V = gcd(X, Y)")
898 METH (modinv, "X.modinv(Y) -> multiplicative inverse of Y mod X")
899 METH (modsqrt, "X.modsqrt(Y) -> square root of Y mod X, if X prime")
900 METH (leastcongruent, "X.leastcongruent(B, M) -> "
901 "smallest Z >= B with Z == X (mod M)")
902 KWMETH(primep, "X.primep([rng = rand]) -> X is prime?")
903 KWMETH(tostring, "X.tostring([radix = 10]) -> STR")
904 KWMETH(storel, "X.storel([len = -1]) -> little-endian bytes")
905 KWMETH(storeb, "X.storeb([len = -1]) -> big-endian bytes")
906 KWMETH(storel2c, "X.storel2c([len = -1]) -> "
907 "little-endian bytes, two's complement")
908 KWMETH(storeb2c, "X.storeb2c([len = -1]) -> "
909 "big-endian bytes, two's complement")
910 NAMETH(tobuf, "X.tobuf() -> buffer format")
911 KWSMTH(fromstring, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
912 " Parse STR as a large integer, according to RADIX. If RADIX is\n"
913 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
914 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
915 SMTH (factorial, "factorial(I) -> I!: compute factorial")
916 SMTH (fibonacci, "fibonacci(I) -> F(I): compute Fibonacci number")
917 SMTH (loadl, "loadl(STR) -> X: read little-endian bytes")
918 SMTH (loadb, "loadb(STR) -> X: read big-endian bytes")
919 SMTH (loadl2c, "loadl2c(STR) -> X: "
920 "read little-endian bytes, two's complement")
921 SMTH (loadb2c, "loadb2c(STR) -> X: "
922 "read big-endian bytes, two's complement")
923 SMTH (frombuf, "frombuf(STR) -> (X, REST): read buffer format")
924 #undef METHNAME
925 { 0 }
926 };
927
928 static const PyNumberMethods mp_pynumber = {
929 mp_pyadd, /* @nb_add@ */
930 mp_pysub, /* @nb_subtract@ */
931 mp_pymul, /* @nb_multiply@ */
932 0, /* @nb_divide@ */
933 mp_pymod, /* @nb_remainder@ */
934 mp_pydivmod, /* @nb_divmod@ */
935 mp_pyexp, /* @nb_power@ */
936 mp_pyneg, /* @nb_negative@ */
937 mp_pyid, /* @nb_positive@ */
938 mp_pyabs, /* @nb_absolute@ */
939 mp_pynonzerop, /* @nb_nonzero@ */
940 mp_pynot2c, /* @nb_invert@ */
941 mp_pylsl2c, /* @nb_lshift@ */
942 mp_pylsr2c, /* @nb_rshift@ */
943 mp_pyand2c, /* @nb_and@ */
944 mp_pyxor2c, /* @nb_xor@ */
945 mp_pyor2c, /* @nb_or@ */
946 mp_pycoerce, /* @nb_coerce@ */
947 mp_pyint, /* @nb_int@ */
948 mp_pylong, /* @nb_long@ */
949 mp_pyfloat, /* @nb_float@ */
950 mp_pyoct, /* @nb_oct@ */
951 mp_pyhex, /* @nb_hex@ */
952
953 0, /* @nb_inplace_add@ */
954 0, /* @nb_inplace_subtract@ */
955 0, /* @nb_inplace_multiply@ */
956 0, /* @nb_inplace_divide@ */
957 0, /* @nb_inplace_remainder@ */
958 0, /* @nb_inplace_power@ */
959 0, /* @nb_inplace_lshift@ */
960 0, /* @nb_inplace_rshift@ */
961 0, /* @nb_inplace_and@ */
962 0, /* @nb_inplace_xor@ */
963 0, /* @nb_inplace_or@ */
964
965 mp_pydiv, /* @nb_floor_divide@ */
966 0, /* @nb_true_divide@ */
967 0, /* @nb_inplace_floor_divide@ */
968 0, /* @nb_inplace_true_divide@ */
969
970 mp_pyint, /* @nb_index@ */
971 };
972
973 static const PyTypeObject mp_pytype_skel = {
974 PyVarObject_HEAD_INIT(0, 0) /* Header */
975 "MP", /* @tp_name@ */
976 sizeof(mp_pyobj), /* @tp_basicsize@ */
977 0, /* @tp_itemsize@ */
978
979 mp_pydealloc, /* @tp_dealloc@ */
980 0, /* @tp_print@ */
981 0, /* @tp_getattr@ */
982 0, /* @tp_setattr@ */
983 mp_pycompare, /* @tp_compare@ */
984 mp_pyrepr, /* @tp_repr@ */
985 PYNUMBER(mp), /* @tp_as_number@ */
986 0, /* @tp_as_sequence@ */
987 0, /* @tp_as_mapping@ */
988 mp_pyhash, /* @tp_hash@ */
989 0, /* @tp_call@ */
990 mp_pystr, /* @tp_str@ */
991 0, /* @tp_getattro@ */
992 0, /* @tp_setattro@ */
993 0, /* @tp_as_buffer@ */
994 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
995 Py_TPFLAGS_CHECKTYPES |
996 Py_TPFLAGS_BASETYPE,
997
998 /* @tp_doc@ */
999 "Multiprecision integers, similar to `long' but more efficient and\n"
1000 "versatile. Support all the standard arithmetic operations, with\n"
1001 "implicit conversions from `PrimeFilter', and other objects which\n"
1002 "convert to `long'.\n"
1003 "\n"
1004 "Constructor MP(X, [radix = R]) attempts to convert X to an `MP'. If\n"
1005 "X is a string, it's read in radix-R form, or we look for a prefix\n"
1006 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
1007 "points, group elements, Python `int' and `long' objects, and anything\n"
1008 "with an integer conversion.\n"
1009 "\n"
1010 "Notes:\n"
1011 "\n"
1012 " * Use `//' for integer division: `/' gives exact rational division.",
1013
1014 0, /* @tp_traverse@ */
1015 0, /* @tp_clear@ */
1016 mp_pyrichcompare, /* @tp_richcompare@ */
1017 0, /* @tp_weaklistoffset@ */
1018 0, /* @tp_iter@ */
1019 0, /* @tp_iternext@ */
1020 PYMETHODS(mp), /* @tp_methods@ */
1021 0, /* @tp_members@ */
1022 PYGETSET(mp), /* @tp_getset@ */
1023 0, /* @tp_base@ */
1024 0, /* @tp_dict@ */
1025 0, /* @tp_descr_get@ */
1026 0, /* @tp_descr_set@ */
1027 0, /* @tp_dictoffset@ */
1028 0, /* @tp_init@ */
1029 PyType_GenericAlloc, /* @tp_alloc@ */
1030 mp_pynew, /* @tp_new@ */
1031 0, /* @tp_free@ */
1032 0 /* @tp_is_gc@ */
1033 };
1034
1035 /*----- Products of small integers ----------------------------------------*/
1036
1037 static PyTypeObject *mpmul_pytype;
1038
1039 typedef struct mpmul_pyobj {
1040 PyObject_HEAD
1041 int livep;
1042 mpmul mm;
1043 } mpmul_pyobj;
1044
1045 #define MPMUL_LIVEP(o) (((mpmul_pyobj *)(o))->livep)
1046 #define MPMUL_PY(o) (&((mpmul_pyobj *)(o))->mm)
1047
1048 static void mpmul_pydealloc(PyObject *me)
1049 {
1050 if (MPMUL_LIVEP(me))
1051 mp_drop(mpmul_done(MPMUL_PY(me)));
1052 FREEOBJ(me);
1053 }
1054
1055 static PyObject *mmmeth_factor(PyObject *me, PyObject *arg)
1056 {
1057 PyObject *q, *i;
1058 mp *x;
1059
1060 if (!MPMUL_LIVEP(me)) VALERR("MPMul object invalid");
1061 if (PyTuple_GET_SIZE(arg) != 1)
1062 i = PyObject_GetIter(arg);
1063 else {
1064 if ((q = PyTuple_GET_ITEM(arg, 0)) == 0) goto end;
1065 if ((i = PyObject_GetIter(q)) == 0) {
1066 PyErr_Clear(); /* that's ok */
1067 i = PyObject_GetIter(arg);
1068 }
1069 }
1070 if (!i) goto end;
1071 while ((q = PyIter_Next(i)) != 0) {
1072 x = getmp(q); Py_DECREF(q); if (!x) {
1073 Py_DECREF(i);
1074 goto end;
1075 }
1076 mpmul_add(MPMUL_PY(me), x);
1077 MP_DROP(x);
1078 }
1079 Py_DECREF(i);
1080 RETURN_ME;
1081 end:
1082 return (0);
1083 }
1084
1085 static PyObject *mmmeth_done(PyObject *me)
1086 {
1087 mp *x;
1088
1089 if (!MPMUL_LIVEP(me)) VALERR("MPMul object invalid");
1090 x = mpmul_done(MPMUL_PY(me));
1091 MPMUL_LIVEP(me) = 0;
1092 return (mp_pywrap(x));
1093 end:
1094 return (0);
1095 }
1096
1097 static PyObject *mpmul_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1098 {
1099 mpmul_pyobj *mm;
1100
1101 if (kw) TYERR("keyword arguments not allowed here");
1102 mm = (mpmul_pyobj *)ty->tp_alloc(ty, 0);
1103 mpmul_init(&mm->mm);
1104 mm->livep = 1;
1105 if (mmmeth_factor((PyObject *)mm, arg) == 0) {
1106 Py_DECREF(mm);
1107 goto end;
1108 }
1109 return ((PyObject *)mm);
1110 end:
1111 return (0);
1112 }
1113
1114 static PyObject *mmget_livep(PyObject *me, void *hunoz)
1115 { return (getbool(MPMUL_LIVEP(me))); }
1116
1117 static const PyGetSetDef mpmul_pygetset[] = {
1118 #define GETSETNAME(op, name) mm##op##_##name
1119 GET (livep, "MM.livep -> flag: object still valid?")
1120 #undef GETSETNAME
1121 { 0 }
1122 };
1123
1124 static const PyMethodDef mpmul_pymethods[] = {
1125 #define METHNAME(name) mmmeth_##name
1126 METH (factor, "MM.factor(ITERABLE) or MM.factor(I, ...)")
1127 NAMETH(done, "MM.done() -> PRODUCT")
1128 #undef METHNAME
1129 { 0 }
1130 };
1131
1132 static const PyTypeObject mpmul_pytype_skel = {
1133 PyVarObject_HEAD_INIT(0, 0) /* Header */
1134 "MPMul", /* @tp_name@ */
1135 sizeof(mpmul_pyobj), /* @tp_basicsize@ */
1136 0, /* @tp_itemsize@ */
1137
1138 mpmul_pydealloc, /* @tp_dealloc@ */
1139 0, /* @tp_print@ */
1140 0, /* @tp_getattr@ */
1141 0, /* @tp_setattr@ */
1142 0, /* @tp_compare@ */
1143 0, /* @tp_repr@ */
1144 0, /* @tp_as_number@ */
1145 0, /* @tp_as_sequence@ */
1146 0, /* @tp_as_mapping@ */
1147 0, /* @tp_hash@ */
1148 0, /* @tp_call@ */
1149 0, /* @tp_str@ */
1150 0, /* @tp_getattro@ */
1151 0, /* @tp_setattro@ */
1152 0, /* @tp_as_buffer@ */
1153 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1154 Py_TPFLAGS_BASETYPE,
1155
1156 /* @tp_doc@ */
1157 "MPMul(N_0, N_1, ....): an object for multiplying many small integers.",
1158
1159 0, /* @tp_traverse@ */
1160 0, /* @tp_clear@ */
1161 0, /* @tp_richcompare@ */
1162 0, /* @tp_weaklistoffset@ */
1163 0, /* @tp_iter@ */
1164 0, /* @tp_iternext@ */
1165 PYMETHODS(mpmul), /* @tp_methods@ */
1166 0, /* @tp_members@ */
1167 PYGETSET(mpmul), /* @tp_getset@ */
1168 0, /* @tp_base@ */
1169 0, /* @tp_dict@ */
1170 0, /* @tp_descr_get@ */
1171 0, /* @tp_descr_set@ */
1172 0, /* @tp_dictoffset@ */
1173 0, /* @tp_init@ */
1174 PyType_GenericAlloc, /* @tp_alloc@ */
1175 mpmul_pynew, /* @tp_new@ */
1176 0, /* @tp_free@ */
1177 0 /* @tp_is_gc@ */
1178 };
1179
1180 /*----- Montgomery reduction ----------------------------------------------*/
1181
1182 static PyTypeObject *mpmont_pytype;
1183
1184 typedef struct mpmont_pyobj {
1185 PyObject_HEAD
1186 mpmont mm;
1187 } mpmont_pyobj;
1188
1189 #define MPMONT_PY(o) (&((mpmont_pyobj *)(o))->mm)
1190
1191 static PyObject *mmmeth_int(PyObject *me, PyObject *arg)
1192 {
1193 PyObject *z = 0;
1194 mp *yy = 0;
1195 mpmont *mm = MPMONT_PY(me);
1196
1197 if (!PyArg_ParseTuple(arg, "O&:in", convmp, &yy))
1198 goto end;
1199 mp_div(0, &yy, yy, mm->m);
1200 z = mp_pywrap(mpmont_mul(mm, MP_NEW, yy, mm->r2));
1201 end:
1202 if (yy) MP_DROP(yy);
1203 return (z);
1204 }
1205
1206 static PyObject *mmmeth_mul(PyObject *me, PyObject *arg)
1207 {
1208 PyObject *rc = 0;
1209 mp *yy = 0, *zz = 0;
1210
1211 if (!PyArg_ParseTuple(arg, "O&O&:mul", convmp, &yy, convmp, &zz))
1212 goto end;
1213 rc = mp_pywrap(mpmont_mul(MPMONT_PY(me), MP_NEW, yy, zz));
1214 end:
1215 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1216 return (rc);
1217 }
1218
1219 static PyObject *mmmeth_exp(PyObject *me, PyObject *arg)
1220 {
1221 PyObject *rc = 0;
1222 mp *yy = 0, *zz = 0;
1223
1224 if (!PyArg_ParseTuple(arg, "O&O&:exp", convmp, &yy, convmp, &zz))
1225 goto end;
1226 if (MP_NEGP(zz)) {
1227 if ((yy = mp_modinv_checked(yy, yy, MPMONT_PY(me)->m)) == 0) goto end;
1228 zz = mp_neg(zz, zz);
1229 }
1230 rc = mp_pywrap(mpmont_exp(MPMONT_PY(me), MP_NEW, yy, zz));
1231 end:
1232 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1233 return (rc);
1234 }
1235
1236 static PyObject *mmmeth_expr(PyObject *me, PyObject *arg)
1237 {
1238 PyObject *rc = 0;
1239 mp *yy = 0, *zz = 0;
1240
1241 if (!PyArg_ParseTuple(arg, "O&O&:expr", convmp, &yy, convmp, &zz))
1242 goto end;
1243 if (MP_NEGP(zz)) {
1244 yy = mpmont_reduce(MPMONT_PY(me), yy, yy);
1245 if ((yy = mp_modinv_checked(yy, yy, MPMONT_PY(me)->m)) == 0) goto end;
1246 yy = mpmont_mul(MPMONT_PY(me), yy, yy, MPMONT_PY(me)->r2);
1247 zz = mp_neg(zz, zz);
1248 }
1249 rc = mp_pywrap(mpmont_expr(MPMONT_PY(me), MP_NEW, yy, zz));
1250 end:
1251 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1252 return (rc);
1253 }
1254
1255 static PyObject *mm_mexpr_id(PyObject *me)
1256 { return mp_pywrap(MP_COPY(MPMONT_PY(me)->r)); }
1257
1258 static int mm_mexpr_fill(void *p, PyObject *me, PyObject *x, PyObject *y)
1259 {
1260 mp *xx = 0, *yy = 0;
1261 mp_expfactor *f = p;
1262 mpmont *mm = MPMONT_PY(me);
1263
1264 if ((xx = getmp(x)) == 0 || (yy = getmp(y)) == 0)
1265 goto fail;
1266 if (MP_NEGP(yy)) {
1267 xx = mpmont_reduce(mm, xx, xx);
1268 if ((xx = mp_modinv_checked(xx, xx, yy)) == 0)
1269 goto fail;
1270 xx = mpmont_mul(mm, xx, xx, mm->r2);
1271 yy = mp_neg(yy, yy);
1272 }
1273 f->base = xx;
1274 f->exp = yy;
1275 return (0);
1276
1277 fail:
1278 mp_drop(xx); mp_drop(yy);
1279 return (-1);
1280 }
1281
1282 static PyObject *mm_mexpr(PyObject *me, void *v, int n)
1283 { return mp_pywrap(mpmont_mexpr(MPMONT_PY(me), MP_NEW, v, n)); }
1284
1285 static void mp_mexp_drop(void *p)
1286 {
1287 mp_expfactor *f = p;
1288 mp_drop(f->base);
1289 mp_drop(f->exp);
1290 }
1291
1292 static PyObject *mmmeth_mexpr(PyObject *me, PyObject *arg)
1293 {
1294 return mexp_common(me, arg, sizeof(mp_expfactor),
1295 mm_mexpr_id, mm_mexpr_fill, mm_mexpr, mp_mexp_drop);
1296 }
1297
1298 static PyObject *mp_mexp_id(PyObject *me)
1299 { return mp_pywrap(MP_ONE); }
1300
1301 static int mp_mexp_fill(void *p, PyObject *me, PyObject *x, PyObject *y)
1302 {
1303 mp *xx = 0, *yy = 0;
1304 mp_expfactor *f = p;
1305
1306 if ((xx = getmp(x)) == 0 || (yy = getmp(y)) == 0)
1307 goto fail;
1308 if (MP_NEGP(yy)) {
1309 if ((xx = mp_modinv_checked(xx, xx, yy)) == 0)
1310 goto fail;
1311 yy = mp_neg(yy, yy);
1312 }
1313 f->base = xx;
1314 f->exp = yy;
1315 return (0);
1316
1317 fail:
1318 mp_drop(xx); mp_drop(yy);
1319 return (-1);
1320 }
1321
1322 static PyObject *mm_mexp(PyObject *me, void *v, int n)
1323 { return mp_pywrap(mpmont_mexp(MPMONT_PY(me), MP_NEW, v, n)); }
1324
1325 static PyObject *mmmeth_mexp(PyObject *me, PyObject *arg)
1326 {
1327 return mexp_common(me, arg, sizeof(mp_expfactor),
1328 mp_mexp_id, mp_mexp_fill, mm_mexp, mp_mexp_drop);
1329 }
1330
1331 #define mmmeth_ext mmmeth_reduce
1332 static PyObject *mmmeth_reduce(PyObject *me, PyObject *arg)
1333 {
1334 PyObject *z = 0;
1335 mp *yy = 0;
1336
1337 if (!PyArg_ParseTuple(arg, "O&", convmp, &yy)) goto end;
1338 z = mp_pywrap(mpmont_reduce(MPMONT_PY(me), MP_NEW, yy));
1339 end:
1340 return (z);
1341 }
1342
1343 static void mpmont_pydealloc(PyObject *me)
1344 {
1345 mpmont_destroy(MPMONT_PY(me));
1346 FREEOBJ(me);
1347 }
1348
1349 static PyObject *mpmont_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1350 {
1351 mpmont_pyobj *mm = 0;
1352 static const char *const kwlist[] = { "m", 0 };
1353 mp *xx = 0;
1354
1355 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
1356 goto end;
1357 if (!MP_POSP(xx) || !MP_ODDP(xx)) VALERR("m must be positive and odd");
1358 mm = (mpmont_pyobj *)ty->tp_alloc(ty, 0);
1359 mpmont_create(&mm->mm, xx);
1360 end:
1361 if (xx) MP_DROP(xx);
1362 return ((PyObject *)mm);
1363 }
1364
1365 static PyObject *mmget_m(PyObject *me, void *hunoz)
1366 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->m))); }
1367
1368 static PyObject *mmget_r(PyObject *me, void *hunoz)
1369 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->r))); }
1370
1371 static PyObject *mmget_r2(PyObject *me, void *hunoz)
1372 { return (mp_pywrap(MP_COPY(MPMONT_PY(me)->r2))); }
1373
1374 static const PyGetSetDef mpmont_pygetset[] = {
1375 #define GETSETNAME(op, name) mm##op##_##name
1376 GET (m, "M.m -> modulus for reduction")
1377 GET (r, "M.r -> multiplicative identity")
1378 GET (r2, "M.r2 -> M.r^2, Montgomerization factor")
1379 #undef GETSETNAME
1380 { 0 }
1381 };
1382
1383 static const PyMethodDef mpmont_pymethods[] = {
1384 #define METHNAME(name) mmmeth_##name
1385 METH (int, "M.int(X) -> XR")
1386 METH (mul, "M.mul(XR, YR) -> ZR where Z = X Y")
1387 METH (expr, "M.expr(XR, N) -> ZR where Z = X^N mod M.m")
1388 METH (mexpr, "M.mexpr([(XR0, N0), (XR1, N1), ...]) = ZR "
1389 "where Z = X0^N0 X1^N1 ... mod M.m\n"
1390 "\t(the list may be flattened if this more convenient.)")
1391 METH (reduce, "M.reduce(XR) -> X")
1392 METH (ext, "M.ext(XR) -> X")
1393 METH (exp, "M.exp(X, N) -> X^N mod M.m")
1394 METH (mexp, "M.mexp([(X0, N0), (X1, N1), ...]) = "
1395 "X0^N0 X1^N1 ... mod M.m\n"
1396 "\t(the list may be flattened if this more convenient.)")
1397 #undef METHNAME
1398 { 0 }
1399 };
1400
1401 static const PyTypeObject mpmont_pytype_skel = {
1402 PyVarObject_HEAD_INIT(0, 0) /* Header */
1403 "MPMont", /* @tp_name@ */
1404 sizeof(mpmont_pyobj), /* @tp_basicsize@ */
1405 0, /* @tp_itemsize@ */
1406
1407 mpmont_pydealloc, /* @tp_dealloc@ */
1408 0, /* @tp_print@ */
1409 0, /* @tp_getattr@ */
1410 0, /* @tp_setattr@ */
1411 0, /* @tp_compare@ */
1412 0, /* @tp_repr@ */
1413 0, /* @tp_as_number@ */
1414 0, /* @tp_as_sequence@ */
1415 0, /* @tp_as_mapping@ */
1416 0, /* @tp_hash@ */
1417 0, /* @tp_call@ */
1418 0, /* @tp_str@ */
1419 0, /* @tp_getattro@ */
1420 0, /* @tp_setattro@ */
1421 0, /* @tp_as_buffer@ */
1422 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1423 Py_TPFLAGS_BASETYPE,
1424
1425 /* @tp_doc@ */
1426 "MPMont(N): a Montgomery reduction context.",
1427
1428 0, /* @tp_traverse@ */
1429 0, /* @tp_clear@ */
1430 0, /* @tp_richcompare@ */
1431 0, /* @tp_weaklistoffset@ */
1432 0, /* @tp_iter@ */
1433 0, /* @tp_iternext@ */
1434 PYMETHODS(mpmont), /* @tp_methods@ */
1435 0, /* @tp_members@ */
1436 PYGETSET(mpmont), /* @tp_getset@ */
1437 0, /* @tp_base@ */
1438 0, /* @tp_dict@ */
1439 0, /* @tp_descr_get@ */
1440 0, /* @tp_descr_set@ */
1441 0, /* @tp_dictoffset@ */
1442 0, /* @tp_init@ */
1443 PyType_GenericAlloc, /* @tp_alloc@ */
1444 mpmont_pynew, /* @tp_new@ */
1445 0, /* @tp_free@ */
1446 0 /* @tp_is_gc@ */
1447 };
1448
1449 /*----- Barrett reduction -------------------------------------------------*/
1450
1451 static PyTypeObject *mpbarrett_pytype;
1452
1453 typedef struct mpbarrett_pyobj {
1454 PyObject_HEAD
1455 mpbarrett mb;
1456 } mpbarrett_pyobj;
1457
1458 #define MPBARRETT_PY(o) (&((mpbarrett_pyobj *)(o))->mb)
1459
1460 static PyObject *mbmeth_exp(PyObject *me, PyObject *arg)
1461 {
1462 PyObject *rc = 0;
1463 mp *yy = 0, *zz = 0;
1464
1465 if (!PyArg_ParseTuple(arg, "O&O&:exp", convmp, &yy, convmp, &zz))
1466 goto end;
1467 if (MP_NEGP(zz)) {
1468 if ((yy = mp_modinv_checked(yy, yy, MPBARRETT_PY(me)->m)) == 0) goto end;
1469 zz = mp_neg(zz, zz);
1470 }
1471 rc = mp_pywrap(mpbarrett_exp(MPBARRETT_PY(me), MP_NEW, yy, zz));
1472 end:
1473 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1474 return (rc);
1475 }
1476
1477 static PyObject *mb_mexp(PyObject *me, void *v, int n)
1478 { return mp_pywrap(mpbarrett_mexp(MPBARRETT_PY(me), MP_NEW, v, n)); }
1479
1480 static PyObject *mbmeth_mexp(PyObject *me, PyObject *arg)
1481 {
1482 return mexp_common(me, arg, sizeof(mp_expfactor),
1483 mp_mexp_id, mp_mexp_fill, mb_mexp, mp_mexp_drop);
1484 }
1485
1486 static PyObject *mbmeth_reduce(PyObject *me, PyObject *arg)
1487 {
1488 PyObject *z = 0;
1489 mp *yy = 0;
1490
1491 if (!PyArg_ParseTuple(arg, "O&:reduce", convmp, &yy))
1492 goto end;
1493 z = mp_pywrap(mpbarrett_reduce(MPBARRETT_PY(me), MP_NEW, yy));
1494 end:
1495 return (z);
1496 }
1497
1498 static void mpbarrett_pydealloc(PyObject *me)
1499 {
1500 mpbarrett_destroy(MPBARRETT_PY(me));
1501 FREEOBJ(me);
1502 }
1503
1504 static PyObject *mpbarrett_pynew(PyTypeObject *ty,
1505 PyObject *arg, PyObject *kw)
1506 {
1507 mpbarrett_pyobj *mb = 0;
1508 static const char *const kwlist[] = { "m", 0 };
1509 mp *xx = 0;
1510
1511 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
1512 goto end;
1513 if (!MP_POSP(xx)) VALERR("m must be positive");
1514 mb = (mpbarrett_pyobj *)ty->tp_alloc(ty, 0);
1515 mpbarrett_create(&mb->mb, xx);
1516 end:
1517 if (xx) MP_DROP(xx);
1518 return ((PyObject *)mb);
1519 }
1520
1521 static PyObject *mbget_m(PyObject *me, void *hunoz)
1522 { return (mp_pywrap(MP_COPY(MPBARRETT_PY(me)->m))); }
1523
1524 static const PyGetSetDef mpbarrett_pygetset[] = {
1525 #define GETSETNAME(op, name) mb##op##_##name
1526 GET (m, "B.m -> modulus for reduction")
1527 #undef GETSETNAME
1528 { 0 }
1529 };
1530
1531 static const PyMethodDef mpbarrett_pymethods[] = {
1532 #define METHNAME(name) mbmeth_##name
1533 METH (reduce, "B.reduce(X) -> X mod B.m")
1534 METH (exp, "B.exp(X, N) -> X^N mod B.m")
1535 METH (mexp, "B.mexp([(X0, N0), (X1, N1), ...]) = "
1536 "X0^N0 X1^N1 ... mod B.m\n"
1537 "\t(the list may be flattened if this more convenient.)")
1538 #undef METHNAME
1539 { 0 }
1540 };
1541
1542 static const PyTypeObject mpbarrett_pytype_skel = {
1543 PyVarObject_HEAD_INIT(0, 0) /* Header */
1544 "MPBarrett", /* @tp_name@ */
1545 sizeof(mpbarrett_pyobj), /* @tp_basicsize@ */
1546 0, /* @tp_itemsize@ */
1547
1548 mpbarrett_pydealloc, /* @tp_dealloc@ */
1549 0, /* @tp_print@ */
1550 0, /* @tp_getattr@ */
1551 0, /* @tp_setattr@ */
1552 0, /* @tp_compare@ */
1553 0, /* @tp_repr@ */
1554 0, /* @tp_as_number@ */
1555 0, /* @tp_as_sequence@ */
1556 0, /* @tp_as_mapping@ */
1557 0, /* @tp_hash@ */
1558 0, /* @tp_call@ */
1559 0, /* @tp_str@ */
1560 0, /* @tp_getattro@ */
1561 0, /* @tp_setattro@ */
1562 0, /* @tp_as_buffer@ */
1563 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1564 Py_TPFLAGS_BASETYPE,
1565
1566 /* @tp_doc@ */
1567 "MPBarrett(N): a Barrett reduction context.",
1568
1569 0, /* @tp_traverse@ */
1570 0, /* @tp_clear@ */
1571 0, /* @tp_richcompare@ */
1572 0, /* @tp_weaklistoffset@ */
1573 0, /* @tp_iter@ */
1574 0, /* @tp_iternext@ */
1575 PYMETHODS(mpbarrett), /* @tp_methods@ */
1576 0, /* @tp_members@ */
1577 PYGETSET(mpbarrett), /* @tp_getset@ */
1578 0, /* @tp_base@ */
1579 0, /* @tp_dict@ */
1580 0, /* @tp_descr_get@ */
1581 0, /* @tp_descr_set@ */
1582 0, /* @tp_dictoffset@ */
1583 0, /* @tp_init@ */
1584 PyType_GenericAlloc, /* @tp_alloc@ */
1585 mpbarrett_pynew, /* @tp_new@ */
1586 0, /* @tp_free@ */
1587 0 /* @tp_is_gc@ */
1588 };
1589
1590 /*----- Nice prime reduction ----------------------------------------------*/
1591
1592 static PyTypeObject *mpreduce_pytype;
1593
1594 typedef struct mpreduce_pyobj {
1595 PyObject_HEAD
1596 mpreduce mr;
1597 } mpreduce_pyobj;
1598
1599 #define MPREDUCE_PY(o) (&((mpreduce_pyobj *)(o))->mr)
1600
1601 static PyObject *mrmeth_exp(PyObject *me, PyObject *arg)
1602 {
1603 PyObject *rc = 0;
1604 mp *yy = 0, *zz = 0;
1605
1606 if (!PyArg_ParseTuple(arg, "O&O&:exp", convmp, &yy, convmp, &zz))
1607 goto end;
1608 if (MP_NEGP(zz)) {
1609 if ((yy = mp_modinv_checked(yy, yy, MPREDUCE_PY(me)->p)) == 0) goto end;
1610 zz = mp_neg(zz, zz);
1611 }
1612 rc = mp_pywrap(mpreduce_exp(MPREDUCE_PY(me), MP_NEW, yy, zz));
1613 end:
1614 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
1615 return (rc);
1616 }
1617
1618 static PyObject *mrmeth_reduce(PyObject *me, PyObject *arg)
1619 {
1620 PyObject *z = 0;
1621 mp *yy = 0;
1622
1623 if (!PyArg_ParseTuple(arg, "O&:reduce", convmp, &yy)) goto end;
1624 z = mp_pywrap(mpreduce_do(MPREDUCE_PY(me), MP_NEW, yy));
1625 end:
1626 return (z);
1627 }
1628
1629 static void mpreduce_pydealloc(PyObject *me)
1630 {
1631 mpreduce_destroy(MPREDUCE_PY(me));
1632 FREEOBJ(me);
1633 }
1634
1635 static PyObject *mpreduce_pynew(PyTypeObject *ty,
1636 PyObject *arg, PyObject *kw)
1637 {
1638 mpreduce_pyobj *mr = 0;
1639 mpreduce r;
1640 static const char *const kwlist[] = { "m", 0 };
1641 mp *xx = 0;
1642
1643 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convmp, &xx))
1644 goto end;
1645 if (!MP_POSP(xx)) VALERR("m must be positive");
1646 if (mpreduce_create(&r, xx)) VALERR("bad modulus (must be 2^k - ...)");
1647 mr = (mpreduce_pyobj *)ty->tp_alloc(ty, 0);
1648 mr->mr = r;
1649 end:
1650 if (xx) MP_DROP(xx);
1651 return ((PyObject *)mr);
1652 }
1653
1654 static PyObject *mrget_m(PyObject *me, void *hunoz)
1655 { return (mp_pywrap(MP_COPY(MPREDUCE_PY(me)->p))); }
1656
1657 static const PyGetSetDef mpreduce_pygetset[] = {
1658 #define GETSETNAME(op, name) mr##op##_##name
1659 GET (m, "R.m -> modulus for reduction")
1660 #undef GETSETNAME
1661 { 0 }
1662 };
1663
1664 static const const PyMethodDef mpreduce_pymethods[] = {
1665 #define METHNAME(name) mrmeth_##name
1666 METH (reduce, "R.reduce(X) -> X mod B.m")
1667 METH (exp, "R.exp(X, N) -> X^N mod B.m")
1668 #undef METHNAME
1669 { 0 }
1670 };
1671
1672 static const PyTypeObject mpreduce_pytype_skel = {
1673 PyVarObject_HEAD_INIT(0, 0) /* Header */
1674 "MPReduce", /* @tp_name@ */
1675 sizeof(mpreduce_pyobj), /* @tp_basicsize@ */
1676 0, /* @tp_itemsize@ */
1677
1678 mpreduce_pydealloc, /* @tp_dealloc@ */
1679 0, /* @tp_print@ */
1680 0, /* @tp_getattr@ */
1681 0, /* @tp_setattr@ */
1682 0, /* @tp_compare@ */
1683 0, /* @tp_repr@ */
1684 0, /* @tp_as_number@ */
1685 0, /* @tp_as_sequence@ */
1686 0, /* @tp_as_mapping@ */
1687 0, /* @tp_hash@ */
1688 0, /* @tp_call@ */
1689 0, /* @tp_str@ */
1690 0, /* @tp_getattro@ */
1691 0, /* @tp_setattro@ */
1692 0, /* @tp_as_buffer@ */
1693 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1694 Py_TPFLAGS_BASETYPE,
1695
1696 /* @tp_doc@ */
1697 "MPReduce(N): a reduction context for reduction modulo Solinas primes.",
1698
1699 0, /* @tp_traverse@ */
1700 0, /* @tp_clear@ */
1701 0, /* @tp_richcompare@ */
1702 0, /* @tp_weaklistoffset@ */
1703 0, /* @tp_iter@ */
1704 0, /* @tp_iternext@ */
1705 PYMETHODS(mpreduce), /* @tp_methods@ */
1706 0, /* @tp_members@ */
1707 PYGETSET(mpreduce), /* @tp_getset@ */
1708 0, /* @tp_base@ */
1709 0, /* @tp_dict@ */
1710 0, /* @tp_descr_get@ */
1711 0, /* @tp_descr_set@ */
1712 0, /* @tp_dictoffset@ */
1713 0, /* @tp_init@ */
1714 PyType_GenericAlloc, /* @tp_alloc@ */
1715 mpreduce_pynew, /* @tp_new@ */
1716 0, /* @tp_free@ */
1717 0 /* @tp_is_gc@ */
1718 };
1719
1720 /*----- Chinese Remainder Theorem solution --------------------------------*/
1721
1722 static PyTypeObject *mpcrt_pytype;
1723
1724 typedef struct mpcrt_pyobj {
1725 PyObject_HEAD
1726 mpcrt c;
1727 } mpcrt_pyobj;
1728
1729 #define MPCRT_PY(o) (&((mpcrt_pyobj *)(o))->c)
1730
1731 static PyObject *mcmeth_solve(PyObject *me, PyObject *arg)
1732 {
1733 mpcrt *c = MPCRT_PY(me);
1734 PyObject *q = 0, *x, *z = 0;
1735 mp *xx;
1736 mp **v = 0;
1737 Py_ssize_t i = 0, n = c->k;
1738
1739 Py_INCREF(me);
1740 if (PyTuple_GET_SIZE(arg) == n)
1741 q = arg;
1742 else if (!PyArg_ParseTuple(arg, "O:solve", &q))
1743 goto end;
1744 Py_INCREF(q);
1745 if (!PySequence_Check(q)) TYERR("want a sequence of residues");
1746 i = PySequence_Size(q); if (i < 0) goto end;
1747 if (i != n) VALERR("residue count mismatch");
1748 v = xmalloc(n * sizeof(*v));
1749 for (i = 0; i < n; i++) {
1750 if ((x = PySequence_GetItem(q, i)) == 0) goto end;
1751 xx = getmp(x); Py_DECREF(x); if (!xx) goto end;
1752 v[i] = xx;
1753 }
1754 z = mp_pywrap(mpcrt_solve(c, MP_NEW, v));
1755 end:
1756 if (v) {
1757 n = i;
1758 for (i = 0; i < n; i++)
1759 MP_DROP(v[i]);
1760 xfree(v);
1761 }
1762 Py_DECREF(me);
1763 Py_XDECREF(q);
1764 return (z);
1765 }
1766
1767 static void mpcrt_pydealloc(PyObject *me)
1768 {
1769 mpcrt *c = MPCRT_PY(me);
1770 mpcrt_destroy(c);
1771 xfree(c->v);
1772 }
1773
1774 static PyObject *mpcrt_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1775 {
1776 mpcrt_mod *v = 0;
1777 Py_ssize_t n, i = 0, j;
1778 static const char *const kwlist[] = { "mv", 0 };
1779 PyObject *q = 0, *x;
1780 mp *xx = MP_NEW, *y = MP_NEW, *g = MP_NEW;
1781 mpmul mm;
1782 mpcrt_pyobj *c = 0;
1783
1784 if (PyTuple_GET_SIZE(arg) > 1)
1785 q = arg;
1786 else if (!PyArg_ParseTupleAndKeywords(arg, kw, "O:new", KWLIST, &q))
1787 goto end;
1788 Py_INCREF(q);
1789 if (!PySequence_Check(q)) TYERR("want a sequence of moduli");
1790 n = PySequence_Size(q); if (n < 0) goto end;
1791 if (!n) VALERR("want at least one modulus");
1792 v = xmalloc(n * sizeof(*v));
1793 for (i = 0; i < n; i++) {
1794 if ((x = PySequence_GetItem(q, i)) == 0) goto end;
1795 xx = getmp(x); Py_DECREF(x); if (!xx) goto end;
1796 if (MP_CMP(xx, <=, MP_ZERO)) VALERR("moduli must be positive");
1797 v[i].m = xx; v[i].n = 0; v[i].ni = 0; v[i].nni = 0; xx = MP_NEW;
1798 }
1799 mpmul_init(&mm);
1800 for (j = 0; j < i; j++) mpmul_add(&mm, v[j].m);
1801 xx = mpmul_done(&mm);
1802 for (j = 0; j < i; j++) {
1803 mp_div(&y, 0, xx, v[j].m);
1804 mp_gcd(&g, 0, 0, y, v[j].m);
1805 if (!MP_EQ(g, MP_ONE)) VALERR("moduli must be pairwise coprime");
1806 }
1807
1808 c = (mpcrt_pyobj *)ty->tp_alloc(ty, 0);
1809 mpcrt_create(&c->c, v, n, 0);
1810 Py_DECREF(q);
1811 mp_drop(xx); mp_drop(y); mp_drop(g);
1812 return ((PyObject *)c);
1813
1814 end:
1815 if (v) {
1816 n = i;
1817 for (i = 0; i < n; i++)
1818 MP_DROP(v[i].m);
1819 xfree(v);
1820 }
1821 Py_XDECREF(q);
1822 mp_drop(xx); mp_drop(y); mp_drop(g);
1823 return (0);
1824 }
1825
1826 static PyObject *mcget_product(PyObject *me, void *hunoz)
1827 { return (mp_pywrap(MP_COPY(MPCRT_PY(me)->mb.m))); }
1828
1829 static PyObject *mcget_moduli(PyObject *me, void *hunoz)
1830 {
1831 int i;
1832 PyObject *q;
1833 mpcrt *c = MPCRT_PY(me);
1834
1835 if ((q = PyList_New(c->k)) == 0) return (0);
1836 for (i = 0; i < c->k; i++)
1837 PyList_SET_ITEM(q, i, mp_pywrap(c->v[i].m));
1838 return (q);
1839 }
1840
1841 static const PyGetSetDef mpcrt_pygetset[] = {
1842 #define GETSETNAME(op, name) mc##op##_##name
1843 GET (product, "C.product -> product of moduli")
1844 GET (moduli, "C.moduli -> list of individual moduli")
1845 #undef GETSETNAME
1846 { 0 }
1847 };
1848
1849 static const PyMethodDef mpcrt_pymethods[] = {
1850 #define METHNAME(name) mcmeth_##name
1851 METH (solve, "C.solve([R0, R1]) -> X mod C.product")
1852 #undef METHNAME
1853 { 0 }
1854 };
1855
1856 static const PyTypeObject mpcrt_pytype_skel = {
1857 PyVarObject_HEAD_INIT(0, 0) /* Header */
1858 "MPCRT", /* @tp_name@ */
1859 sizeof(mpcrt_pyobj), /* @tp_basicsize@ */
1860 0, /* @tp_itemsize@ */
1861
1862 mpcrt_pydealloc, /* @tp_dealloc@ */
1863 0, /* @tp_print@ */
1864 0, /* @tp_getattr@ */
1865 0, /* @tp_setattr@ */
1866 0, /* @tp_compare@ */
1867 0, /* @tp_repr@ */
1868 0, /* @tp_as_number@ */
1869 0, /* @tp_as_sequence@ */
1870 0, /* @tp_as_mapping@ */
1871 0, /* @tp_hash@ */
1872 0, /* @tp_call@ */
1873 0, /* @tp_str@ */
1874 0, /* @tp_getattro@ */
1875 0, /* @tp_setattro@ */
1876 0, /* @tp_as_buffer@ */
1877 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
1878 Py_TPFLAGS_BASETYPE,
1879
1880 /* @tp_doc@ */
1881 "MPCRT(SEQ): a context for solving Chinese Remainder Theorem problems.",
1882
1883 0, /* @tp_traverse@ */
1884 0, /* @tp_clear@ */
1885 0, /* @tp_richcompare@ */
1886 0, /* @tp_weaklistoffset@ */
1887 0, /* @tp_iter@ */
1888 0, /* @tp_iternext@ */
1889 PYMETHODS(mpcrt), /* @tp_methods@ */
1890 0, /* @tp_members@ */
1891 PYGETSET(mpcrt), /* @tp_getset@ */
1892 0, /* @tp_base@ */
1893 0, /* @tp_dict@ */
1894 0, /* @tp_descr_get@ */
1895 0, /* @tp_descr_set@ */
1896 0, /* @tp_dictoffset@ */
1897 0, /* @tp_init@ */
1898 PyType_GenericAlloc, /* @tp_alloc@ */
1899 mpcrt_pynew, /* @tp_new@ */
1900 0, /* @tp_free@ */
1901 0 /* @tp_is_gc@ */
1902 };
1903
1904 /*----- Binary polynomials ------------------------------------------------*/
1905
1906 static PyObject *gf_pyrepr(PyObject *o)
1907 { return mp_topystring(MP_X(o), 16, "GF(", "0x", ")"); }
1908
1909 static PyObject *gf_pyrichcompare(PyObject *x, PyObject *y, int op)
1910 {
1911 mp *xx, *yy;
1912 int xl, yl;
1913 int b;
1914
1915 if (gfbinop(x, y, &xx, &yy)) RETURN_NOTIMPL;
1916 switch (op) {
1917 case Py_EQ: b = MP_EQ(xx, yy); break;
1918 case Py_NE: b = !MP_EQ(xx, yy); break;
1919 default:
1920 xl = mp_bits(xx);
1921 yl = mp_bits(yy);
1922 switch (op) {
1923 case Py_LT: b = xl < yl; break;
1924 case Py_LE: b = xl <= yl; break;
1925 case Py_GT: b = xl > yl; break;
1926 case Py_GE: b = xl >= yl; break;
1927 default: abort();
1928 }
1929 break;
1930 }
1931 MP_DROP(xx); MP_DROP(yy);
1932 return (getbool(b));
1933 }
1934
1935 static PyObject *gf_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1936 {
1937 PyObject *x;
1938 mp *z;
1939 mp_pyobj *zz = 0;
1940 int radix = 0;
1941 static const char *const kwlist[] = { "x", "radix", 0 };
1942
1943 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O|i:gf", KWLIST, &x, &radix))
1944 goto end;
1945 if (GF_PYCHECK(x)) RETURN_OBJ(x);
1946 if (!good_radix_p(radix, 1)) VALERR("radix out of range");
1947 if ((z = mp_frompyobject(x, radix)) == 0) {
1948 PyErr_Format(PyExc_TypeError, "can't convert %.100s to gf",
1949 Py_TYPE(x)->tp_name);
1950 goto end;
1951 }
1952 if (MP_NEGP(z)) {
1953 MP_DROP(z);
1954 VALERR("gf cannot be negative");
1955 }
1956 zz = (mp_pyobj *)ty->tp_alloc(ty, 0);
1957 zz->x = z;
1958 end:
1959 return ((PyObject *)zz);
1960 }
1961
1962 static PyObject *gf_pyexp(PyObject *x, PyObject *y, PyObject *z)
1963 {
1964 mp *xx = 0, *yy = 0, *zz = 0;
1965 mp *r = 0;
1966 PyObject *rc = 0;
1967
1968 if ((xx = tomp(x)) == 0 || (yy = tomp(y)) == 0 ||
1969 (z && z != Py_None && (zz = tomp(z)) == 0)) {
1970 mp_drop(xx); mp_drop(yy); mp_drop(zz);
1971 RETURN_NOTIMPL;
1972 }
1973 if (!z || z == Py_None) {
1974 if (MP_NEGP(yy)) VALERR("negative exponent");
1975 r = gf_exp(MP_NEW, xx, yy);
1976 } else {
1977 gfreduce gr;
1978 if (MP_ZEROP(zz)) ZDIVERR("zero modulus");
1979 if (MP_NEGP(yy)) {
1980 if ((xx = gf_modinv_checked(xx, xx, zz)) == 0) goto end;
1981 yy = mp_neg(yy, yy);
1982 }
1983 gfreduce_create(&gr, zz);
1984 r = gfreduce_exp(&gr, MP_NEW, xx, yy);
1985 gfreduce_destroy(&gr);
1986 }
1987 rc = gf_pywrap(r);
1988 end:
1989 mp_drop(xx); mp_drop(yy); mp_drop(zz);
1990 return (rc);
1991 }
1992
1993 static PyObject *gfmeth_sqr(PyObject *me)
1994 { return (gf_pywrap(gf_sqr(MP_NEW, MP_X(me)))); }
1995
1996 static PyObject *gfmeth_gcd(PyObject *me, PyObject *arg)
1997 {
1998 PyObject *z = 0;
1999 mp *yy = 0, *zz = MP_NEW;
2000
2001 if (!PyArg_ParseTuple(arg, "O&:gcd", convgf, &yy)) goto end;
2002 gf_gcd(&zz, 0, 0, MP_X(me), yy);
2003 z = gf_pywrap(zz);
2004 end:
2005 if (yy) MP_DROP(yy);
2006 return (z);
2007 }
2008
2009 static PyObject *gfmeth_gcdx(PyObject *me, PyObject *arg)
2010 {
2011 PyObject *z = 0;
2012 mp *yy = 0, *zz = MP_NEW, *uu = MP_NEW, *vv = MP_NEW;
2013
2014 if (!PyArg_ParseTuple(arg, "O&:gcdx", convgf, &yy))
2015 goto end;
2016 gf_gcd(&zz, &uu, &vv, MP_X(me), yy);
2017 z = Py_BuildValue("(NNN)",
2018 gf_pywrap(zz), gf_pywrap(uu), gf_pywrap(vv));
2019 end:
2020 if (yy) MP_DROP(yy);
2021 return (z);
2022 }
2023
2024 static PyObject *gfmeth_modinv(PyObject *me, PyObject *arg)
2025 {
2026 PyObject *z = 0;
2027 mp *yy = 0, *zz = MP_NEW;
2028
2029 if (!PyArg_ParseTuple(arg, "O&:modinv", convgf, &yy) ||
2030 (zz = gf_modinv_checked(MP_NEW, yy, MP_X(me))) == 0)
2031 goto end;
2032 z = gf_pywrap(zz);
2033 end:
2034 if (yy) MP_DROP(yy);
2035 return (z);
2036 }
2037
2038 static PyObject *gfmeth_fromstring(PyObject *me,
2039 PyObject *arg, PyObject *kw)
2040 {
2041 int r = 0;
2042 char *p;
2043 Py_ssize_t len;
2044 PyObject *z = 0;
2045 mp *zz;
2046 mptext_stringctx sc;
2047 static const char *const kwlist[] = { "x", "radix", 0 };
2048
2049 if (!PyArg_ParseTupleAndKeywords(arg, kw, "s#|i:fromstring", KWLIST,
2050 &p, &len, &r))
2051 goto end;
2052 if (!good_radix_p(r, 1)) VALERR("bad radix");
2053 sc.buf = p; sc.lim = p + len;
2054 if ((zz = mp_read(MP_NEW, r, &mptext_stringops, &sc)) == 0 ||
2055 MP_NEGP(zz)) {
2056 if (zz) MP_DROP(zz);
2057 VALERR("bad binary polynomial");
2058 }
2059 z = Py_BuildValue("(Ns#)", gf_pywrap(zz),
2060 sc.buf, (Py_ssize_t)(sc.lim - sc.buf));
2061 end:
2062 return (z);
2063 }
2064
2065 static PyObject *gfmeth_irreduciblep(PyObject *me)
2066 { return getbool(gf_irreduciblep(MP_X(me))); }
2067
2068 static PyObject *gfget_degree(PyObject *me, void *hunoz)
2069 { return (PyInt_FromLong(mp_bits(MP_X(me)) - 1)); }
2070
2071 static const PyGetSetDef gf_pygetset[] = {
2072 #define GETSETNAME(op, name) gf##op##_##name
2073 GET (degree, "X.degree -> polynomial degree of X")
2074 #undef GETSETNAME
2075 #define GETSETNAME(op, name) mp##op##_##name
2076 GET (nbits, "X.nbits -> bit length of X")
2077 GET (noctets, "X.noctets -> octet length of X")
2078 #undef GETSETNAME
2079 { 0 }
2080 };
2081
2082 static const PyMethodDef gf_pymethods[] = {
2083 #define METHNAME(func) gfmeth_##func
2084 METH (setbit, "X.setbit(N) -> X with bit N set")
2085 METH (clearbit, "X.clearbit(N) -> X with bit N clear")
2086 METH (testbit, "X.testbit(N) -> true/false if bit N set/clear in X")
2087 NAMETH(sqr, "X.sqr() -> X^2")
2088 METH (gcd, "X.gcd(Y) -> gcd(X, Y)")
2089 METH (gcdx, "X.gcdx(Y) -> (gcd(X, Y), U, V) with X U + Y V = gcd(X, Y)")
2090 METH (modinv, "X.modinv(Y) -> multiplicative inverse of Y mod X")
2091 NAMETH(irreduciblep, "X.irreduciblep() -> true/false")
2092 KWSMTH(fromstring, "fromstring(STR, [radix = 0]) -> (X, REST)\n"
2093 " Parse STR as a binary polynomial, according to RADIX. If RADIX is\n"
2094 " zero, read a prefix from STR to decide radix: allow `0b' for binary,\n"
2095 " `0' or `0o' for octal, `0x' for hex, or `R_' for other radix R.")
2096 SMTH (loadl, "loadl(STR) -> X: read little-endian bytes")
2097 SMTH (loadb, "loadb(STR) -> X: read big-endian bytes")
2098 SMTH (frombuf, "frombuf(STR) -> (X, REST): read buffer format")
2099 #undef METHNAME
2100 #define METHNAME(func) mpmeth_##func
2101 KWMETH(tostring, "X.tostring([radix = 10]) -> STR")
2102 KWMETH(storel, "X.storel([len = -1]) -> little-endian bytes")
2103 KWMETH(storeb, "X.storeb([len = -1]) -> big-endian bytes")
2104 KWMETH(storel2c, "X.storel2c([len = -1]) -> "
2105 "little-endian bytes, two's complement")
2106 KWMETH(storeb2c, "X.storeb2c([len = -1]) -> "
2107 "big-endian bytes, two's complement")
2108 NAMETH(tobuf, "X.tobuf() -> buffer format")
2109 #undef METHNAME
2110 { 0 }
2111 };
2112
2113 static const PyNumberMethods gf_pynumber = {
2114 gf_pyadd, /* @nb_add@ */
2115 gf_pysub, /* @nb_subtract@ */
2116 gf_pymul, /* @nb_multiply@ */
2117 0, /* @nb_divide@ */
2118 gf_pymod, /* @nb_remainder@ */
2119 gf_pydivmod, /* @nb_divmod@ */
2120 gf_pyexp, /* @nb_power@ */
2121 mp_pyid, /* @nb_negative@ */
2122 mp_pyid, /* @nb_positive@ */
2123 mp_pyid, /* @nb_absolute@ */
2124 mp_pynonzerop, /* @nb_nonzero@ */
2125 0 /* doesn't make any sense */, /* @nb_invert@ */
2126 gf_pylsl, /* @nb_lshift@ */
2127 gf_pylsr, /* @nb_rshift@ */
2128 gf_pyand, /* @nb_and@ */
2129 gf_pyxor, /* @nb_xor@ */
2130 gf_pyor, /* @nb_or@ */
2131 gf_pycoerce, /* @nb_coerce@ */
2132 mp_pyint, /* @nb_int@ */
2133 mp_pylong, /* @nb_long@ */
2134 0 /* doesn't make any sense */, /* @nb_float@ */
2135 mp_pyoct, /* @nb_oct@ */
2136 mp_pyhex, /* @nb_hex@ */
2137
2138 0, /* @nb_inplace_add@ */
2139 0, /* @nb_inplace_subtract@ */
2140 0, /* @nb_inplace_multiply@ */
2141 0, /* @nb_inplace_divide@ */
2142 0, /* @nb_inplace_remainder@ */
2143 0, /* @nb_inplace_power@ */
2144 0, /* @nb_inplace_lshift@ */
2145 0, /* @nb_inplace_rshift@ */
2146 0, /* @nb_inplace_and@ */
2147 0, /* @nb_inplace_xor@ */
2148 0, /* @nb_inplace_or@ */
2149
2150 gf_pydiv, /* @nb_floor_divide@ */
2151 0, /* @nb_true_divide@ */
2152 0, /* @nb_inplace_floor_divide@ */
2153 0, /* @nb_inplace_true_divide@ */
2154
2155 mp_pyint, /* @nb_index@ */
2156 };
2157
2158 static const PyTypeObject gf_pytype_skel = {
2159 PyVarObject_HEAD_INIT(0, 0) /* Header */
2160 "GF", /* @tp_name@ */
2161 sizeof(mp_pyobj), /* @tp_basicsize@ */
2162 0, /* @tp_itemsize@ */
2163
2164 mp_pydealloc, /* @tp_dealloc@ */
2165 0, /* @tp_print@ */
2166 0, /* @tp_getattr@ */
2167 0, /* @tp_setattr@ */
2168 0, /* @tp_compare@ */
2169 gf_pyrepr, /* @tp_repr@ */
2170 PYNUMBER(gf), /* @tp_as_number@ */
2171 0, /* @tp_as_sequence@ */
2172 0, /* @tp_as_mapping@ */
2173 mp_pyhash, /* @tp_hash@ */
2174 0, /* @tp_call@ */
2175 mp_pyhex, /* @tp_str@ */
2176 0, /* @tp_getattro@ */
2177 0, /* @tp_setattro@ */
2178 0, /* @tp_as_buffer@ */
2179 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2180 Py_TPFLAGS_CHECKTYPES |
2181 Py_TPFLAGS_BASETYPE,
2182
2183 /* @tp_doc@ */
2184 "Binary polynomials. Support almost all the standard arithmetic\n"
2185 "operations.\n"
2186 "\n"
2187 "Constructor GF(X, [radix = R]) attempts to convert X to a `GF'. If\n"
2188 "X is a string, it's read in radix-R form, or we look for a prefix\n"
2189 "if R = 0. Other acceptable things are field elements, elliptic curve\n"
2190 "points, group elements, Python `int' and `long' objects, and anything\n"
2191 "with an integer conversion.\n"
2192 "\n"
2193 "The name is hopelessly wrong from a technical point of view, but\n"
2194 "but it's much easier to type than `p2' or `c2' or whatever.\n"
2195 "\n"
2196 "Notes:\n"
2197 "\n"
2198 " * Use `//' for Euclidean division: `/' gives exact rational division.",
2199
2200 0, /* @tp_traverse@ */
2201 0, /* @tp_clear@ */
2202 gf_pyrichcompare, /* @tp_richcompare@ */
2203 0, /* @tp_weaklistoffset@ */
2204 0, /* @tp_iter@ */
2205 0, /* @tp_iternext@ */
2206 PYMETHODS(gf), /* @tp_methods@ */
2207 0, /* @tp_members@ */
2208 PYGETSET(gf), /* @tp_getset@ */
2209 0, /* @tp_base@ */
2210 0, /* @tp_dict@ */
2211 0, /* @tp_descr_get@ */
2212 0, /* @tp_descr_set@ */
2213 0, /* @tp_dictoffset@ */
2214 0, /* @tp_init@ */
2215 PyType_GenericAlloc, /* @tp_alloc@ */
2216 gf_pynew, /* @tp_new@ */
2217 0, /* @tp_free@ */
2218 0 /* @tp_is_gc@ */
2219 };
2220
2221 /*----- Sparse poly reduction ---------------------------------------------*/
2222
2223 static PyTypeObject *gfreduce_pytype;
2224
2225 typedef struct gfreduce_pyobj {
2226 PyObject_HEAD
2227 gfreduce mr;
2228 } gfreduce_pyobj;
2229
2230 #define GFREDUCE_PY(o) (&((gfreduce_pyobj *)(o))->mr)
2231
2232 static PyObject *grmeth_exp(PyObject *me, PyObject *arg)
2233 {
2234 PyObject *rc = 0;
2235 mp *yy = 0, *zz = 0;
2236
2237 if (!PyArg_ParseTuple(arg, "O&O&:exp", convgf, &yy, convgf, &zz))
2238 goto end;
2239 if (MP_NEGP(zz)) {
2240 if ((yy = gf_modinv_checked(yy, yy, GFREDUCE_PY(me)->p)) == 0) goto end;
2241 zz = mp_neg(zz, zz);
2242 }
2243 rc = gf_pywrap(gfreduce_exp(GFREDUCE_PY(me), MP_NEW, yy, zz));
2244 end:
2245 if (yy) MP_DROP(yy); if (zz) MP_DROP(zz);
2246 return (rc);
2247 }
2248
2249 static PyObject *grmeth_trace(PyObject *me, PyObject *arg)
2250 {
2251 PyObject *rc = 0;
2252 mp *xx = 0;
2253
2254 if (!PyArg_ParseTuple(arg, "O&:trace", convgf, &xx)) goto end;
2255 rc = PyInt_FromLong(gfreduce_trace(GFREDUCE_PY(me), xx));
2256 end:
2257 if (xx) MP_DROP(xx);
2258 return (rc);
2259 }
2260
2261 static PyObject *grmeth_halftrace(PyObject *me, PyObject *arg)
2262 {
2263 PyObject *rc = 0;
2264 mp *xx = 0;
2265
2266 if (!PyArg_ParseTuple(arg, "O&:halftrace", convgf, &xx)) goto end;
2267 rc = gf_pywrap(gfreduce_halftrace(GFREDUCE_PY(me), MP_NEW, xx));
2268 end:
2269 if (xx) MP_DROP(xx);
2270 return (rc);
2271 }
2272
2273 static PyObject *grmeth_sqrt(PyObject *me, PyObject *arg)
2274 {
2275 PyObject *rc = 0;
2276 mp *xx = 0, *yy;
2277
2278 if (!PyArg_ParseTuple(arg, "O&:sqrt", convgf, &xx)) goto end;
2279 if ((yy = gfreduce_sqrt(GFREDUCE_PY(me), MP_NEW, xx)) == 0)
2280 VALERR("no modular square root");
2281 rc = gf_pywrap(yy);
2282 end:
2283 if (xx) MP_DROP(xx);
2284 return (rc);
2285 }
2286
2287 static PyObject *grmeth_quadsolve(PyObject *me, PyObject *arg)
2288 {
2289 PyObject *rc = 0;
2290 mp *xx = 0, *yy;
2291
2292 if (!PyArg_ParseTuple(arg, "O&:quadsolve", convgf, &xx)) goto end;
2293 if ((yy = gfreduce_quadsolve(GFREDUCE_PY(me), MP_NEW, xx)) == 0)
2294 VALERR("no solution found");
2295 rc = gf_pywrap(yy);
2296 end:
2297 if (xx) MP_DROP(xx);
2298 return (rc);
2299 }
2300
2301 static PyObject *grmeth_reduce(PyObject *me, PyObject *arg)
2302 {
2303 PyObject *z = 0;
2304 mp *yy = 0;
2305
2306 if (!PyArg_ParseTuple(arg, "O&:reduce", convgf, &yy)) goto end;
2307 z = gf_pywrap(gfreduce_do(GFREDUCE_PY(me), MP_NEW, yy));
2308 end:
2309 return (z);
2310 }
2311
2312 static void gfreduce_pydealloc(PyObject *me)
2313 {
2314 gfreduce_destroy(GFREDUCE_PY(me));
2315 FREEOBJ(me);
2316 }
2317
2318 static PyObject *gfreduce_pynew(PyTypeObject *ty,
2319 PyObject *arg, PyObject *kw)
2320 {
2321 gfreduce_pyobj *mr = 0;
2322 gfreduce r;
2323 static const char *const kwlist[] = { "m", 0 };
2324 mp *xx = 0;
2325
2326 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&:new", KWLIST, convgf, &xx))
2327 goto end;
2328 if (MP_ZEROP(xx)) ZDIVERR("modulus is zero!");
2329 gfreduce_create(&r, xx);
2330 mr = (gfreduce_pyobj *)ty->tp_alloc(ty, 0);
2331 mr->mr = r;
2332 end:
2333 if (xx) MP_DROP(xx);
2334 return ((PyObject *)mr);
2335 }
2336
2337 static PyObject *grget_m(PyObject *me, void *hunoz)
2338 { return (gf_pywrap(MP_COPY(GFREDUCE_PY(me)->p))); }
2339
2340 static const PyGetSetDef gfreduce_pygetset[] = {
2341 #define GETSETNAME(op, name) gr##op##_##name
2342 GET (m, "R.m -> reduction polynomial")
2343 #undef GETSETNAME
2344 { 0 }
2345 };
2346
2347 static const PyMethodDef gfreduce_pymethods[] = {
2348 #define METHNAME(name) grmeth_##name
2349 METH (reduce, "R.reduce(X) -> X mod B.m")
2350 METH (trace, "R.trace(X) -> Tr(X) = x + x^2 + ... + x^{2^{m - 1}}")
2351 METH (halftrace, "R.halftrace(X) -> x + x^{2^2} + ... + x^{2^{m - 1}}")
2352 METH (sqrt, "R.sqrt(X) -> Y where Y^2 = X mod R")
2353 METH (quadsolve, "R.quadsolve(X) -> Y where Y^2 + Y = X mod R")
2354 METH (exp, "R.exp(X, N) -> X^N mod B.m")
2355 #undef METHNAME
2356 { 0 }
2357 };
2358
2359 static const PyTypeObject gfreduce_pytype_skel = {
2360 PyVarObject_HEAD_INIT(0, 0) /* Header */
2361 "GFReduce", /* @tp_name@ */
2362 sizeof(gfreduce_pyobj), /* @tp_basicsize@ */
2363 0, /* @tp_itemsize@ */
2364
2365 gfreduce_pydealloc, /* @tp_dealloc@ */
2366 0, /* @tp_print@ */
2367 0, /* @tp_getattr@ */
2368 0, /* @tp_setattr@ */
2369 0, /* @tp_compare@ */
2370 0, /* @tp_repr@ */
2371 0, /* @tp_as_number@ */
2372 0, /* @tp_as_sequence@ */
2373 0, /* @tp_as_mapping@ */
2374 0, /* @tp_hash@ */
2375 0, /* @tp_call@ */
2376 0, /* @tp_str@ */
2377 0, /* @tp_getattro@ */
2378 0, /* @tp_setattro@ */
2379 0, /* @tp_as_buffer@ */
2380 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2381 Py_TPFLAGS_BASETYPE,
2382
2383 /* @tp_doc@ */
2384 "GFReduce(N): a context for reduction modulo sparse polynomials.",
2385
2386 0, /* @tp_traverse@ */
2387 0, /* @tp_clear@ */
2388 0, /* @tp_richcompare@ */
2389 0, /* @tp_weaklistoffset@ */
2390 0, /* @tp_iter@ */
2391 0, /* @tp_iternext@ */
2392 PYMETHODS(gfreduce), /* @tp_methods@ */
2393 0, /* @tp_members@ */
2394 PYGETSET(gfreduce), /* @tp_getset@ */
2395 0, /* @tp_base@ */
2396 0, /* @tp_dict@ */
2397 0, /* @tp_descr_get@ */
2398 0, /* @tp_descr_set@ */
2399 0, /* @tp_dictoffset@ */
2400 0, /* @tp_init@ */
2401 PyType_GenericAlloc, /* @tp_alloc@ */
2402 gfreduce_pynew, /* @tp_new@ */
2403 0, /* @tp_free@ */
2404 0 /* @tp_is_gc@ */
2405 };
2406
2407 /*----- Normal/poly transformation ----------------------------------------*/
2408
2409 static PyTypeObject *gfn_pytype;
2410
2411 typedef struct gfn_pyobj {
2412 PyObject_HEAD
2413 mp *p;
2414 gfn ntop, pton;
2415 } gfn_pyobj;
2416
2417 #define GFN_P(o) (((gfn_pyobj *)(o))->p)
2418 #define GFN_PTON(o) (&((gfn_pyobj *)(o))->pton)
2419 #define GFN_NTOP(o) (&((gfn_pyobj *)(o))->ntop)
2420
2421 static PyObject *gfn_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
2422 {
2423 mp *p = 0, *beta = 0;
2424 gfn_pyobj *gg = 0;
2425 static const char *const kwlist[] = { "p", "beta", 0 };
2426
2427 if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&:new", KWLIST,
2428 convgf, &p, convgf, &beta))
2429 goto end;
2430 gg = PyObject_New(gfn_pyobj, ty);
2431 gg->p = 0;
2432 if (gfn_create(p, beta, &gg->ntop, &gg->pton)) {
2433 Py_DECREF(gg);
2434 gg = 0;
2435 VALERR("can't invert transformation matrix");
2436 }
2437 gg->p = MP_COPY(p);
2438 end:
2439 mp_drop(p);
2440 mp_drop(beta);
2441 return ((PyObject *)gg);
2442 }
2443
2444 static PyObject *gfnget_p(PyObject *me, void *hunoz)
2445 { return (gf_pywrap(MP_COPY(GFN_P(me)))); }
2446
2447 static PyObject *gfnget_beta(PyObject *me, void *hunoz)
2448 {
2449 gfn *n = GFN_NTOP(me);
2450 mp *x = n->r[n->n - 1];
2451 return (gf_pywrap(MP_COPY(x)));
2452 }
2453
2454 #define XFORMOP(name, NAME) \
2455 static PyObject *gfnmeth_##name(PyObject *me, PyObject *arg) \
2456 { \
2457 mp *xx = 0; \
2458 mp *z = 0; \
2459 \
2460 if (!PyArg_ParseTuple(arg, "O&:" #name, convgf, &xx)) goto end; \
2461 z = gfn_transform(GFN_##NAME(me), MP_NEW, xx); \
2462 end: \
2463 mp_drop(xx); \
2464 if (!z) return (0); \
2465 return (gf_pywrap(z)); \
2466 }
2467 XFORMOP(pton, PTON)
2468 XFORMOP(ntop, NTOP)
2469 #undef XFORMOP
2470
2471 static void gfn_pydealloc(PyObject *me)
2472 {
2473 if (GFN_P(me)) {
2474 MP_DROP(GFN_P(me));
2475 gfn_destroy(GFN_PTON(me));
2476 gfn_destroy(GFN_NTOP(me));
2477 }
2478 FREEOBJ(me);
2479 }
2480
2481 static const PyGetSetDef gfn_pygetset[] = {
2482 #define GETSETNAME(op, name) gfn##op##_##name
2483 GET (p, "X.p -> polynomial basis, as polynomial")
2484 GET (beta, "X.beta -> normal basis element, in poly form")
2485 #undef GETSETNAME
2486 { 0 }
2487 };
2488
2489 static const PyMethodDef gfn_pymethods[] = {
2490 #define METHNAME(name) gfnmeth_##name
2491 METH (pton, "X.pton(A) -> normal-basis representation of A")
2492 METH (ntop, "X.ntop(A) -> polynomial-basis representation of A")
2493 #undef METHNAME
2494 { 0 }
2495 };
2496
2497 static const PyTypeObject gfn_pytype_skel = {
2498 PyVarObject_HEAD_INIT(0, 0) /* Header */
2499 "GFN", /* @tp_name@ */
2500 sizeof(gfn_pyobj), /* @tp_basicsize@ */
2501 0, /* @tp_itemsize@ */
2502
2503 gfn_pydealloc, /* @tp_dealloc@ */
2504 0, /* @tp_print@ */
2505 0, /* @tp_getattr@ */
2506 0, /* @tp_setattr@ */
2507 0, /* @tp_compare@ */
2508 0, /* @tp_repr@ */
2509 0, /* @tp_as_number@ */
2510 0, /* @tp_as_sequence@ */
2511 0, /* @tp_as_mapping@ */
2512 0, /* @tp_hash@ */
2513 0, /* @tp_call@ */
2514 0, /* @tp_str@ */
2515 0, /* @tp_getattro@ */
2516 0, /* @tp_setattro@ */
2517 0, /* @tp_as_buffer@ */
2518 Py_TPFLAGS_DEFAULT | /* @tp_flags@ */
2519 Py_TPFLAGS_BASETYPE,
2520
2521 /* @tp_doc@ */
2522 "GFN(P, BETA): an object for transforming elements of binary fields\n"
2523 " between polynomial and normal basis representations.",
2524
2525 0, /* @tp_traverse@ */
2526 0, /* @tp_clear@ */
2527 0, /* @tp_richcompare@ */
2528 0, /* @tp_weaklistoffset@ */
2529 0, /* @tp_iter@ */
2530 0, /* @tp_iternext@ */
2531 PYMETHODS(gfn), /* @tp_methods@ */
2532 0, /* @tp_members@ */
2533 PYGETSET(gfn), /* @tp_getset@ */
2534 0, /* @tp_base@ */
2535 0, /* @tp_dict@ */
2536 0, /* @tp_descr_get@ */
2537 0, /* @tp_descr_set@ */
2538 0, /* @tp_dictoffset@ */
2539 0, /* @tp_init@ */
2540 PyType_GenericAlloc, /* @tp_alloc@ */
2541 gfn_pynew, /* @tp_new@ */
2542 0, /* @tp_free@ */
2543 0 /* @tp_is_gc@ */
2544 };
2545
2546 /*----- Glue --------------------------------------------------------------*/
2547
2548 static const struct nameval consts[] = {
2549 CONST(MPW_MAX),
2550 { 0 }
2551 };
2552
2553 void mp_pyinit(void)
2554 {
2555 INITTYPE(mp, root);
2556 INITTYPE(gf, root);
2557 INITTYPE(mpmul, root);
2558 INITTYPE(mpmont, root);
2559 INITTYPE(mpbarrett, root);
2560 INITTYPE(mpreduce, root);
2561 INITTYPE(mpcrt, root);
2562 INITTYPE(gfreduce, root);
2563 INITTYPE(gfn, root);
2564 }
2565
2566 void mp_pyinsert(PyObject *mod)
2567 {
2568 INSERT("MP", mp_pytype);
2569 INSERT("MPMul", mpmul_pytype);
2570 INSERT("MPMont", mpmont_pytype);
2571 INSERT("MPBarrett", mpbarrett_pytype);
2572 INSERT("MPReduce", mpreduce_pytype);
2573 INSERT("MPCRT", mpcrt_pytype);
2574 INSERT("GF", gf_pytype);
2575 INSERT("GFReduce", gfreduce_pytype);
2576 INSERT("GFN", gfn_pytype);
2577 setconstants(mod, consts);
2578 }
2579
2580 /*----- That's all, folks -------------------------------------------------*/