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