chiark / gitweb /
*.c: Rearrange and reformat the class methods.
[catacomb-python] / ec.c
1 /* -*-c-*-
2  *
3  * Elliptic curves
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 /*----- Utility functions -------------------------------------------------*/
32
33 PyTypeObject *ecpt_pytype;
34 PyTypeObject *ecptcurve_pytype;
35 PyTypeObject *eccurve_pytype;
36 PyTypeObject *ecprimecurve_pytype;
37 PyTypeObject *ecprimeprojcurve_pytype;
38 PyTypeObject *ecbincurve_pytype;
39 PyTypeObject *ecbinprojcurve_pytype;
40 PyTypeObject *ecinfo_pytype;
41
42 ec_curve *eccurve_copy(ec_curve *c)
43 {
44   field *f;
45   mp *a, *b;
46
47   if ((f = field_copy(c->f)) == 0)
48     return (0);
49   a = F_OUT(f, MP_NEW, c->a);
50   b = F_OUT(f, MP_NEW, c->b);
51   if (STRCMP(EC_NAME(c), ==, "prime"))
52     c = ec_prime(f, a, b);
53   else if (STRCMP(EC_NAME(c), ==, "primeproj"))
54     c = ec_primeproj(f, a, b);
55   else if (STRCMP(EC_NAME(c), ==, "bin"))
56     c = ec_bin(f, a, b);
57   else if (STRCMP(EC_NAME(c), ==, "binproj"))
58     c = ec_binproj(f, a, b);
59   else
60     c = 0;
61   MP_DROP(a);
62   MP_DROP(b);
63   if (!c) F_DESTROY(f);
64   return (c);
65 }
66
67 static PyObject *ecpt_dopywrap(PyObject *cobj, ec_curve *c, ec *p)
68 {
69   ecpt_pyobj *z = PyObject_New(ecpt_pyobj, (PyTypeObject *)cobj);
70   z->p = *p;
71   z->c = c;
72   Py_INCREF(cobj);
73   return ((PyObject *)z);
74 }
75
76 PyObject *ecpt_pywrap(PyObject *cobj, ec *p)
77   { return (ecpt_dopywrap(cobj, ECCURVE_C(cobj), p)); }
78
79 PyObject *ecpt_pywrapout(void *cobj, ec *p)
80 {
81   ec_curve *c;
82
83   if (!PyType_IsSubtype(cobj, ecptcurve_pytype))
84     c = 0;
85   else {
86     c = ECCURVE_C(cobj);
87     EC_IN(ECCURVE_C(cobj), p, p);
88   }
89   return (ecpt_dopywrap(cobj, c, p));
90 }
91
92 int toecpt(ec_curve *c, ec *d, PyObject *p)
93 {
94   if (ECPTCURVE_PYCHECK(p)) {
95     if (ECPT_C(p) != c && !ec_samep(ECPT_C(p), c))
96       return (-1);
97     EC_COPY(d, ECPT_P(p));
98   } else if (ECPT_PYCHECK(p))
99     EC_IN(c, d, ECPT_P(p));
100   else
101     return (-1);
102   return (0);
103 }
104
105 int getecpt(ec_curve *c, ec *d, PyObject *p)
106 {
107   if (toecpt(c, d, p)) {
108     PyErr_Format(PyExc_TypeError, "can't convert %.100s to ecpt",
109                  p->ob_type->tp_name);
110     return (-1);
111   }
112   return (0);
113 }
114
115 void getecptout(ec *d, PyObject *p)
116 {
117   if (ECPTCURVE_PYCHECK(p))
118     EC_OUT(ECPT_C(p), d, ECPT_P(p));
119   else {
120     assert(ECPT_PYCHECK(p));
121     EC_COPY(d, ECPT_P(p));
122   }
123 }
124
125 int convecpt(PyObject *o, void *p)
126 {
127   if (!ECPT_PYCHECK(o))
128     TYERR("want elliptic curve point");
129   getecptout(p, o);
130   return (1);
131 end:
132   return (0);
133 }
134
135 /*----- Curve points ------------------------------------------------------*/
136
137 static int ecbinop(PyObject *x, PyObject *y,
138                    ec_curve **c, PyObject **cobj, ec *xx, ec *yy)
139 {
140   if (ECPTCURVE_PYCHECK(x)) *cobj = ECPT_COBJ(x);
141   else if (ECPTCURVE_PYCHECK(y)) *cobj = ECPT_COBJ(y);
142   else return (-1);
143   *c = ECCURVE_C(*cobj);
144   if (toecpt(*c, xx, x) || toecpt(*c, yy, y)) return (-1);
145   return (0);
146 }
147
148 #define BINOP(name)                                                     \
149   static PyObject *ecpt_py##name(PyObject *x, PyObject *y) {            \
150     ec xx = EC_INIT, yy = EC_INIT, zz = EC_INIT;                        \
151     PyObject *cobj;                                                     \
152     ec_curve *c;                                                        \
153     if (ecbinop(x, y, &c, &cobj, &xx, &yy)) RETURN_NOTIMPL;             \
154     c->ops->name(c, &zz, &xx, &yy);                                     \
155     EC_DESTROY(&xx); EC_DESTROY(&yy);                                   \
156     return (ecpt_pywrap(ECPT_COBJ(x), &zz));                            \
157   }
158 BINOP(add)
159 BINOP(sub)
160 #undef BINOP
161
162 #define UNOP(name)                                                      \
163   static PyObject *ecpt_py##name(PyObject *x) {                         \
164     ec zz = EC_INIT;                                                    \
165     ec_curve *c = ECPT_C(x);                                            \
166     c->ops->name(c, &zz, ECPT_P(x));                                    \
167     return (ecpt_pywrap(ECPT_COBJ(x), &zz));                            \
168   }
169 UNOP(neg)
170 #undef UNOP
171
172 static PyObject *ecpt_pyid(PyObject *x) { RETURN_OBJ(x); }
173
174 static int ecpt_pynonzerop(PyObject *x) { return (!EC_ATINF(ECPT_P(x))); }
175
176 static void ecpt_pydealloc(PyObject *x)
177 {
178   EC_DESTROY(ECPT_P(x));
179   Py_DECREF(ECPT_COBJ(x));
180   FREEOBJ(x);
181 }
182
183 static PyObject *ecpt_pymul(PyObject *x, PyObject *y)
184 {
185   mp *xx;
186   ec zz = EC_INIT;
187
188   if (ECPT_PYCHECK(x)) { PyObject *t; t = x; x = y; y = t; }
189   if (!ECPT_PYCHECK(y) || (xx = tomp(x)) == 0) RETURN_NOTIMPL;
190   ec_imul(ECPT_C(y), &zz, ECPT_P(y), xx);
191   MP_DROP(xx);
192   return (ecpt_pywrap(ECPT_COBJ(y), &zz));
193 }
194
195 static long ecpt_pyhash(PyObject *me)
196 {
197   uint32 h;
198   ec p = EC_INIT;
199
200   getecptout(&p, me);
201   if (EC_ATINF(&p)) h = 0x81d81a94;
202   else h = 0xe0fdd039 ^ (2*mphash(p.x)) ^ (3*mphash(p.y));
203   EC_DESTROY(&p);
204   return (h%LONG_MAX);
205 }
206
207 static PyObject *ecpt_pyrichcompare(PyObject *x, PyObject *y, int op)
208 {
209   ec p = EC_INIT, q = EC_INIT;
210   int b;
211   PyObject *rc = 0;
212
213   if (!ECPT_PYCHECK(y)) RETURN_NOTIMPL;
214   getecptout(&p, x);
215   getecptout(&q, y);
216   switch (op) {
217     case Py_EQ: b = EC_EQ(&p, &q); break;
218     case Py_NE: b = !EC_EQ(&p, &q); break;
219     default: TYERR("elliptic curve points are unordered");
220   }
221   rc = getbool(b);
222 end:
223   EC_DESTROY(&p);
224   EC_DESTROY(&q);
225   return (rc);
226 }
227
228 static PyObject *epmeth_oncurvep(PyObject *me, PyObject *arg)
229 {
230   if (!PyArg_ParseTuple(arg, ":oncurvep")) return (0);
231   return (getbool(EC_ATINF(ECPT_P(me)) ||
232                   !EC_CHECK(ECPT_C(me), ECPT_P(me))));
233 }
234
235 static PyObject *epmeth_dbl(PyObject *me, PyObject *arg)
236 {
237   ec p = EC_INIT;
238   if (!PyArg_ParseTuple(arg, ":dbl")) return (0);
239   EC_DBL(ECPT_C(me), &p, ECPT_P(me));
240   return (ecpt_pywrap(ECPT_COBJ(me), &p));
241 }
242
243 static PyObject *epmeth_tobuf(PyObject *me, PyObject *arg)
244 {
245   buf b;
246   ec p = EC_INIT;
247   PyObject *rc;
248   size_t n;
249
250   if (!PyArg_ParseTuple(arg, ":tobuf")) return (0);
251   getecptout(&p, me);
252   if (EC_ATINF(&p))
253     n = 2;
254   else
255     n = mp_octets(p.x) + mp_octets(p.y) + 6;
256   rc = bytestring_pywrap(0, n);
257   buf_init(&b, PyString_AS_STRING(rc), n);
258   buf_putec(&b, &p);
259   assert(BOK(&b));
260   _PyString_Resize(&rc, BLEN(&b));
261   EC_DESTROY(&p);
262   return (rc);
263 }
264
265 static PyObject *epmeth_toraw(PyObject *me, PyObject *arg)
266 {
267   buf b;
268   PyObject *rc;
269   char *p;
270   ec_curve *c = ECPT_C(me);
271   ec pp = EC_INIT;
272   int len;
273
274   if (!PyArg_ParseTuple(arg, ":toraw")) return (0);
275   len = c->f->noctets * 2 + 1;
276   rc = bytestring_pywrap(0, len);
277   p = PyString_AS_STRING(rc);
278   buf_init(&b, p, len);
279   EC_OUT(c, &pp, ECPT_P(me));
280   ec_putraw(c, &b, &pp);
281   EC_DESTROY(&pp);
282   _PyString_Resize(&rc, BLEN(&b));
283   return (rc);
284 }
285
286 static PyObject *epmeth_ec2osp(PyObject *me, PyObject *arg, PyObject *kw)
287 {
288   buf b;
289   PyObject *rc;
290   char *p;
291   ec_curve *c = ECPT_C(me);
292   ec pp = EC_INIT;
293   unsigned f = EC_EXPLY;
294   int len;
295   static const char *const kwlist[] = { "flags", 0 };
296
297   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&:ec2osp", KWLIST,
298                                    convuint, &f))
299     return (0);
300   len = c->f->noctets * 2 + 1;
301   rc = bytestring_pywrap(0, len);
302   p = PyString_AS_STRING(rc);
303   buf_init(&b, p, len);
304   EC_OUT(c, &pp, ECPT_P(me));
305   if (ec_ec2osp(c, f, &b, &pp)) {
306     Py_DECREF(rc); rc = 0;
307     VALERR("invalid flags");
308   }
309   EC_DESTROY(&pp);
310   _PyString_Resize(&rc, BLEN(&b));
311 end:
312   return (rc);
313 }
314
315 static PyObject *epget_curve(PyObject *me, void *hunoz)
316   { RETURN_OBJ(ECPT_COBJ(me)); }
317
318 static PyObject *meth__ECPt_frombuf(PyObject *me, PyObject *arg)
319 {
320   buf b;
321   char *p;
322   Py_ssize_t sz;
323   PyObject *rc = 0;
324   ec pp = EC_INIT;
325
326   if (!PyArg_ParseTuple(arg, "Os#:frombuf", &me, &p, &sz)) goto end;
327   buf_init(&b, p, sz);
328   if (buf_getec(&b, &pp)) VALERR("malformed data");
329   rc = Py_BuildValue("(NN)", ecpt_pywrapout(me, &pp),
330                      bytestring_pywrapbuf(&b));
331 end:
332   return (rc);
333 }
334
335 static PyObject *meth__ECPt_parse(PyObject *me, PyObject *arg)
336 {
337   char *p;
338   qd_parse qd;
339   PyObject *rc = 0;
340   ec pp = EC_INIT;
341
342   if (!PyArg_ParseTuple(arg, "Os:parse", &me, &p)) goto end;
343   qd.p = p; qd.e = 0;
344   if (!ec_ptparse(&qd, &pp)) VALERR(qd.e);
345   rc = Py_BuildValue("(Ns)", ecpt_pywrapout(me, &pp), qd.p);
346 end:
347   return (rc);
348 }
349
350 static PyObject *meth__ECPtCurve_fromraw(PyObject *me, PyObject *arg)
351 {
352   char *p;
353   Py_ssize_t len;
354   buf b;
355   PyObject *rc = 0;
356   ec_curve *cc;
357   ec pp = EC_INIT;
358
359   if (!PyArg_ParseTuple(arg, "Os#:fromraw", &me, &p, &len))
360     return (0);
361   buf_init(&b, p, len);
362   cc = ECCURVE_C(me);
363   if (ec_getraw(cc, &b, &pp))
364     VALERR("bad point");
365   EC_IN(cc, &pp, &pp);
366   rc = Py_BuildValue("(NN)", ecpt_pywrap(me, &pp), bytestring_pywrapbuf(&b));
367 end:
368   return (rc);
369 }
370
371 static PyObject *meth__ECPtCurve_os2ecp(PyObject *me,
372                                         PyObject *arg, PyObject *kw)
373 {
374   char *p;
375   Py_ssize_t len;
376   buf b;
377   PyObject *rc = 0;
378   ec_curve *cc;
379   unsigned f = EC_XONLY | EC_LSB | EC_SORT | EC_EXPLY;
380   ec pp = EC_INIT;
381   static const char *const kwlist[] = { "class", "buf", "flags", 0 };
382
383   if (!PyArg_ParseTupleAndKeywords(arg, kw, "Os#|O&:os2ecp", KWLIST,
384                                    &me, &p, &len, convuint, &f))
385     return (0);
386   buf_init(&b, p, len);
387   cc = ECCURVE_C(me);
388   if (ec_os2ecp(cc, f, &b, &pp)) VALERR("bad point");
389   EC_IN(cc, &pp, &pp);
390   rc = Py_BuildValue("(NN)", ecpt_pywrap(me, &pp), bytestring_pywrapbuf(&b));
391 end:
392   return (rc);
393 }
394
395 static PyObject *epncget_ix(PyObject *me, void *hunoz)
396 {
397   ec p = EC_INIT;
398   PyObject *rc;
399   if (EC_ATINF(ECPT_P(me))) RETURN_NONE;
400   getecptout(&p, me);
401   rc = mp_pywrap(MP_COPY(p.x));
402   EC_DESTROY(&p);
403   return (rc);
404 }
405
406 static PyObject *epncget_iy(PyObject *me, void *hunoz)
407 {
408   ec p = EC_INIT;
409   PyObject *rc;
410   if (EC_ATINF(ECPT_P(me))) RETURN_NONE;
411   getecptout(&p, me);
412   rc = mp_pywrap(MP_COPY(p.y));
413   EC_DESTROY(&p);
414   return (rc);
415 }
416
417 static PyObject *epncget_point(PyObject *me, void *hunoz)
418   { RETURN_ME; }
419
420 static PyObject *epget_point(PyObject *me, void *hunoz)
421 {
422   ec p = EC_INIT;
423   getecptout(&p, me);
424   return (ecpt_pywrapout(ecpt_pytype, &p));
425 }
426
427 static PyObject *epget_x(PyObject *me, void *hunoz)
428 {
429   ec_curve *c = ECPT_C(me);
430   ec *pp = ECPT_P(me);
431   PyObject *fobj = ECPT_FOBJ(me);
432   ec p = EC_INIT;
433   PyObject *rc;
434
435   if (EC_ATINF(pp)) RETURN_NONE;
436   EC_OUT(c, &p, pp);
437   rc = fe_pywrap(fobj, F_IN(c->f, MP_NEW, p.x));
438   EC_DESTROY(&p);
439   return (rc);
440 }
441
442 static PyObject *epget_y(PyObject *me, void *hunoz)
443 {
444   ec_curve *c = ECPT_C(me);
445   ec *pp = ECPT_P(me);
446   PyObject *fobj = ECPT_FOBJ(me);
447   ec p = EC_INIT;
448   PyObject *rc;
449
450   if (EC_ATINF(pp)) RETURN_NONE;
451   EC_OUT(c, &p, pp);
452   rc = fe_pywrap(fobj, F_IN(c->f, MP_NEW, p.y));
453   EC_DESTROY(&p);
454   return (rc);
455 }
456
457 static PyObject *epget__x(PyObject *me, void *hunoz)
458 {
459   if (EC_ATINF(ECPT_P(me))) RETURN_NONE;
460   return (fe_pywrap(ECPT_FOBJ(me), MP_COPY(ECPT_P(me)->x)));
461 }
462
463 static PyObject *epget__y(PyObject *me, void *hunoz)
464 {
465   if (EC_ATINF(ECPT_P(me))) RETURN_NONE;
466   return (fe_pywrap(ECPT_FOBJ(me), MP_COPY(ECPT_P(me)->y)));
467 }
468
469 static PyObject *epget__z(PyObject *me, void *hunoz)
470 {
471   if (EC_ATINF(ECPT_P(me)) || !ECPT_P(me)->z) RETURN_NONE;
472   return (fe_pywrap(ECPT_FOBJ(me), MP_COPY(ECPT_P(me)->z)));
473 }
474
475 static mp *coord_in(field *f, PyObject *x)
476 {
477   mp *xx;
478   if (FE_PYCHECK(x) && FE_F(x) == f)
479     return (MP_COPY(FE_X(x)));
480   else if ((xx = getmp(x)) == 0)
481     return (0);
482   else
483     return (F_IN(f, xx, xx));
484 }
485
486 static int ecptxl_3(ec_curve *c, ec *p,
487                     PyObject *x, PyObject *y, PyObject *z)
488 {
489   int rc = -1;
490
491   if (!x || !y || !z) TYERR("missing argument");
492   if (!c) VALERR("internal form with no curve!");
493   if ((p->x = coord_in(c->f, x)) == 0 ||
494       (p->y = coord_in(c->f, y)) == 0 ||
495       (z != Py_None && (p->z = coord_in(c->f, z)) == 0))
496     goto end;
497   if (!p->z) p->z = MP_COPY(c->f->one); /* just in case */
498   rc = 0;
499 end:
500   return (rc);
501 }
502
503 static int ecptxl_2(ec_curve *c, ec *p, PyObject *x, PyObject *y)
504 {
505   int rc = -1;
506
507   if (!x || !y) TYERR("missing argument");
508   if ((p->x = getmp(x)) == 0 ||
509       (p->y = getmp(y)) == 0)
510     goto end;
511   if (c) EC_IN(c, p, p);
512   rc = 0;
513 end:
514   return (rc);
515 }
516
517 static int ecptxl_1(ec_curve *c, ec *p, PyObject *x)
518 {
519   int rc = -1;
520   PyObject *y = 0, *z = 0, *t = 0;
521   mp *xx = 0;
522   const void *q;
523   Py_ssize_t n;
524   qd_parse qd;
525
526   Py_XINCREF(x);
527   if (!x || x == Py_None)
528     /*cool*/;
529   else if (ECPT_PYCHECK(x)) {
530     getecptout(p, x);
531     goto fix;
532   } else if (PyString_Check(x)) {
533     if (PyObject_AsReadBuffer(x, &q, &n))
534       goto end;
535     qd.p = q;
536     qd.e = 0;
537     if (!ec_ptparse(&qd, p))
538       VALERR(qd.e);
539     goto fix;
540   } else if (c && (xx = tomp(x)) != 0) {
541     xx = F_IN(c->f, xx, xx);
542     if (!EC_FIND(c, p, xx)) VALERR("not on the curve");
543   } else if (PySequence_Check(x)) {
544     t = x; x = 0;
545     n = PySequence_Size(t); if (n < 0) goto end;
546     if (n != 2 && (n != 3 || !c))
547       TYERR("want sequence of two or three items");
548     if ((x = PySequence_GetItem(t, 0)) == 0 ||
549         (y = PySequence_GetItem(t, 1)) == 0 ||
550         (n == 3 && (z = PySequence_GetItem(t, 2)) == 0))
551       goto end;
552     rc = (n == 2) ? ecptxl_2(c, p, x, y) : ecptxl_3(c, p, x, y, z);
553     goto end;
554   } else
555     TYERR("can't convert to curve point");
556   goto ok;
557
558 fix:
559   if (c) EC_IN(c, p, p);
560 ok:
561   rc = 0;
562 end:
563   Py_XDECREF(x); Py_XDECREF(y); Py_XDECREF(z); Py_XDECREF(t);
564   mp_drop(xx);
565   return (rc);
566 }
567
568 static int ecptxl(ec_curve *c, ec *p, PyObject *x, PyObject *y, PyObject *z)
569 {
570   if (z)
571     return (ecptxl_3(c, p, x, y, z));
572   else if (y)
573     return (ecptxl_2(c, p, x, y));
574   else
575     return (ecptxl_1(c, p, x));
576 }
577
578 static PyObject *ecptnc_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
579 {
580   PyObject *x = 0, *y = 0, *z = 0;
581   ec p = EC_INIT;
582   static const char *const kwlist[] = { "x", "y", 0 };
583
584   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|OO:new", KWLIST, &x, &y) ||
585       ecptxl(0, &p, x, y, z))
586     goto end;
587   return (ecpt_pywrapout(ty, &p));
588 end:
589   mp_drop(p.x); mp_drop(p.y); mp_drop(p.z);
590   return (0);
591 }
592
593 static PyObject *ecpt_pyint(PyObject *me)
594 {
595   ec p = EC_INIT;
596   long l;
597   PyObject *rc = 0;
598   if (EC_ATINF(ECPT_P(me))) VALERR("point at infinity");
599   getecptout(&p, me);
600   if (!mp_tolong_checked(p.x, &l, 0)) rc = PyInt_FromLong(l);
601   else rc = mp_topylong(p.x);
602 end:
603   EC_DESTROY(&p);
604   return (rc);
605 }
606
607 static PyObject *ecpt_pylong(PyObject *me)
608 {
609   ec p = EC_INIT;
610   PyObject *rc = 0;
611   if (EC_ATINF(ECPT_P(me))) VALERR("point at infinity");
612   getecptout(&p, me);
613   rc = mp_topylong(p.x);
614 end:
615   EC_DESTROY(&p);
616   return (rc);
617 }
618
619 static PyObject *ecpt_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
620 {
621   PyObject *x = 0, *y = 0, *z = 0;
622   ec p = EC_INIT;
623   static const char *const kwlist[] = { "x", "y", "z", 0 };
624
625   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|OOO:new", KWLIST,
626                                    &x, &y, &z) ||
627       ecptxl(ECCURVE_C(ty), &p, x, y, z))
628     goto end;
629   return (ecpt_pywrap((PyObject *)ty, &p));
630 end:
631   mp_drop(p.x); mp_drop(p.y); mp_drop(p.z);
632   return (0);
633 }
634
635 static const PyGetSetDef ecptnc_pygetset[] = {
636 #define GETSETNAME(op, name) epnc##op##_##name
637   GET   (ix,            "P.ix -> integer x coordinate of P")
638   GET   (iy,            "P.iy -> integer y coordinate of P")
639   GET   (point,         "P.point -> standalone curve point (no-op)")
640 #undef GETSETNAME
641   { 0 }
642 };
643
644 static const PyMethodDef ecptnc_pymethods[] = {
645 #define METHNAME(func) epmeth_##func
646   METH  (tobuf,         "X.tobuf() -> BIN")
647 #undef METHNAME
648   { 0 }
649 };
650
651 static const PyNumberMethods ecpt_pynumber = {
652   0,                                    /* @nb_add@ */
653   0,                                    /* @nb_subtract@ */
654   0,                                    /* @nb_multiply@ */
655   0,                                    /* @nb_divide@ */
656   0,                                    /* @nb_remainder@ */
657   0,                                    /* @nb_divmod@ */
658   0,                                    /* @nb_power@ */
659   0,                                    /* @nb_negative@ */
660   0,                                    /* @nb_positive@ */
661   0,                                    /* @nb_absolute@ */
662   ecpt_pynonzerop,                      /* @nb_nonzero@ */
663   0,                                    /* @nb_invert@ */
664   0,                                    /* @nb_lshift@ */
665   0,                                    /* @nb_rshift@ */
666   0,                                    /* @nb_and@ */
667   0,                                    /* @nb_xor@ */
668   0,                                    /* @nb_or@ */
669   0,                                    /* @nb_coerce@ */
670   ecpt_pyint,                           /* @nb_int@ */
671   ecpt_pylong,                          /* @nb_long@ */
672   0,                                    /* @nb_float@ */
673   0,                                    /* @nb_oct@ */
674   0,                                    /* @nb_hex@ */
675
676   0,                                    /* @nb_inplace_add@ */
677   0,                                    /* @nb_inplace_subtract@ */
678   0,                                    /* @nb_inplace_multiply@ */
679   0,                                    /* @nb_inplace_divide@ */
680   0,                                    /* @nb_inplace_remainder@ */
681   0,                                    /* @nb_inplace_power@ */
682   0,                                    /* @nb_inplace_lshift@ */
683   0,                                    /* @nb_inplace_rshift@ */
684   0,                                    /* @nb_inplace_and@ */
685   0,                                    /* @nb_inplace_xor@ */
686   0,                                    /* @nb_inplace_or@ */
687
688   0,                                    /* @nb_floor_divide@ */
689   0,                                    /* @nb_true_divide@ */
690   0,                                    /* @nb_inplace_floor_divide@ */
691   0,                                    /* @nb_inplace_true_divide@ */
692 };
693
694 static PyTypeObject ecpt_pytype_skel = {
695   PyObject_HEAD_INIT(0) 0,              /* Header */
696   "ECPt",                               /* @tp_name@ */
697   sizeof(ecpt_pyobj),                   /* @tp_basicsize@ */
698   0,                                    /* @tp_itemsize@ */
699
700   ecpt_pydealloc,                       /* @tp_dealloc@ */
701   0,                                    /* @tp_print@ */
702   0,                                    /* @tp_getattr@ */
703   0,                                    /* @tp_setattr@ */
704   0,                                    /* @tp_compare@ */
705   0,                                    /* @tp_repr@ */
706   PYNUMBER(ecpt),                       /* @tp_as_number@ */
707   0,                                    /* @tp_as_sequence@ */
708   0,                                    /* @tp_as_mapping@ */
709   ecpt_pyhash,                          /* @tp_hash@ */
710   0,                                    /* @tp_call@ */
711   0,                                    /* @tp_str@ */
712   0,                                    /* @tp_getattro@ */
713   0,                                    /* @tp_setattro@ */
714   0,                                    /* @tp_as_buffer@ */
715   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
716     Py_TPFLAGS_CHECKTYPES |
717     Py_TPFLAGS_BASETYPE,
718
719   /* @tp_doc@ */
720   "ECPt([X, [Y]]): elliptic curve points, not associated with any curve.\n"
721   "  X alone may be None, an existing point, a string 'X, Y', an\n"
722   "  x-coordinate, or a pair (X, Y); X and Y should be a coordinate pair.",
723
724   0,                                    /* @tp_traverse@ */
725   0,                                    /* @tp_clear@ */
726   ecpt_pyrichcompare,                   /* @tp_richcompare@ */
727   0,                                    /* @tp_weaklistoffset@ */
728   0,                                    /* @tp_iter@ */
729   0,                                    /* @tp_iternext@ */
730   PYMETHODS(ecptnc),                    /* @tp_methods@ */
731   0,                                    /* @tp_members@ */
732   PYGETSET(ecptnc),                     /* @tp_getset@ */
733   0,                                    /* @tp_base@ */
734   0,                                    /* @tp_dict@ */
735   0,                                    /* @tp_descr_get@ */
736   0,                                    /* @tp_descr_set@ */
737   0,                                    /* @tp_dictoffset@ */
738   0,                                    /* @tp_init@ */
739   PyType_GenericAlloc,                  /* @tp_alloc@ */
740   ecptnc_pynew,                         /* @tp_new@ */
741   0,                                    /* @tp_free@ */
742   0                                     /* @tp_is_gc@ */
743 };
744
745 static const PyGetSetDef ecpt_pygetset[] = {
746 #define GETSETNAME(op, name) ep##op##_##name
747   GET   (curve,         "P.curve -> elliptic curve containing P")
748   GET   (point,         "P.point -> standalone curve point")
749   GET   (x,             "P.x -> Cartesian x coordinate of P")
750   GET   (y,             "P.y -> Cartesian y coordinate of P")
751   GET   (_x,            "P._x -> internal x coordinate of P")
752   GET   (_y,            "P._y -> internal y coordinate of P")
753   GET   (_z,            "P._z -> internal z coordinate of P, or None")
754 #undef GETSETNAME
755   { 0 }
756 };
757
758 static const PyMethodDef ecpt_pymethods[] = {
759 #define METHNAME(func) epmeth_##func
760   METH  (toraw,         "X.toraw() -> BIN")
761   KWMETH(ec2osp,        "X.ec2osp([flags = EC_EXPLY]) -> BIN")
762   METH  (dbl,           "X.dbl() -> X + X")
763   METH  (oncurvep,      "X.oncurvep() -> BOOL")
764 #undef METHNAME
765   { 0 }
766 };
767
768 static const PyNumberMethods ecptcurve_pynumber = {
769   ecpt_pyadd,                           /* @nb_add@ */
770   ecpt_pysub,                           /* @nb_subtract@ */
771   ecpt_pymul,                           /* @nb_multiply@ */
772   0,                                    /* @nb_divide@ */
773   0,                                    /* @nb_remainder@ */
774   0,                                    /* @nb_divmod@ */
775   0,                                    /* @nb_power@ */
776   ecpt_pyneg,                           /* @nb_negative@ */
777   ecpt_pyid,                            /* @nb_positive@ */
778   0,                                    /* @nb_absolute@ */
779   0,                                    /* @nb_nonzero@ */
780   0,                                    /* @nb_invert@ */
781   0,                                    /* @nb_lshift@ */
782   0,                                    /* @nb_rshift@ */
783   0,                                    /* @nb_and@ */
784   0,                                    /* @nb_xor@ */
785   0,                                    /* @nb_or@ */
786   0,                                    /* @nb_coerce@ */
787   0,                                    /* @nb_int@ */
788   0,                                    /* @nb_long@ */
789   0,                                    /* @nb_float@ */
790   0,                                    /* @nb_oct@ */
791   0,                                    /* @nb_hex@ */
792
793   0,                                    /* @nb_inplace_add@ */
794   0,                                    /* @nb_inplace_subtract@ */
795   0,                                    /* @nb_inplace_multiply@ */
796   0,                                    /* @nb_inplace_divide@ */
797   0,                                    /* @nb_inplace_remainder@ */
798   0,                                    /* @nb_inplace_power@ */
799   0,                                    /* @nb_inplace_lshift@ */
800   0,                                    /* @nb_inplace_rshift@ */
801   0,                                    /* @nb_inplace_and@ */
802   0,                                    /* @nb_inplace_xor@ */
803   0,                                    /* @nb_inplace_or@ */
804
805   0,                                    /* @nb_floor_divide@ */
806   0,                                    /* @nb_true_divide@ */
807   0,                                    /* @nb_inplace_floor_divide@ */
808   0,                                    /* @nb_inplace_true_divide@ */
809 };
810
811 static PyTypeObject ecptcurve_pytype_skel = {
812   PyObject_HEAD_INIT(0) 0,              /* Header */
813   "ECPtCurve",                          /* @tp_name@ */
814   sizeof(ecpt_pyobj),                   /* @tp_basicsize@ */
815   0,                                    /* @tp_itemsize@ */
816
817   ecpt_pydealloc,                       /* @tp_dealloc@ */
818   0,                                    /* @tp_print@ */
819   0,                                    /* @tp_getattr@ */
820   0,                                    /* @tp_setattr@ */
821   0,                                    /* @tp_compare@ */
822   0,                                    /* @tp_repr@ */
823   PYNUMBER(ecptcurve),                  /* @tp_as_number@ */
824   0,                                    /* @tp_as_sequence@ */
825   0,                                    /* @tp_as_mapping@ */
826   0,                                    /* @tp_hash@ */
827   0,                                    /* @tp_call@ */
828   0,                                    /* @tp_str@ */
829   0,                                    /* @tp_getattro@ */
830   0,                                    /* @tp_setattro@ */
831   0,                                    /* @tp_as_buffer@ */
832   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
833     Py_TPFLAGS_CHECKTYPES |
834     Py_TPFLAGS_BASETYPE,
835
836   /* @tp_doc@ */
837   "Elliptic curve points; abstract base class for points on given curves.",
838
839   0,                                    /* @tp_traverse@ */
840   0,                                    /* @tp_clear@ */
841   0,                                    /* @tp_richcompare@ */
842   0,                                    /* @tp_weaklistoffset@ */
843   0,                                    /* @tp_iter@ */
844   0,                                    /* @tp_iternext@ */
845   PYMETHODS(ecpt),                      /* @tp_methods@ */
846   0,                                    /* @tp_members@ */
847   PYGETSET(ecpt),                       /* @tp_getset@ */
848   0,                                    /* @tp_base@ */
849   0,                                    /* @tp_dict@ */
850   0,                                    /* @tp_descr_get@ */
851   0,                                    /* @tp_descr_set@ */
852   0,                                    /* @tp_dictoffset@ */
853   0,                                    /* @tp_init@ */
854   PyType_GenericAlloc,                  /* @tp_alloc@ */
855   abstract_pynew,                       /* @tp_new@ */
856   0,                                    /* @tp_free@ */
857   0                                     /* @tp_is_gc@ */
858 };
859
860 /*----- Elliptic curves themselves ----------------------------------------*/
861
862 static PyObject *eccurve_pyrichcompare(PyObject *x, PyObject *y, int op)
863 {
864   int b;
865
866   assert(ECCURVE_PYCHECK(x));
867   if (!ECCURVE_PYCHECK(y)) RETURN_NOTIMPL;
868   b = ec_samep(ECCURVE_C(x), ECCURVE_C(y));
869   switch (op) {
870     case Py_EQ: break;
871     case Py_NE: b = !b; break;
872     default: TYERR("can't order elliptic curves");
873   }
874   return (getbool(b));
875 end:
876   return (0);
877 }
878
879 static PyObject *ecmmul_id(PyObject *me)
880   { ec p = EC_INIT; return (ecpt_pywrap(me, &p)); }
881
882 static int ecmmul_fill(void *pp, PyObject *me, PyObject *x, PyObject *m)
883 {
884   ec_mulfactor *f = pp;
885
886   EC_CREATE(&f->base);
887   if (getecpt(ECCURVE_C(me), &f->base, x) ||
888       (f->exp = getmp(m)) == 0)
889     return (-1);
890   return (0);
891 }
892
893 static PyObject *ecmmul_exp(PyObject *me, void *pp, int n)
894 {
895   ec p = EC_INIT;
896   ec_immul(ECCURVE_C(me), &p, pp, n);
897   return (ecpt_pywrap(me, &p));
898 }
899
900 static void ecmmul_drop(void *pp)
901 {
902   ec_mulfactor *f = pp;
903   EC_DESTROY(&f->base);
904   MP_DROP(f->exp);
905 }
906
907 static PyObject *ecmeth_mmul(PyObject *me, PyObject *arg)
908 {
909   return (mexp_common(me, arg, sizeof(ec_mulfactor),
910                       ecmmul_id, ecmmul_fill, ecmmul_exp, ecmmul_drop));
911 }
912
913 static void eccurve_pydealloc(PyObject *me)
914 {
915   ec_destroycurve(ECCURVE_C(me));
916   Py_DECREF(ECCURVE_FOBJ(me));
917   PyType_Type.tp_dealloc(me);
918 }
919
920 static PyObject *ecmeth_find(PyObject *me, PyObject *arg)
921 {
922   PyObject *x;
923   mp *xx = 0;
924   ec p = EC_INIT;
925   PyObject *rc = 0;
926
927   if (!PyArg_ParseTuple(arg, "O:find", &x)) goto end;
928   if (FIELD_PYCHECK(x) && FE_F(x) == ECCURVE_C(me)->f)
929     xx = MP_COPY(FE_X(x));
930   else if ((xx = getmp(x)) == 0)
931     goto end;
932   else
933     xx = F_IN(ECCURVE_C(me)->f, xx, xx);
934   if (EC_FIND(ECCURVE_C(me), &p, xx) == 0)
935     VALERR("not on the curve");
936   rc = ecpt_pywrap(me, &p);
937 end:
938   if (xx) MP_DROP(xx);
939   return (rc);
940 }
941
942 static PyObject *ecmeth_rand(PyObject *me, PyObject *arg, PyObject *kw)
943 {
944   static const char *const kwlist[] = { "rng", 0 };
945   grand *r = &rand_global;
946   ec p = EC_INIT;
947
948   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&:rand", KWLIST,
949                                    convgrand, &r))
950     return (0);
951   ec_rand(ECCURVE_C(me), &p, r);
952   EC_IN(ECCURVE_C(me), &p, &p);
953   return (ecpt_pywrap(me, &p));
954 }
955
956 static PyObject *meth__ECCurve_parse(PyObject *me, PyObject *arg)
957 {
958   char *p;
959   qd_parse qd;
960   ec_curve *c;
961   PyObject *rc = 0;
962
963   if (!PyArg_ParseTuple(arg, "Os:parse", &me, &p)) goto end;
964   qd.p = p; qd.e = 0;
965   if ((c = ec_curveparse(&qd)) == 0) VALERR(qd.e);
966   rc = eccurve_pywrap(0, c);
967 end:
968   return (rc);
969 }
970
971 static PyObject *eccurve_dopywrap(PyTypeObject *ty,
972                                   PyObject *fobj, ec_curve *c)
973 {
974   eccurve_pyobj *cobj = newtype(ty, 0, c->ops->name);
975   cobj->c = c;
976   cobj->fobj = fobj;
977   cobj->ty.ht_type.tp_basicsize = sizeof(ecpt_pyobj);
978   cobj->ty.ht_type.tp_base = ecptcurve_pytype;
979   Py_INCREF(ecptcurve_pytype);
980   cobj->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
981                                Py_TPFLAGS_BASETYPE |
982                                Py_TPFLAGS_CHECKTYPES |
983                                Py_TPFLAGS_HEAPTYPE);
984   cobj->ty.ht_type.tp_alloc = PyType_GenericAlloc;
985   cobj->ty.ht_type.tp_free = 0;
986   cobj->ty.ht_type.tp_new = ecpt_pynew;
987   typeready(&cobj->ty.ht_type);
988   return ((PyObject *)cobj);
989 }
990
991 PyObject *eccurve_pywrap(PyObject *fobj, ec_curve *c)
992 {
993   PyTypeObject *ty;
994
995   if (!fobj)
996     fobj = field_pywrap(c->f);
997   else
998     Py_INCREF(fobj);
999   assert(FIELD_F(fobj) == c->f);
1000   if (STRCMP(EC_NAME(c), ==, "prime"))
1001     ty = ecprimecurve_pytype;
1002   else if (STRCMP(EC_NAME(c), ==, "primeproj"))
1003     ty = ecprimeprojcurve_pytype;
1004   else if (STRCMP(EC_NAME(c), ==, "bin"))
1005     ty = ecbincurve_pytype;
1006   else if (STRCMP(EC_NAME(c), ==, "binproj"))
1007     ty = ecbinprojcurve_pytype;
1008   else
1009     abort();
1010   return (eccurve_dopywrap(ty, fobj, c));
1011 }
1012
1013 static PyObject *eccurve_pynew(PyTypeObject *ty,
1014                                ec_curve *(*make)(field *, mp *, mp *),
1015                                PyObject *arg, PyObject *kw)
1016 {
1017   PyObject *fobj;
1018   PyObject *cobj = 0;
1019   static const char *const kwlist[] = { "field", "a", "b", 0 };
1020   mp *aa = 0, *bb = 0;
1021
1022   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O!O&O&", KWLIST,
1023                                    field_pytype, &fobj,
1024                                    convmp, &aa, convmp, &bb))
1025     goto end;
1026   Py_INCREF(fobj);
1027   cobj = eccurve_dopywrap(ty, fobj, make(FIELD_F(fobj), aa, bb));
1028 end:
1029   if (aa) MP_DROP(aa);
1030   if (bb) MP_DROP(bb);
1031   return (cobj);
1032 }
1033
1034 static PyObject *ecget_name(PyObject *me, void *hunoz)
1035   { return (PyString_FromString(EC_NAME(ECCURVE_C(me)))); }
1036
1037 static PyObject *ecget_a(PyObject *me, void *hunoz)
1038   { return (fe_pywrap(ECCURVE_FOBJ(me), MP_COPY(ECCURVE_C(me)->a))); }
1039
1040 static PyObject *ecget_b(PyObject *me, void *hunoz)
1041   { return (fe_pywrap(ECCURVE_FOBJ(me), MP_COPY(ECCURVE_C(me)->b))); }
1042
1043 static PyObject *ecget_field(PyObject *me, void *hunoz)
1044   { RETURN_OBJ(ECCURVE_FOBJ(me)); }
1045
1046 static PyObject *ecget_inf(PyObject *me, void *hunoz)
1047   { ec inf = EC_INIT; return (ecpt_pywrap(me, &inf)); }
1048
1049 static const PyGetSetDef eccurve_pygetset[] = {
1050 #define GETSETNAME(op, name) ec##op##_##name
1051   GET   (name,          "E.name -> name of this kind of curve")
1052   GET   (a,             "E.a -> first parameter of curve")
1053   GET   (b,             "E.b -> second parameter of curve")
1054   GET   (field,         "E.field -> finite field containing this curve")
1055   GET   (inf,           "E.inf -> point at infinity of this curve")
1056 #undef GETSETNAME
1057   { 0 }
1058 };
1059
1060 static const PyMethodDef eccurve_pymethods[] = {
1061 #define METHNAME(name) ecmeth_##name
1062   METH  (mmul,     "E.mmul([(P0, N0), (P1, N1), ...]) = N0 P0 + N1 P1 + ...")
1063   METH  (find,          "E.find(X) -> P")
1064   KWMETH(rand,          "E.rand([rng = rand]) -> P")
1065 #undef METHNAME
1066   { 0 }
1067 };
1068
1069 static PyTypeObject eccurve_pytype_skel = {
1070   PyObject_HEAD_INIT(0) 0,              /* Header */
1071   "ECCurve",                            /* @tp_name@ */
1072   sizeof(eccurve_pyobj),                /* @tp_basicsize@ */
1073   0,                                    /* @tp_itemsize@ */
1074
1075   eccurve_pydealloc,                    /* @tp_dealloc@ */
1076   0,                                    /* @tp_print@ */
1077   0,                                    /* @tp_getattr@ */
1078   0,                                    /* @tp_setattr@ */
1079   0,                                    /* @tp_compare@ */
1080   0,                                    /* @tp_repr@ */
1081   0,                                    /* @tp_as_number@ */
1082   0,                                    /* @tp_as_sequence@ */
1083   0,                                    /* @tp_as_mapping@ */
1084   0,                                    /* @tp_hash@ */
1085   0,                                    /* @tp_call@ */
1086   0,                                    /* @tp_str@ */
1087   0,                                    /* @tp_getattro@ */
1088   0,                                    /* @tp_setattro@ */
1089   0,                                    /* @tp_as_buffer@ */
1090   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1091     Py_TPFLAGS_BASETYPE,
1092
1093   /* @tp_doc@ */
1094   "An elliptic curve.  Abstract class.",
1095
1096   0,                                    /* @tp_traverse@ */
1097   0,                                    /* @tp_clear@ */
1098   eccurve_pyrichcompare,                /* @tp_richcompare@ */
1099   0,                                    /* @tp_weaklistoffset@ */
1100   0,                                    /* @tp_iter@ */
1101   0,                                    /* @tp_iternext@ */
1102   PYMETHODS(eccurve),                   /* @tp_methods@ */
1103   0,                                    /* @tp_members@ */
1104   PYGETSET(eccurve),                    /* @tp_getset@ */
1105   0,                                    /* @tp_base@ */
1106   0,                                    /* @tp_dict@ */
1107   0,                                    /* @tp_descr_get@ */
1108   0,                                    /* @tp_descr_set@ */
1109   0,                                    /* @tp_dictoffset@ */
1110   0,                                    /* @tp_init@ */
1111   PyType_GenericAlloc,                  /* @tp_alloc@ */
1112   abstract_pynew,                       /* @tp_new@ */
1113   0,                                    /* @tp_free@ */
1114   0                                     /* @tp_is_gc@ */
1115 };
1116
1117 static PyObject *ecprimecurve_pynew(PyTypeObject *ty,
1118                                     PyObject *arg, PyObject *kw)
1119 {
1120   return (eccurve_pynew(ty, ec_prime, arg, kw));
1121 }
1122
1123 static PyTypeObject ecprimecurve_pytype_skel = {
1124   PyObject_HEAD_INIT(0) 0,              /* Header */
1125   "ECPrimeCurve",                       /* @tp_name@ */
1126   sizeof(eccurve_pyobj),                /* @tp_basicsize@ */
1127   0,                                    /* @tp_itemsize@ */
1128
1129   eccurve_pydealloc,                    /* @tp_dealloc@ */
1130   0,                                    /* @tp_print@ */
1131   0,                                    /* @tp_getattr@ */
1132   0,                                    /* @tp_setattr@ */
1133   0,                                    /* @tp_compare@ */
1134   0,                                    /* @tp_repr@ */
1135   0,                                    /* @tp_as_number@ */
1136   0,                                    /* @tp_as_sequence@ */
1137   0,                                    /* @tp_as_mapping@ */
1138   0,                                    /* @tp_hash@ */
1139   0,                                    /* @tp_call@ */
1140   0,                                    /* @tp_str@ */
1141   0,                                    /* @tp_getattro@ */
1142   0,                                    /* @tp_setattro@ */
1143   0,                                    /* @tp_as_buffer@ */
1144   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1145     Py_TPFLAGS_BASETYPE,
1146
1147   /* @tp_doc@ */
1148   "ECPrimeCurve(FIELD, A, B): an elliptic curve over a prime field.\n"
1149   "  Use ECPrimeProjCurve instead.",
1150
1151   0,                                    /* @tp_traverse@ */
1152   0,                                    /* @tp_clear@ */
1153   eccurve_pyrichcompare,                /* @tp_richcompare@ */
1154   0,                                    /* @tp_weaklistoffset@ */
1155   0,                                    /* @tp_iter@ */
1156   0,                                    /* @tp_iternext@ */
1157   0,                                    /* @tp_methods@ */
1158   0,                                    /* @tp_members@ */
1159   0,                                    /* @tp_getset@ */
1160   0,                                    /* @tp_base@ */
1161   0,                                    /* @tp_dict@ */
1162   0,                                    /* @tp_descr_get@ */
1163   0,                                    /* @tp_descr_set@ */
1164   0,                                    /* @tp_dictoffset@ */
1165   0,                                    /* @tp_init@ */
1166   PyType_GenericAlloc,                  /* @tp_alloc@ */
1167   ecprimecurve_pynew,                   /* @tp_new@ */
1168   0,                                    /* @tp_free@ */
1169   0                                     /* @tp_is_gc@ */
1170 };
1171
1172 static PyObject *ecprimeprojcurve_pynew(PyTypeObject *ty,
1173                                         PyObject *arg, PyObject *kw)
1174 {
1175   return (eccurve_pynew(ty, ec_primeproj, arg, kw));
1176 }
1177
1178 static PyTypeObject ecprimeprojcurve_pytype_skel = {
1179   PyObject_HEAD_INIT(0) 0,              /* Header */
1180   "ECPrimeProjCurve",                   /* @tp_name@ */
1181   sizeof(eccurve_pyobj),                /* @tp_basicsize@ */
1182   0,                                    /* @tp_itemsize@ */
1183
1184   eccurve_pydealloc,                    /* @tp_dealloc@ */
1185   0,                                    /* @tp_print@ */
1186   0,                                    /* @tp_getattr@ */
1187   0,                                    /* @tp_setattr@ */
1188   0,                                    /* @tp_compare@ */
1189   0,                                    /* @tp_repr@ */
1190   0,                                    /* @tp_as_number@ */
1191   0,                                    /* @tp_as_sequence@ */
1192   0,                                    /* @tp_as_mapping@ */
1193   0,                                    /* @tp_hash@ */
1194   0,                                    /* @tp_call@ */
1195   0,                                    /* @tp_str@ */
1196   0,                                    /* @tp_getattro@ */
1197   0,                                    /* @tp_setattro@ */
1198   0,                                    /* @tp_as_buffer@ */
1199   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1200     Py_TPFLAGS_BASETYPE,
1201
1202   /* @tp_doc@ */
1203   "ECPrimeProjCurve(FIELD, A, B): an elliptic curve over a prime field\n"
1204   "  using projective coordinates.",
1205
1206   0,                                    /* @tp_traverse@ */
1207   0,                                    /* @tp_clear@ */
1208   eccurve_pyrichcompare,                /* @tp_richcompare@ */
1209   0,                                    /* @tp_weaklistoffset@ */
1210   0,                                    /* @tp_iter@ */
1211   0,                                    /* @tp_iternext@ */
1212   0,                                    /* @tp_methods@ */
1213   0,                                    /* @tp_members@ */
1214   0,                                    /* @tp_getset@ */
1215   0,                                    /* @tp_base@ */
1216   0,                                    /* @tp_dict@ */
1217   0,                                    /* @tp_descr_get@ */
1218   0,                                    /* @tp_descr_set@ */
1219   0,                                    /* @tp_dictoffset@ */
1220   0,                                    /* @tp_init@ */
1221   PyType_GenericAlloc,                  /* @tp_alloc@ */
1222   ecprimeprojcurve_pynew,               /* @tp_new@ */
1223   0,                                    /* @tp_free@ */
1224   0                                     /* @tp_is_gc@ */
1225 };
1226
1227 static PyObject *ecbincurve_pynew(PyTypeObject *ty,
1228                                   PyObject *arg, PyObject *kw)
1229 {
1230   return (eccurve_pynew(ty, ec_bin, arg, kw));
1231 }
1232
1233 static PyTypeObject ecbincurve_pytype_skel = {
1234   PyObject_HEAD_INIT(0) 0,              /* Header */
1235   "ECBinCurve",                         /* @tp_name@ */
1236   sizeof(eccurve_pyobj),                /* @tp_basicsize@ */
1237   0,                                    /* @tp_itemsize@ */
1238
1239   eccurve_pydealloc,                    /* @tp_dealloc@ */
1240   0,                                    /* @tp_print@ */
1241   0,                                    /* @tp_getattr@ */
1242   0,                                    /* @tp_setattr@ */
1243   0,                                    /* @tp_compare@ */
1244   0,                                    /* @tp_repr@ */
1245   0,                                    /* @tp_as_number@ */
1246   0,                                    /* @tp_as_sequence@ */
1247   0,                                    /* @tp_as_mapping@ */
1248   0,                                    /* @tp_hash@ */
1249   0,                                    /* @tp_call@ */
1250   0,                                    /* @tp_str@ */
1251   0,                                    /* @tp_getattro@ */
1252   0,                                    /* @tp_setattro@ */
1253   0,                                    /* @tp_as_buffer@ */
1254   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1255     Py_TPFLAGS_BASETYPE,
1256
1257   /* @tp_doc@ */
1258   "ECBinCurve(FIELD, A, B): an elliptic curve over a binary field.\n"
1259   "  Use ECBinProjCurve instead.",
1260
1261   0,                                    /* @tp_traverse@ */
1262   0,                                    /* @tp_clear@ */
1263   eccurve_pyrichcompare,                /* @tp_richcompare@ */
1264   0,                                    /* @tp_weaklistoffset@ */
1265   0,                                    /* @tp_iter@ */
1266   0,                                    /* @tp_iternext@ */
1267   0,                                    /* @tp_methods@ */
1268   0,                                    /* @tp_members@ */
1269   0,                                    /* @tp_getset@ */
1270   0,                                    /* @tp_base@ */
1271   0,                                    /* @tp_dict@ */
1272   0,                                    /* @tp_descr_get@ */
1273   0,                                    /* @tp_descr_set@ */
1274   0,                                    /* @tp_dictoffset@ */
1275   0,                                    /* @tp_init@ */
1276   PyType_GenericAlloc,                  /* @tp_alloc@ */
1277   ecbincurve_pynew,                     /* @tp_new@ */
1278   0,                                    /* @tp_free@ */
1279   0                                     /* @tp_is_gc@ */
1280 };
1281
1282 static PyObject *ecbinprojcurve_pynew(PyTypeObject *ty,
1283                                       PyObject *arg, PyObject *kw)
1284 {
1285   return (eccurve_pynew(ty, ec_binproj, arg, kw));
1286 }
1287
1288 static PyTypeObject ecbinprojcurve_pytype_skel = {
1289   PyObject_HEAD_INIT(0) 0,              /* Header */
1290   "ECBinProjCurve",                     /* @tp_name@ */
1291   sizeof(eccurve_pyobj),                /* @tp_basicsize@ */
1292   0,                                    /* @tp_itemsize@ */
1293
1294   eccurve_pydealloc,                    /* @tp_dealloc@ */
1295   0,                                    /* @tp_print@ */
1296   0,                                    /* @tp_getattr@ */
1297   0,                                    /* @tp_setattr@ */
1298   0,                                    /* @tp_compare@ */
1299   0,                                    /* @tp_repr@ */
1300   0,                                    /* @tp_as_number@ */
1301   0,                                    /* @tp_as_sequence@ */
1302   0,                                    /* @tp_as_mapping@ */
1303   0,                                    /* @tp_hash@ */
1304   0,                                    /* @tp_call@ */
1305   0,                                    /* @tp_str@ */
1306   0,                                    /* @tp_getattro@ */
1307   0,                                    /* @tp_setattro@ */
1308   0,                                    /* @tp_as_buffer@ */
1309   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1310     Py_TPFLAGS_BASETYPE,
1311
1312   /* @tp_doc@ */
1313   "ECBinProjCurve(FIELD, A, B): an elliptic curve over a binary field,\n"
1314   "  using projective coordinates.",
1315
1316   0,                                    /* @tp_traverse@ */
1317   0,                                    /* @tp_clear@ */
1318   eccurve_pyrichcompare,                /* @tp_richcompare@ */
1319   0,                                    /* @tp_weaklistoffset@ */
1320   0,                                    /* @tp_iter@ */
1321   0,                                    /* @tp_iternext@ */
1322   0,                                    /* @tp_methods@ */
1323   0,                                    /* @tp_members@ */
1324   0,                                    /* @tp_getset@ */
1325   0,                                    /* @tp_base@ */
1326   0,                                    /* @tp_dict@ */
1327   0,                                    /* @tp_descr_get@ */
1328   0,                                    /* @tp_descr_set@ */
1329   0,                                    /* @tp_dictoffset@ */
1330   0,                                    /* @tp_init@ */
1331   PyType_GenericAlloc,                  /* @tp_alloc@ */
1332   ecbinprojcurve_pynew,                 /* @tp_new@ */
1333   0,                                    /* @tp_free@ */
1334   0                                     /* @tp_is_gc@ */
1335 };
1336
1337 /*----- Curve info --------------------------------------------------------*/
1338
1339 static int ncurves = -1;
1340
1341 void ecinfo_copy(ec_info *eic, const ec_info *ei)
1342 {
1343   eic->c = eccurve_copy(ei->c);
1344   EC_CREATE(&eic->g);
1345   EC_COPY(&eic->g, &ei->g);
1346   eic->r = MP_COPY(ei->r);
1347   eic->h = MP_COPY(ei->h);
1348 }
1349
1350 PyObject *ecinfo_pywrap(ec_info *ei)
1351 {
1352   ecinfo_pyobj *o;
1353
1354   o = PyObject_NEW(ecinfo_pyobj, ecinfo_pytype);
1355   o->ei = *ei;
1356   o->cobj = eccurve_pywrap(0, o->ei.c);
1357   Py_INCREF(o->cobj);
1358   return ((PyObject *)o);
1359 }
1360
1361 static void ecinfo_pydealloc(PyObject *me)
1362 {
1363   ec_info *ei = ECINFO_EI(me);
1364   EC_DESTROY(&ei->g);
1365   MP_DROP(ei->r);
1366   MP_DROP(ei->h);
1367   Py_DECREF(ECINFO_COBJ(me));
1368   FREEOBJ(me);
1369 }
1370
1371 static PyObject *ecinfo_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
1372 {
1373   ec_info ei = { 0 };
1374   PyObject *e, *g;
1375   static const char *const kwlist[] = { "curve", "G", "r", "h", 0 };
1376   ecinfo_pyobj *rc = 0;
1377
1378   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O!O!O&O&:new", KWLIST,
1379                                    eccurve_pytype, &e, ecpt_pytype, &g,
1380                                    convmp, &ei.r, convmp, &ei.h))
1381     goto end;
1382   if (ECPT_C(g) != ECCURVE_C(e) && !ec_samep(ECPT_C(g), ECCURVE_C(e)))
1383     TYERR("point not from this curve");
1384   ei.c = ECCURVE_C(e);
1385   EC_CREATE(&ei.g);
1386   EC_OUT(ei.c, &ei.g, ECPT_P(g));
1387   rc = (ecinfo_pyobj *)ty->tp_alloc(ty, 0);
1388   rc->ei = ei;
1389   rc->cobj = e;
1390   Py_INCREF(rc->cobj);
1391   return ((PyObject *)rc);
1392
1393 end:
1394   mp_drop(ei.r);
1395   mp_drop(ei.h);
1396   return (0);
1397 }
1398
1399 static PyObject *meth__ECInfo_parse(PyObject *me, PyObject *arg)
1400 {
1401   char *p;
1402   qd_parse qd;
1403   ec_info ei;
1404   PyObject *rc = 0;
1405
1406   if (!PyArg_ParseTuple(arg, "Os:parse", &me, &p)) goto end;
1407   qd.p = p; qd.e = 0;
1408   if (ec_infoparse(&qd, &ei)) VALERR(qd.e);
1409   rc = Py_BuildValue("(Ns)", ecinfo_pywrap(&ei), qd.p);
1410 end:
1411   return (rc);
1412 }
1413
1414 static PyObject *meth__ECInfo__curven(PyObject *me, PyObject *arg)
1415 {
1416   int i;
1417   ec_info ei;
1418   PyObject *rc = 0;
1419
1420   if (!PyArg_ParseTuple(arg, "Oi:_curven", &me, &i)) goto end;
1421   if (i < 0 || i >= ncurves) VALERR("curve index out of range");
1422   ec_infofromdata(&ei, ectab[i].data);
1423   rc = ecinfo_pywrap(&ei);
1424 end:
1425   return (rc);
1426 }
1427
1428 static PyObject *ecinfo_pyrichcompare(PyObject *x, PyObject *y, int op)
1429 {
1430   int b = ec_sameinfop(ECINFO_EI(x), ECINFO_EI(y));
1431   switch (op) {
1432     case Py_EQ: break;
1433     case Py_NE: b = !b;
1434     default: TYERR("can't order elliptic curve infos");
1435   }
1436   return (getbool(b));
1437 end:
1438   return (0);
1439 }
1440
1441 static PyObject *eimeth_check(PyObject *me, PyObject *arg, PyObject *kw)
1442 {
1443   static const char *const kwlist[] = { "rng", 0 };
1444   grand *r = &rand_global;
1445   const char *p;
1446
1447   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&:check", KWLIST,
1448                                    convgrand, &r))
1449     goto end;
1450   if ((p = ec_checkinfo(ECINFO_EI(me), r)) != 0)
1451     VALERR(p);
1452   RETURN_ME;
1453 end:
1454   return (0);
1455 }
1456
1457 static PyObject *eiget_curve(PyObject *me, void *hunoz)
1458   { RETURN_OBJ(ECINFO_COBJ(me)); }
1459
1460 static PyObject *eiget_G(PyObject *me, void *hunoz)
1461 {
1462   ec_info *ei = ECINFO_EI(me);
1463   ec p = EC_INIT;
1464   EC_IN(ei->c, &p, &ei->g);
1465   return (ecpt_pywrap(ECINFO_COBJ(me), &p));
1466 }
1467
1468 static PyObject *eiget_r(PyObject *me, void *hunoz)
1469   { return (mp_pywrap(MP_COPY(ECINFO_EI(me)->r))); }
1470
1471 static PyObject *eiget_h(PyObject *me, void *hunoz)
1472   { return (mp_pywrap(MP_COPY(ECINFO_EI(me)->h))); }
1473
1474 static const PyGetSetDef ecinfo_pygetset[] = {
1475 #define GETSETNAME(op, name) ei##op##_##name
1476   GET   (curve,         "I.curve -> the elliptic curve")
1477   GET   (G,             "I.G -> generator point for the group")
1478   GET   (r,             "I.r -> order of the group (and hence of G")
1479   GET   (h,             "I.h -> cofactor of the group")
1480 #undef GETSETNAME
1481   { 0 }
1482 };
1483
1484 static const PyMethodDef ecinfo_pymethods[] = {
1485 #define METHNAME(name) eimeth_##name
1486   KWMETH(check,         "I.check([rng = rand]) -> None")
1487 #undef METHNAME
1488   { 0 }
1489 };
1490
1491 static PyTypeObject ecinfo_pytype_skel = {
1492   PyObject_HEAD_INIT(0) 0,              /* Header */
1493   "ECInfo",                             /* @tp_name@ */
1494   sizeof(ecinfo_pyobj),                 /* @tp_basicsize@ */
1495   0,                                    /* @tp_itemsize@ */
1496
1497   ecinfo_pydealloc,                     /* @tp_dealloc@ */
1498   0,                                    /* @tp_print@ */
1499   0,                                    /* @tp_getattr@ */
1500   0,                                    /* @tp_setattr@ */
1501   0,                                    /* @tp_compare@ */
1502   0,                                    /* @tp_repr@ */
1503   0,                                    /* @tp_as_number@ */
1504   0,                                    /* @tp_as_sequence@ */
1505   0,                                    /* @tp_as_mapping@ */
1506   0,                                    /* @tp_hash@ */
1507   0,                                    /* @tp_call@ */
1508   0,                                    /* @tp_str@ */
1509   0,                                    /* @tp_getattro@ */
1510   0,                                    /* @tp_setattro@ */
1511   0,                                    /* @tp_as_buffer@ */
1512   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1513     Py_TPFLAGS_BASETYPE,
1514
1515   /* @tp_doc@ */
1516   "ECInfo(CURVE, G, R, H): elliptic curve domain parameters.",
1517
1518   0,                                    /* @tp_traverse@ */
1519   0,                                    /* @tp_clear@ */
1520   ecinfo_pyrichcompare,                 /* @tp_richcompare@ */
1521   0,                                    /* @tp_weaklistoffset@ */
1522   0,                                    /* @tp_iter@ */
1523   0,                                    /* @tp_iternext@ */
1524   PYMETHODS(ecinfo),                    /* @tp_methods@ */
1525   0,                                    /* @tp_members@ */
1526   PYGETSET(ecinfo),                     /* @tp_getset@ */
1527   0,                                    /* @tp_base@ */
1528   0,                                    /* @tp_dict@ */
1529   0,                                    /* @tp_descr_get@ */
1530   0,                                    /* @tp_descr_set@ */
1531   0,                                    /* @tp_dictoffset@ */
1532   0,                                    /* @tp_init@ */
1533   PyType_GenericAlloc,                  /* @tp_alloc@ */
1534   ecinfo_pynew,                         /* @tp_new@ */
1535   0,                                    /* @tp_free@ */
1536   0                                     /* @tp_is_gc@ */
1537 };
1538
1539 /*----- Setup -------------------------------------------------------------*/
1540
1541 static const PyMethodDef methods[] = {
1542 #define METHNAME(func) meth_##func
1543   METH  (_ECPt_frombuf, "frombuf(E, STR) -> (P, REST)")
1544   METH  (_ECPtCurve_fromraw, "fromraw(E, STR) -> (P, REST)")
1545   KWMETH(_ECPtCurve_os2ecp, "os2ecp(E, STR, [flags = ...]) -> (P, REST)")
1546   METH  (_ECPt_parse,   "parse(E, STR) -> (P, REST)")
1547   METH  (_ECCurve_parse, "parse(STR) -> (E, REST)")
1548   METH  (_ECInfo_parse, "parse(STR) -> (I, REST)")
1549   METH  (_ECInfo__curven, "_curven(N) -> I")
1550 #undef METHNAME
1551   { 0 }
1552 };
1553
1554 void ec_pyinit(void)
1555 {
1556   INITTYPE(ecpt, root);
1557   INITTYPE(ecptcurve, ecpt);
1558   INITTYPE(eccurve, type);
1559   INITTYPE(ecprimecurve, eccurve);
1560   INITTYPE(ecprimeprojcurve, ecprimecurve);
1561   INITTYPE(ecbincurve, eccurve);
1562   INITTYPE(ecbinprojcurve, ecbincurve);
1563   INITTYPE(ecinfo, root);
1564   addmethods(methods);
1565 }
1566
1567 static PyObject *namedcurves(void)
1568 {
1569   int i, j;
1570   const char *p;
1571   PyObject *d, *c;
1572
1573   d = PyDict_New();
1574   for (i = 0; ectab[i].name; i++) {
1575     p = ectab[i].name;
1576     for (j = 0; j < i; j++) {
1577       if (ectab[i].data == ectab[j].data) {
1578         c = PyDict_GetItemString(d, (/*unconst*/ char *)ectab[j].name);
1579         Py_INCREF(c);
1580         goto found;
1581       }
1582     }
1583     c = PyInt_FromLong(i);
1584   found:
1585     PyDict_SetItemString(d, (/*unconst*/ char *)p, c);
1586     Py_DECREF(c);
1587   }
1588   ncurves = i;
1589   return (d);
1590 }
1591
1592 void ec_pyinsert(PyObject *mod)
1593 {
1594   INSERT("ECPt", ecpt_pytype);
1595   INSERT("ECPtCurve", ecptcurve_pytype);
1596   INSERT("ECCurve", eccurve_pytype);
1597   INSERT("ECPrimeCurve", ecprimecurve_pytype);
1598   INSERT("ECPrimeProjCurve", ecprimeprojcurve_pytype);
1599   INSERT("ECBinCurve", ecbincurve_pytype);
1600   INSERT("ECBinProjCurve", ecbinprojcurve_pytype);
1601   INSERT("ECInfo", ecinfo_pytype);
1602   INSERT("_eccurves", namedcurves());
1603 }
1604
1605 /*----- That's all, folks -------------------------------------------------*/