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