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