chiark / gitweb /
catacomb/pwsafe.py: Use `binascii' for Base64 conversion.
[catacomb-python] / group.c
1 /* -*-c-*-
2  *
3  * Abstract group inteface
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 /*----- DH and binary group infos -----------------------------------------*/
32
33 static PyTypeObject *fginfo_pytype, *dhinfo_pytype, *bindhinfo_pytype;
34
35 typedef struct fginfo_pyobj {
36   PyObject_HEAD
37   gprime_param dp;
38 } fginfo_pyobj;
39
40 #define FGINFO_DP(fg) (&((fginfo_pyobj *)(fg))->dp)
41
42 static PyObject *fginfo_pywrap(gprime_param *dp, PyTypeObject *ty)
43 {
44   fginfo_pyobj *z = PyObject_New(fginfo_pyobj, ty);
45   z->dp = *dp;
46   return ((PyObject *)z);
47 }
48
49 static PyObject *fginfo_pynew(PyTypeObject *ty,
50                               PyObject *arg, PyObject *kw)
51 {
52   static const char *const kwlist[] = { "p", "r", "g", 0 };
53   gprime_param dp = { 0 };
54   fginfo_pyobj *z = 0;
55
56   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&O&:new", KWLIST,
57                                    convmp, &dp.p,
58                                    convmp, &dp.q,
59                                    convmp, &dp.g))
60     goto end;
61   z = PyObject_New(fginfo_pyobj, ty);
62   z->dp = dp;
63   return ((PyObject *)z);
64 end:
65   mp_drop(dp.p);
66   mp_drop(dp.q);
67   mp_drop(dp.g);
68   return (0);
69 }
70
71 static PyObject *figet_r(PyObject *me, void *hunoz)
72   { return mp_pywrap(MP_COPY(FGINFO_DP(me)->q)); }
73
74 static PyObject *diget_p(PyObject *me, void *hunoz)
75   { return mp_pywrap(MP_COPY(FGINFO_DP(me)->p)); }
76
77 static PyObject *diget_g(PyObject *me, void *hunoz)
78   { return mp_pywrap(MP_COPY(FGINFO_DP(me)->g)); }
79
80 static PyObject *biget_p(PyObject *me, void *hunoz)
81   { return gf_pywrap(MP_COPY(FGINFO_DP(me)->p)); }
82
83 static PyObject *biget_m(PyObject *me, void *hunoz)
84   { return PyInt_FromLong(mp_octets(FGINFO_DP(me)->p) - 1); }
85
86 static PyObject *biget_g(PyObject *me, void *hunoz)
87   { return gf_pywrap(MP_COPY(FGINFO_DP(me)->g)); }
88
89 static void fginfo_pydealloc(PyObject *me)
90 {
91   mp_drop(FGINFO_DP(me)->p);
92   mp_drop(FGINFO_DP(me)->q);
93   mp_drop(FGINFO_DP(me)->g);
94   FREEOBJ(me);
95 }
96
97 static PyObject *dimeth_generate(PyObject *me, PyObject *arg, PyObject *kw)
98 {
99   dh_param dp;
100   unsigned ql = 0, pl;
101   unsigned steps = 0;
102   grand *r = &rand_global;
103   struct excinfo exc = EXCINFO_INIT;
104   pypgev evt = { { 0 } };
105   static const char *const kwlist[] =
106     { "pbits", "qbits", "event", "rng", "nsteps", 0 };
107   PyObject *rc = 0;
108
109   evt.exc = &exc;
110   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&|O&O&O&O&:generate", KWLIST,
111                                    convuint, &pl, convuint, &ql,
112                                    convpgev, &evt, convgrand, &r,
113                                    convuint, &steps))
114     goto end;
115   if (dh_gen(&dp, ql, pl, steps, r, evt.ev.proc, evt.ev.ctx))
116     PGENERR(&exc);
117   rc = fginfo_pywrap(&dp, dhinfo_pytype);
118 end:
119   droppgev(&evt);
120   return (rc);
121 }
122
123 static PyObject *dimeth_genlimlee(PyObject *me, PyObject *arg, PyObject *kw)
124 {
125   dh_param dp;
126   unsigned ql, pl;
127   unsigned steps = 0;
128   grand *r = &rand_global;
129   struct excinfo exc = EXCINFO_INIT;
130   pypgev oe = { { 0 } }, ie = { { 0 } };
131   int subgroupp = 1;
132   unsigned f = 0;
133   static const char *const kwlist[] = {
134     "pbits", "qbits", "event", "ievent",
135     "rng", "nsteps", "subgroupp", 0
136   };
137   size_t i, nf;
138   mp **v = 0;
139   PyObject *rc = 0, *vec = 0;
140
141   oe.exc = ie.exc = &exc;
142   if (!PyArg_ParseTupleAndKeywords(arg, kw,
143                                    "O&O&|O&O&O&O&O&:genlimlee", KWLIST,
144                                    convuint, &pl, convuint, &ql,
145                                    convpgev, &oe, convpgev, &ie,
146                                    convgrand, &r, convuint, &steps,
147                                    convbool, &subgroupp))
148     goto end;
149   if (subgroupp) f |= DH_SUBGROUP;
150   if (dh_limlee(&dp, ql, pl, f, steps, r,
151                 oe.ev.proc, oe.ev.ctx, ie.ev.proc, ie.ev.ctx, &nf, &v))
152     PGENERR(&exc);
153   vec = PyList_New(nf);
154   for (i = 0; i < nf; i++)
155     PyList_SET_ITEM(vec, i, mp_pywrap(v[i]));
156   xfree(v);
157   rc = Py_BuildValue("(NN)", fginfo_pywrap(&dp, dhinfo_pytype), vec);
158 end:
159   droppgev(&oe); droppgev(&ie);
160   return (rc);
161 }
162
163 static PyObject *dimeth_genkcdsa(PyObject *me, PyObject *arg, PyObject *kw)
164 {
165   dh_param dp;
166   unsigned ql, pl;
167   unsigned steps = 0;
168   grand *r = &rand_global;
169   struct excinfo exc = EXCINFO_INIT;
170   pypgev evt = { { 0 } };
171   static const char *const kwlist[] =
172     { "pbits", "qbits", "event", "rng", "nsteps", 0 };
173   mp *v = MP_NEW;
174   PyObject *rc = 0;
175
176   evt.exc = &exc;
177   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&|O&O&O&:genkcdsa", KWLIST,
178                                    convuint, &pl, convuint, &ql,
179                                    convpgev, &evt, convgrand, &r,
180                                    convuint, &steps))
181     goto end;
182   if (dh_kcdsagen(&dp, ql, pl, 0, steps, r, evt.ev.proc, evt.ev.ctx))
183     PGENERR(&exc);
184   mp_div(&v, 0, dp.p, dp.q);
185   v = mp_lsr(v, v, 1);
186   rc = Py_BuildValue("(NN)", fginfo_pywrap(&dp, dhinfo_pytype),
187                      mp_pywrap(v));
188 end:
189   droppgev(&evt);
190   return (rc);
191 }
192
193 static PyObject *dimeth_gendsa(PyObject *me, PyObject *arg, PyObject *kw)
194 {
195   dsa_param dp;
196   unsigned ql, pl;
197   unsigned steps = 0;
198   dsa_seed ds;
199   struct bin k;
200   struct excinfo exc = EXCINFO_INIT;
201   pypgev evt = { { 0 } };
202   static const char *const kwlist[] =
203     { "pbits", "qbits", "seed", "event", "nsteps", 0 };
204   PyObject *rc = 0;
205
206   evt.exc = &exc;
207   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O&O&O&|O&O&:gendsa", KWLIST,
208                                    convuint, &pl, convuint, &ql,
209                                    convbin, &k,
210                                    convpgev, &evt, convuint, &steps))
211     goto end;
212   if (dsa_gen(&dp, ql, pl, steps, k.p, k.sz, &ds, evt.ev.proc, evt.ev.ctx))
213     PGENERR(&exc);
214   rc = Py_BuildValue("(NNl)", fginfo_pywrap(&dp, dhinfo_pytype),
215                      bytestring_pywrap(ds.p, ds.sz), (long)ds.count);
216   xfree(ds.p);
217 end:
218   droppgev(&evt);
219   return (rc);
220 }
221
222 static PyObject *meth__parse(PyObject *me, PyObject *arg, PyTypeObject *ty,
223                              int (*parse)(qd_parse *, gprime_param *))
224 {
225   qd_parse qd;
226   char *p;
227   gprime_param gp;
228   PyObject *rc = 0;
229
230   if (!PyArg_ParseTuple(arg, "s:parse", &p)) goto end;
231   qd.p = p; qd.e = 0;
232   if (parse(&qd, &gp)) VALERR(qd.e);
233   rc = fginfo_pywrap(&gp, ty);
234 end:
235   return (rc);
236 }
237
238 static PyObject *dimeth_parse(PyObject *me, PyObject *arg)
239   { return (meth__parse(me, arg, dhinfo_pytype, dh_parse)); }
240
241 static PyObject *bimeth_parse(PyObject *me, PyObject *arg)
242   { return (meth__parse(me, arg, bindhinfo_pytype, dhbin_parse)); }
243
244 static const PyGetSetDef fginfo_pygetset[] = {
245 #define GETSETNAME(op, name) fi##op##_##name
246   GET   (r,             "I.r -> group order")
247 #undef GETSETNAME
248   { 0 }
249 };
250
251 static const PyGetSetDef dhinfo_pygetset[] = {
252 #define GETSETNAME(op, name) di##op##_##name
253   GET   (p,             "I.p -> prime")
254   GET   (g,             "I.g -> generator")
255 #undef GETSETNAME
256   { 0 }
257 };
258
259 static const PyMethodDef dhinfo_pymethods[] = {
260 #define METHNAME(name) dimeth_##name
261   SMTH  (parse,         "parse(STR) -> D, REST")
262   KWSMTH(generate,
263        "generate(PBITS, [qbits = 0], [event = pgen_nullev],\n"
264        "         [rng = rand], [nsteps = 0]) -> D")
265   KWSMTH(genlimlee,
266        "genlimlee(PBITS, QBITS, [event = pgen_nullev], "
267                                                   "[ievent = pgen_nullev],\n"
268        "          [rng = rand], [nsteps = 0], [subgroupp = True]) "
269                                                           "-> (D, [Q, ...])")
270   KWSMTH(gendsa,
271        "gendsa(PBITS, QBITS, SEED, [event = pgen_nullev], [nsteps = 0])\n"
272        "  -> (D, SEED, COUNT)")
273   KWSMTH(genkcdsa,
274        "gendsa(PBITS, QBITS, [event = pgen_nullev], "
275                                               "[rng = rand], [nsteps = 0])\n"
276        "  -> (D, V)")
277 #undef METHNAME
278   { 0 }
279 };
280
281 static const PyGetSetDef bindhinfo_pygetset[] = {
282 #define GETSETNAME(op, name) bi##op##_##name
283   GET   (p,             "I.p -> irreducible polynomial")
284   GET   (m,             "I.m -> degree of polynomial")
285   GET   (g,             "I.g -> generator")
286 #undef GETSETNAME
287   { 0 }
288 };
289
290 static const PyMethodDef bindhinfo_pymethods[] = {
291 #define METHNAME(name) bimeth_##name
292   SMTH  (parse,         "parse(STR) -> D, REST")
293 #undef METHNAME
294   { 0 }
295 };
296
297 static const PyTypeObject fginfo_pytype_skel = {
298   PyVarObject_HEAD_INIT(0, 0)           /* Header */
299   "FGInfo",                             /* @tp_name@ */
300   sizeof(fginfo_pyobj),                 /* @tp_basicsize@ */
301   0,                                    /* @tp_itemsize@ */
302
303   fginfo_pydealloc,                     /* @tp_dealloc@ */
304   0,                                    /* @tp_print@ */
305   0,                                    /* @tp_getattr@ */
306   0,                                    /* @tp_setattr@ */
307   0,                                    /* @tp_compare@ */
308   0,                                    /* @tp_repr@ */
309   0,                                    /* @tp_as_number@ */
310   0,                                    /* @tp_as_sequence@ */
311   0,                                    /* @tp_as_mapping@ */
312   0,                                    /* @tp_hash@ */
313   0,                                    /* @tp_call@ */
314   0,                                    /* @tp_str@ */
315   0,                                    /* @tp_getattro@ */
316   0,                                    /* @tp_setattro@ */
317   0,                                    /* @tp_as_buffer@ */
318   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
319     Py_TPFLAGS_BASETYPE,
320
321   /* @tp_doc@ */
322   "Abstract base class for field-group information objects.",
323
324   0,                                    /* @tp_traverse@ */
325   0,                                    /* @tp_clear@ */
326   0,                                    /* @tp_richcompare@ */
327   0,                                    /* @tp_weaklistoffset@ */
328   0,                                    /* @tp_iter@ */
329   0,                                    /* @tp_iternext@ */
330   0,                                    /* @tp_methods@ */
331   0,                                    /* @tp_members@ */
332   PYGETSET(fginfo),                     /* @tp_getset@ */
333   0,                                    /* @tp_base@ */
334   0,                                    /* @tp_dict@ */
335   0,                                    /* @tp_descr_get@ */
336   0,                                    /* @tp_descr_set@ */
337   0,                                    /* @tp_dictoffset@ */
338   0,                                    /* @tp_init@ */
339   PyType_GenericAlloc,                  /* @tp_alloc@ */
340   abstract_pynew,                       /* @tp_new@ */
341   0,                                    /* @tp_free@ */
342   0                                     /* @tp_is_gc@ */
343 };
344
345 static const PyTypeObject dhinfo_pytype_skel = {
346   PyVarObject_HEAD_INIT(0, 0)           /* Header */
347   "DHInfo",                             /* @tp_name@ */
348   sizeof(fginfo_pyobj),                 /* @tp_basicsize@ */
349   0,                                    /* @tp_itemsize@ */
350
351   fginfo_pydealloc,                     /* @tp_dealloc@ */
352   0,                                    /* @tp_print@ */
353   0,                                    /* @tp_getattr@ */
354   0,                                    /* @tp_setattr@ */
355   0,                                    /* @tp_compare@ */
356   0,                                    /* @tp_repr@ */
357   0,                                    /* @tp_as_number@ */
358   0,                                    /* @tp_as_sequence@ */
359   0,                                    /* @tp_as_mapping@ */
360   0,                                    /* @tp_hash@ */
361   0,                                    /* @tp_call@ */
362   0,                                    /* @tp_str@ */
363   0,                                    /* @tp_getattro@ */
364   0,                                    /* @tp_setattro@ */
365   0,                                    /* @tp_as_buffer@ */
366   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
367     Py_TPFLAGS_BASETYPE,
368
369   /* @tp_doc@ */
370   "DHInfo(P, R, G): standard (integer) Diffie-Hellman group information.",
371
372   0,                                    /* @tp_traverse@ */
373   0,                                    /* @tp_clear@ */
374   0,                                    /* @tp_richcompare@ */
375   0,                                    /* @tp_weaklistoffset@ */
376   0,                                    /* @tp_iter@ */
377   0,                                    /* @tp_iternext@ */
378   PYMETHODS(dhinfo),                    /* @tp_methods@ */
379   0,                                    /* @tp_members@ */
380   PYGETSET(dhinfo),                     /* @tp_getset@ */
381   0,                                    /* @tp_base@ */
382   0,                                    /* @tp_dict@ */
383   0,                                    /* @tp_descr_get@ */
384   0,                                    /* @tp_descr_set@ */
385   0,                                    /* @tp_dictoffset@ */
386   0,                                    /* @tp_init@ */
387   PyType_GenericAlloc,                  /* @tp_alloc@ */
388   fginfo_pynew,                         /* @tp_new@ */
389   0,                                    /* @tp_free@ */
390   0                                     /* @tp_is_gc@ */
391 };
392
393 static const PyTypeObject bindhinfo_pytype_skel = {
394   PyVarObject_HEAD_INIT(0, 0)           /* Header */
395   "BinDHInfo",                          /* @tp_name@ */
396   sizeof(fginfo_pyobj),                 /* @tp_basicsize@ */
397   0,                                    /* @tp_itemsize@ */
398
399   fginfo_pydealloc,                     /* @tp_dealloc@ */
400   0,                                    /* @tp_print@ */
401   0,                                    /* @tp_getattr@ */
402   0,                                    /* @tp_setattr@ */
403   0,                                    /* @tp_compare@ */
404   0,                                    /* @tp_repr@ */
405   0,                                    /* @tp_as_number@ */
406   0,                                    /* @tp_as_sequence@ */
407   0,                                    /* @tp_as_mapping@ */
408   0,                                    /* @tp_hash@ */
409   0,                                    /* @tp_call@ */
410   0,                                    /* @tp_str@ */
411   0,                                    /* @tp_getattro@ */
412   0,                                    /* @tp_setattro@ */
413   0,                                    /* @tp_as_buffer@ */
414   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
415     Py_TPFLAGS_BASETYPE,
416
417   /* @tp_doc@ */
418   "BinDHInfo(P, R, G): binary-field Diffie-Hellman group information.",
419
420   0,                                    /* @tp_traverse@ */
421   0,                                    /* @tp_clear@ */
422   0,                                    /* @tp_richcompare@ */
423   0,                                    /* @tp_weaklistoffset@ */
424   0,                                    /* @tp_iter@ */
425   0,                                    /* @tp_iternext@ */
426   PYMETHODS(bindhinfo),                 /* @tp_methods@ */
427   0,                                    /* @tp_members@ */
428   PYGETSET(bindhinfo),                  /* @tp_getset@ */
429   0,                                    /* @tp_base@ */
430   0,                                    /* @tp_dict@ */
431   0,                                    /* @tp_descr_get@ */
432   0,                                    /* @tp_descr_set@ */
433   0,                                    /* @tp_dictoffset@ */
434   0,                                    /* @tp_init@ */
435   PyType_GenericAlloc,                  /* @tp_alloc@ */
436   fginfo_pynew,                         /* @tp_new@ */
437   0,                                    /* @tp_free@ */
438   0                                     /* @tp_is_gc@ */
439 };
440
441 /*----- General utilities -------------------------------------------------*/
442
443 PyTypeObject *ge_pytype, *group_pytype;
444 static PyTypeObject *primegroup_pytype, *bingroup_pytype, *ecgroup_pytype;
445
446 group *group_copy(group *g)
447 {
448   if (STRCMP(G_NAME(g), ==, "prime")) {
449     gctx_prime *gc = (gctx_prime *)g;
450     gprime_param gp;
451     gp.g = G_TOINT(g, MP_NEW, g->g);
452     gp.p = gc->mm.m;
453     gp.q = gc->g.r;
454     g = group_prime(&gp);
455     MP_DROP(gp.g);
456   } else if (STRCMP(G_NAME(g), ==, "bin")) {
457     gctx_bin *gc = (gctx_bin *)g;
458     gbin_param gb;
459     gb.g = G_TOINT(g, MP_NEW, g->g);
460     gb.p = gc->r.p;
461     gb.q = gc->g.r;
462     g = group_binary(&gb);
463     MP_DROP(gb.g);
464   } else if (STRCMP(G_NAME(g), ==, "ec")) {
465     gctx_ec *gc = (gctx_ec *)g;
466     ec_info ei;
467     if ((ei.c = eccurve_copy(gc->ei.c)) == 0)
468       return (0);
469     EC_CREATE(&ei.g);
470     EC_COPY(&ei.g, &gc->ei.g);
471     ei.r = MP_COPY(gc->ei.r);
472     ei.h = MP_COPY(gc->ei.h);
473     g = group_ec(&ei);
474   } else
475     g = 0;
476   return (g);
477 }
478
479 PyObject *ge_pywrap(PyObject *gobj, ge *x)
480 {
481   ge_pyobj *z = PyObject_New(ge_pyobj, (PyTypeObject *)gobj);
482   z->x = x;
483   z->g = GROUP_G(gobj);
484   Py_INCREF(gobj);
485   return ((PyObject *)z);
486 }
487
488 static PyObject *ge_pynew(PyTypeObject *ty, PyObject *arg, PyObject *kw)
489 {
490   static const char *const kwlist[] = { "x", 0 };
491   PyObject *x;
492   group *g;
493   ec p = EC_INIT;
494   mp *y = 0;
495   ge *xx = 0;
496   size_t n;
497   mptext_stringctx sc;
498
499   g = GROUP_G(ty);
500   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O:new", KWLIST, &x)) goto end;
501   xx = G_CREATE(g);
502   if (ECPT_PYCHECK(x)) {
503     getecptout(&p, x);
504     if (G_FROMEC(g, xx, &p))
505       TYERR("can't convert from elliptic curve point");
506     EC_DESTROY(&p);
507   } else if ((y = tomp(x)) != 0) {
508     if (G_FROMINT(g, xx, y))
509       TYERR("can't convert from integer");
510     MP_DROP(y);
511   } else if (TEXT_CHECK(x)) {
512     TEXT_PTRLEN(x, sc.buf, n); sc.lim = sc.buf + n;
513     if (G_READ(g, xx, &mptext_stringops, &sc) || sc.buf < sc.lim)
514       VALERR("malformed group element string");
515   } else
516     TYERR("can't convert to group element");
517   return (ge_pywrap((PyObject *)ty, xx));
518 end:
519   mp_drop(y);
520   EC_DESTROY(&p);
521   if (xx) G_DESTROY(g, xx);
522   return (0);
523 }
524
525 static PyObject *group_dopywrap(PyTypeObject *ty, group *g)
526 {
527   group_pyobj *gobj = newtype(ty, 0, g->ops->name);
528   gobj->g = g;
529   gobj->ty.ht_type.tp_basicsize = sizeof(ge_pyobj);
530   gobj->ty.ht_type.tp_base = ge_pytype;
531   Py_INCREF(group_pytype);
532   gobj->ty.ht_type.tp_flags = (Py_TPFLAGS_DEFAULT |
533                                Py_TPFLAGS_BASETYPE |
534                                Py_TPFLAGS_CHECKTYPES |
535                                Py_TPFLAGS_HEAPTYPE);
536   gobj->ty.ht_type.tp_alloc = PyType_GenericAlloc;
537   gobj->ty.ht_type.tp_free = 0;
538   gobj->ty.ht_type.tp_new = ge_pynew;
539   typeready(&gobj->ty.ht_type);
540   return ((PyObject *)gobj);
541 }
542
543 PyObject *group_pywrap(group *g)
544 {
545   PyTypeObject *ty;
546
547   if (STRCMP(G_NAME(g), ==, "prime")) ty = primegroup_pytype;
548   else if (STRCMP(G_NAME(g), ==, "bin")) ty = bingroup_pytype;
549   else if (STRCMP(G_NAME(g), ==, "ec")) ty = ecgroup_pytype;
550   else abort();
551   return (group_dopywrap(ty, g));
552 }
553
554 /*----- Group elements ----------------------------------------------------*/
555
556 #define BINOP(name)                                                     \
557   static PyObject *ge_py##name(PyObject *x, PyObject *y)                \
558   {                                                                     \
559     ge *z;                                                              \
560     group *g;                                                           \
561     if (!GE_PYCHECK(x) || !GE_PYCHECK(y) ||                             \
562         (GE_G(x) != GE_G(y) && !group_samep(GE_G(x), GE_G(y))))         \
563       RETURN_NOTIMPL;                                                   \
564     g = GE_G(x);                                                        \
565     z = G_CREATE(g);                                                    \
566     g->ops->name(g, z, GE_X(x), GE_X(y));                               \
567     return (ge_pywrap(GE_GOBJ(x), z));                                  \
568   }
569 BINOP(mul)
570 BINOP(div)
571 #undef BINOP
572
573 #define UNOP(name)                                                      \
574   static PyObject *gemeth_##name(PyObject *me)                          \
575   {                                                                     \
576     group *g;                                                           \
577     ge *z;                                                              \
578     g = GE_G(me);                                                       \
579     z = G_CREATE(g);                                                    \
580     g->ops->name(g, z, GE_X(me));                                       \
581     return (ge_pywrap(GE_GOBJ(me), z));                                 \
582   }
583 UNOP(sqr)
584 UNOP(inv)
585 #undef UNOP
586
587 static PyObject *ge_pyexp(PyObject *x, PyObject *n, PyObject *m)
588 {
589   mp *nn;
590   ge *z;
591
592   if (m != Py_None || !GE_PYCHECK(x) || (nn = getmp(n)) == 0)
593     RETURN_NOTIMPL;
594   z = G_CREATE(GE_G(x));
595   G_EXP(GE_G(x), z, GE_X(x), nn);
596   MP_DROP(nn);
597   return (ge_pywrap(GE_GOBJ(x), z));
598 }
599
600 static void ge_pydealloc(PyObject *me)
601 {
602   G_DESTROY(GE_G(me), GE_X(me));
603   Py_DECREF(GE_GOBJ(me));
604   FREEOBJ(me);
605 }
606
607 static void group_pydealloc(PyObject *me)
608 {
609   G_DESTROYGROUP(GROUP_G(me));
610   PyType_Type.tp_dealloc(me);
611 }
612
613 static PyObject *gmexp_id(PyObject *me)
614 {
615   group *g = GROUP_G(me); ge *x = G_CREATE(g);
616   G_COPY(g, x, g->i); return (ge_pywrap(me, x));
617 }
618
619 static int gmexp_fill(void *pp, PyObject  *me, PyObject *x, PyObject *m)
620 {
621   group_expfactor *f = pp;
622
623   if (!GE_PYCHECK(x) || GE_G(x) != GROUP_G(me) || (f->exp = getmp(m)) == 0)
624     return (-1);
625   f->base = GE_X(x);
626   return (0);
627 }
628
629 static PyObject *ge_pyrichcompare(PyObject *x, PyObject *y, int op)
630 {
631   int b;
632   PyObject *rc = 0;
633
634   if (!GE_PYCHECK(x) || !GE_PYCHECK(y) ||
635       (GE_G(x) != GE_G(y) && !group_samep(GE_G(x), GE_G(y))))
636     RETURN_NOTIMPL;
637   switch (op) {
638     case Py_EQ: b = G_EQ(GE_G(x), GE_X(x), GE_X(y)); break;
639     case Py_NE: b = !G_EQ(GE_G(x), GE_X(x), GE_X(y)); break;
640     default: TYERR("group elements are unordered");
641   }
642   rc = getbool(b);
643 end:
644   return (rc);
645 }
646
647 static PyObject *gemeth_check(PyObject *me)
648 {
649   if (group_check(GE_G(me), GE_X(me))) VALERR("bad group element");
650   RETURN_OBJ(me);
651 end:
652   return (0);
653 }
654
655 static int ge_pynonzerop(PyObject *x)
656   { return (!G_IDENTP(GE_G(x), GE_X(x))); }
657
658 static PyObject *ge_pystr(PyObject *me)
659 {
660   dstr d = DSTR_INIT;
661   PyObject *rc;
662
663   group_writedstr(GE_G(me), GE_X(me), &d);
664   rc = TEXT_FROMSTRLEN(d.buf, d.len);
665   DDESTROY(&d);
666   return (rc);
667 }
668
669 static PyObject *ge_pylong(PyObject *me)
670 {
671   mp *x = 0;
672   PyObject *rc = 0;
673
674   if ((x = G_TOINT(GE_G(me), MP_NEW, GE_X(me))) == 0)
675     TYERR("can't convert to integer");
676   rc = mp_topylong(x);
677 end:
678   mp_drop(x);
679   return (rc);
680 }
681
682 static PyObject *ge_pyint(PyObject *me)
683 {
684   mp *x = 0;
685   PyObject *rc = 0;
686   long l;
687
688   if ((x = G_TOINT(GE_G(me), MP_NEW, GE_X(me))) == 0)
689     TYERR("can't convert to integer");
690   if (!mp_tolong_checked(x, &l, 0)) rc = PyInt_FromLong(l);
691   else rc = mp_topylong(x);
692 end:
693   mp_drop(x);
694   return (rc);
695 }
696
697 static PyObject *gemeth_toint(PyObject *me)
698 {
699   mp *x;
700
701   if ((x = G_TOINT(GE_G(me), MP_NEW, GE_X(me))) == 0)
702     TYERR("can't convert to integer");
703   return (mp_pywrap(x));
704 end:
705   return (0);
706 }
707
708 static PyObject *gemeth_toec(PyObject *me, PyObject *arg, PyObject *kw)
709 {
710   static const char *const kwlist[] = { "curve", 0 };
711   PyTypeObject *cty = 0;
712   PyObject *rc = 0;
713   group *g;
714   ec_curve *c;
715   ec p = EC_INIT;
716
717   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O:toec", KWLIST,
718                                    &cty)) goto end;
719   g = GROUP_G(GE_GOBJ(me));
720   if (cty) {
721     if (!PyType_Check(cty) || !PyType_IsSubtype(cty, ecpt_pytype))
722       TYERR("want subtype of catacomb.ECPt");
723     Py_INCREF((PyObject *)cty);
724   } else if (STRCMP(G_NAME(g), ==, "ec")) {
725     c = eccurve_copy(((gctx_ec *)g)->ei.c);
726     cty = (PyTypeObject *)eccurve_pywrap(0, c);
727   } else  {
728     cty = ecpt_pytype;
729     Py_INCREF((PyObject *)cty);
730   }
731   if (G_TOEC(GE_G(me), &p, GE_X(me))) {
732     Py_DECREF((PyObject *)cty);
733     TYERR("can't convert to ec point");
734   }
735   rc = ecpt_pywrapout(cty, &p);
736   Py_DECREF((PyObject *)cty);
737 end:
738   return (rc);
739 }
740
741 static PyObject *gemeth_tobuf(PyObject *me)
742 {
743   buf b;
744   PyObject *rc;
745   size_t n;
746
747   n = GE_G(me)->noctets + 4;
748   rc = bytestring_pywrap(0, n);
749   buf_init(&b, BIN_PTR(rc), n);
750   G_TOBUF(GE_G(me), &b, GE_X(me));
751   assert(BOK(&b));
752   BIN_SETLEN(rc, BLEN(&b));
753   return (rc);
754 }
755
756 static PyObject *gemeth_toraw(PyObject *me)
757 {
758   buf b;
759   PyObject *rc;
760   size_t n;
761
762   n = GE_G(me)->noctets;
763   rc = bytestring_pywrap(0, n);
764   buf_init(&b, BIN_PTR(rc), n);
765   G_TORAW(GE_G(me), &b, GE_X(me));
766   assert(BOK(&b));
767   BIN_SETLEN(rc, BLEN(&b));
768   return (rc);
769 }
770
771 static PyObject *gmexp_exp(PyObject *me, void *pp, int n)
772 {
773   ge *z = G_CREATE(GROUP_G(me));
774   G_MEXP(GROUP_G(me), z, pp, n);
775   return (ge_pywrap(me, z));
776 }
777
778 static void gmexp_drop(void *pp)
779 {
780   group_expfactor *f = pp;
781   MP_DROP(f->exp);
782 }
783
784 static PyObject *gmeth_mexp(PyObject *me, PyObject *arg)
785 {
786   return (mexp_common(me, arg, sizeof(group_expfactor),
787                       gmexp_id, gmexp_fill, gmexp_exp, gmexp_drop));
788 }
789
790 static PyObject *gmeth_checkgroup(PyObject *me, PyObject *arg, PyObject *kw)
791 {
792   static const char *const kwlist[] = { "rng", 0 };
793   grand *r = &rand_global;
794   const char *p;
795
796   if (!PyArg_ParseTupleAndKeywords(arg, kw, "|O&:checkgroup", KWLIST,
797                                    convgrand, &r))
798     goto end;
799   if ((p = G_CHECK(GROUP_G(me), r)) != 0)
800     VALERR(p);
801   RETURN_OBJ(me);
802 end:
803   return (0);
804 }
805
806 static PyObject *group_pyrichcompare(PyObject *x, PyObject *y, int op)
807 {
808   int b = group_samep(GROUP_G(x), GROUP_G(y));
809   switch (op) {
810     case Py_EQ: break;
811     case Py_NE: b = !b;
812     default: TYERR("can't order groups");
813   }
814   return (getbool(b));
815 end:
816   return (0);
817 }
818
819 static PyObject *gemeth_frombuf(PyObject *me, PyObject *arg)
820 {
821   buf b;
822   struct bin in;
823   group *g;
824   ge *x = 0;
825
826   if (!PyArg_ParseTuple(arg, "O&:frombuf", convbin, &in)) return (0);
827   g = GROUP_G(me);
828   buf_init(&b, (/*unconst*/ void *)in.p, in.sz);
829   x = G_CREATE(g);
830   if (G_FROMBUF(g, &b, x)) VALERR("invalid data");
831   return (Py_BuildValue("(NN)", ge_pywrap(me, x), bytestring_pywrapbuf(&b)));
832 end:
833   if (x) G_DESTROY(g, x);
834   return (0);
835 }
836
837 static PyObject *gemeth_fromraw(PyObject *me, PyObject *arg)
838 {
839   buf b;
840   struct bin in;
841   group *g;
842   ge *x = 0;
843
844   if (!PyArg_ParseTuple(arg, "O&:fromraw", convbin, &in)) return (0);
845   g = GROUP_G(me);
846   buf_init(&b, (/*unconst*/ void *)in.p, in.sz);
847   x = G_CREATE(g);
848   if (G_FROMRAW(g, &b, x)) VALERR("invalid data");
849   return (Py_BuildValue("(NN)", ge_pywrap(me, x), bytestring_pywrapbuf(&b)));
850 end:
851   if (x) G_DESTROY(g, x);
852   return (0);
853 }
854
855 static PyObject *gemeth_fromstring(PyObject *me, PyObject *arg)
856 {
857   mptext_stringctx sc;
858   char *p;
859   Py_ssize_t n;
860   group *g;
861   ge *x = 0;
862
863   if (!PyArg_ParseTuple(arg, "s#:fromstring", &p, &n)) return (0);
864   sc.buf = p;
865   sc.lim = sc.buf + n;
866   g = GROUP_G(me);
867   x = G_CREATE(g);
868   if (G_READ(g, x, &mptext_stringops, &sc))
869     VALERR("bad group element string");
870   return (Py_BuildValue("(Ns#)", ge_pywrap(me, x),
871                         sc.buf, (Py_ssize_t)(sc.lim - sc.buf)));
872 end:
873   if (x) G_DESTROY(g, x);
874   return (0);
875 }
876
877 static PyObject *gmeth_parse(PyObject *me, PyObject *arg)
878 {
879   char *p;
880   qd_parse qd;
881   group *g;
882
883   if (!PyArg_ParseTuple(arg, "s:parse", &p)) goto end;
884   qd.p = p; qd.e = 0;
885   if ((g = group_parse(&qd)) == 0) VALERR(qd.e);
886   return (group_pywrap(g));
887 end:
888   return (0);
889 }
890
891 static PyObject *geget_group(PyObject *me, void *hunoz)
892   { RETURN_OBJ(GE_GOBJ(me)); }
893
894 static PyObject *gget_nbits(PyObject *me, void *hunoz)
895   { return (PyInt_FromLong(GROUP_G(me)->nbits)); }
896
897 static PyObject *gget_noctets(PyObject *me, void *hunoz)
898   { return (PyInt_FromLong(GROUP_G(me)->noctets)); }
899
900 static PyObject *gget_i(PyObject *me, void *hunoz)
901 {
902   group *g = GROUP_G(me); ge *x = G_CREATE(g);
903   G_COPY(g, x, g->i); return (ge_pywrap(me, x));
904 }
905
906 static PyObject *gget_g(PyObject *me, void *hunoz)
907 {
908   group *g = GROUP_G(me); ge *x = G_CREATE(g);
909   G_COPY(g, x, g->g); return (ge_pywrap(me, x));
910 }
911
912 static Py_hash_t ge_pyhash(PyObject *me)
913 {
914   buf b;
915   size_t sz = GE_G(me)->noctets + 4;
916   uint32 h = 0xf672c776 + GE_G(me)->ops->ty;
917   octet *p = xmalloc(sz);
918   buf_init(&b, p, sz);
919   G_TOBUF(GE_G(me), &b, GE_X(me));
920   assert(BOK(&b));
921   h = unihash_hash(&unihash_global, h, BBASE(&b), BLEN(&b));
922   xfree(p);
923   return (h % LONG_MAX);
924 }
925
926 static PyObject *gget_r(PyObject *me, void *hunoz)
927   { return (mp_pywrap(MP_COPY(GROUP_G(me)->r))); }
928
929 static PyObject *gget_h(PyObject *me, void *hunoz)
930   { return (mp_pywrap(MP_COPY(GROUP_G(me)->h))); }
931
932 static const PyGetSetDef ge_pygetset[] = {
933 #define GETSETNAME(op, name) ge##op##_##name
934   GET   (group,         "X.group -> group containing X")
935 #undef GETSETNAME
936   { 0 }
937 };
938
939 static const PyMethodDef ge_pymethods[] = {
940 #define METHNAME(name) gemeth_##name
941   NAMETH(inv,           "X.inv() -> inverse element of X")
942   NAMETH(sqr,           "X.sqr() -> X^2 = X * X")
943   NAMETH(check,         "X.check() -> check X really belongs to its group")
944   NAMETH(toint,         "X.toint() -> X converted to an integer")
945   KWMETH(toec,          "X.toec([curve = ECPt]) -> "
946                                        "X converted to elliptic curve point")
947   NAMETH(tobuf,         "X.tobuf() -> X in buffer representation")
948   NAMETH(toraw,         "X.toraw() -> X in raw representation")
949   CMTH  (frombuf,       "frombuf(BUF) -> X, REST")
950   CMTH  (fromraw,       "fromraw(BUF) -> X, REST")
951   CMTH  (fromstring,    "fromstring(STR) -> X, REST")
952 #undef METHNAME
953   { 0 }
954 };
955
956 static const PyNumberMethods ge_pynumber = {
957   0,                                    /* @nb_add@ */
958   0,                                    /* @nb_subtract@ */
959   ge_pymul,                             /* @nb_multiply@ */
960   ge_pydiv,                             /* @nb_divide@ */
961   0,                                    /* @nb_remainder@ */
962   0,                                    /* @nb_divmod@ */
963   ge_pyexp,                             /* @nb_power@ */
964   0,                                    /* @nb_negative@ */
965   0,                                    /* @nb_positive@ */
966   0,                                    /* @nb_absolute@ */
967   ge_pynonzerop,                        /* @nb_nonzero@ */
968   0,                                    /* @nb_invert@ */
969   0,                                    /* @nb_lshift@ */
970   0,                                    /* @nb_rshift@ */
971   0,                                    /* @nb_and@ */
972   0,                                    /* @nb_xor@ */
973   0,                                    /* @nb_or@ */
974   0,                                    /* @nb_coerce@ */
975   ge_pyint,                             /* @nb_int@ */
976   ge_pylong,                            /* @nb_long@ */
977   0 /* meaningless */,                  /* @nb_float@ */
978   0,                                    /* @nb_oct@ */
979   0,                                    /* @nb_hex@ */
980
981   0,                                    /* @nb_inplace_add@ */
982   0,                                    /* @nb_inplace_subtract@ */
983   0,                                    /* @nb_inplace_multiply@ */
984   0,                                    /* @nb_inplace_divide@ */
985   0,                                    /* @nb_inplace_remainder@ */
986   0,                                    /* @nb_inplace_power@ */
987   0,                                    /* @nb_inplace_lshift@ */
988   0,                                    /* @nb_inplace_rshift@ */
989   0,                                    /* @nb_inplace_and@ */
990   0,                                    /* @nb_inplace_xor@ */
991   0,                                    /* @nb_inplace_or@ */
992
993   0,                                    /* @nb_floor_divide@ */
994   ge_pydiv,                             /* @nb_true_divide@ */
995   0,                                    /* @nb_inplace_floor_divide@ */
996   0,                                    /* @nb_inplace_true_divide@ */
997 };
998
999 static const PyTypeObject ge_pytype_skel = {
1000   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1001   "GE",                                 /* @tp_name@ */
1002   sizeof(ge_pyobj),                     /* @tp_basicsize@ */
1003   0,                                    /* @tp_itemsize@ */
1004
1005   ge_pydealloc,                         /* @tp_dealloc@ */
1006   0,                                    /* @tp_print@ */
1007   0,                                    /* @tp_getattr@ */
1008   0,                                    /* @tp_setattr@ */
1009   0,                                    /* @tp_compare@ */
1010   0,                                    /* @tp_repr@ */
1011   PYNUMBER(ge),                         /* @tp_as_number@ */
1012   0,                                    /* @tp_as_sequence@ */
1013   0,                                    /* @tp_as_mapping@ */
1014   ge_pyhash,                            /* @tp_hash@ */
1015   0,                                    /* @tp_call@ */
1016   ge_pystr,                             /* @tp_str@ */
1017   0,                                    /* @tp_getattro@ */
1018   0,                                    /* @tp_setattro@ */
1019   0,                                    /* @tp_as_buffer@ */
1020   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1021     Py_TPFLAGS_CHECKTYPES |
1022     Py_TPFLAGS_BASETYPE,
1023
1024   /* @tp_doc@ */
1025   "Group elements, abstract base class.",
1026
1027   0,                                    /* @tp_traverse@ */
1028   0,                                    /* @tp_clear@ */
1029   ge_pyrichcompare,                     /* @tp_richcompare@ */
1030   0,                                    /* @tp_weaklistoffset@ */
1031   0,                                    /* @tp_iter@ */
1032   0,                                    /* @tp_iternext@ */
1033   PYMETHODS(ge),                        /* @tp_methods@ */
1034   0,                                    /* @tp_members@ */
1035   PYGETSET(ge),                         /* @tp_getset@ */
1036   0,                                    /* @tp_base@ */
1037   0,                                    /* @tp_dict@ */
1038   0,                                    /* @tp_descr_get@ */
1039   0,                                    /* @tp_descr_set@ */
1040   0,                                    /* @tp_dictoffset@ */
1041   0,                                    /* @tp_init@ */
1042   PyType_GenericAlloc,                  /* @tp_alloc@ */
1043   abstract_pynew,                       /* @tp_new@ */
1044   0,                                    /* @tp_free@ */
1045   0                                     /* @tp_is_gc@ */
1046 };
1047
1048 static const PyGetSetDef group_pygetset[] = {
1049 #define GETSETNAME(op, name) g##op##_##name
1050   GET   (noctets,       "G.noctets -> size in octets of element")
1051   GET   (nbits,         "G.nbits -> size in bits of element")
1052   GET   (i,             "G.i -> group identity")
1053   GET   (g,             "G.g -> group generator")
1054   GET   (r,             "G.r -> group order")
1055   GET   (h,             "G.h -> group cofactor")
1056 #undef GETSETNAME
1057   { 0 }
1058 };
1059
1060 static const PyMethodDef group_pymethods[] = {
1061 #define METHNAME(name) gmeth_##name
1062   METH  (mexp,        "G.mexp([(X0, N0), (X1, N1), ...]) -> X0^N0 X1^N1 ...")
1063   KWMETH(checkgroup,    "G.checkgroup([rng = rand]): check group is good")
1064   SMTH  (parse,         "parse(STR) -> G, REST")
1065 #undef METHNAME
1066   { 0 }
1067 };
1068
1069 static const PyTypeObject group_pytype_skel = {
1070   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1071   "Group",                              /* @tp_name@ */
1072   sizeof(group_pyobj),                  /* @tp_basicsize@ */
1073   0,                                    /* @tp_itemsize@ */
1074
1075   group_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   "Abstract base class for groups.",
1095
1096   0,                                    /* @tp_traverse@ */
1097   0,                                    /* @tp_clear@ */
1098   group_pyrichcompare,                  /* @tp_richcompare@ */
1099   0,                                    /* @tp_weaklistoffset@ */
1100   0,                                    /* @tp_iter@ */
1101   0,                                    /* @tp_iternext@ */
1102   PYMETHODS(group),                     /* @tp_methods@ */
1103   0,                                    /* @tp_members@ */
1104   PYGETSET(group),                      /* @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 *pgget_info(PyObject *me, void *hunoz)
1118 {
1119   gprime_param dp;
1120   gctx_prime *gg = (gctx_prime *)GROUP_G(me);
1121   dp.p = MP_COPY(gg->mm.m);
1122   dp.q = MP_COPY(gg->g.r);
1123   dp.g = mpmont_reduce(&gg->mm, MP_NEW, gg->gen.x);
1124   return (fginfo_pywrap(&dp, dhinfo_pytype));
1125 }
1126
1127 static const PyGetSetDef primegroup_pygetset[] = {
1128 #define GETSETNAME(op, name) pg##op##_##name
1129   GET   (info,          "G.info -> information about the group")
1130 #undef GETSETNAME
1131   { 0 }
1132 };
1133
1134 static PyObject *primegroup_pynew(PyTypeObject *ty,
1135                                   PyObject *arg, PyObject *kw)
1136 {
1137   PyObject *i;
1138   static const char *const kwlist[] = { "info", 0 };
1139
1140   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O!:new", KWLIST,
1141                                    dhinfo_pytype, &i))
1142     return (0);
1143   return (group_dopywrap(ty, group_prime(FGINFO_DP(i))));
1144 }
1145
1146 static const PyTypeObject primegroup_pytype_skel = {
1147   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1148   "PrimeGroup",                         /* @tp_name@ */
1149   sizeof(group_pyobj),                  /* @tp_basicsize@ */
1150   0,                                    /* @tp_itemsize@ */
1151
1152   group_pydealloc,                      /* @tp_dealloc@ */
1153   0,                                    /* @tp_print@ */
1154   0,                                    /* @tp_getattr@ */
1155   0,                                    /* @tp_setattr@ */
1156   0,                                    /* @tp_compare@ */
1157   0,                                    /* @tp_repr@ */
1158   0,                                    /* @tp_as_number@ */
1159   0,                                    /* @tp_as_sequence@ */
1160   0,                                    /* @tp_as_mapping@ */
1161   0,                                    /* @tp_hash@ */
1162   0,                                    /* @tp_call@ */
1163   0,                                    /* @tp_str@ */
1164   0,                                    /* @tp_getattro@ */
1165   0,                                    /* @tp_setattro@ */
1166   0,                                    /* @tp_as_buffer@ */
1167   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1168     Py_TPFLAGS_BASETYPE,
1169
1170   /* @tp_doc@ */
1171   "PrimeGroup(INFO): subgroups of prime fields.",
1172
1173   0,                                    /* @tp_traverse@ */
1174   0,                                    /* @tp_clear@ */
1175   0,                                    /* @tp_richcompare@ */
1176   0,                                    /* @tp_weaklistoffset@ */
1177   0,                                    /* @tp_iter@ */
1178   0,                                    /* @tp_iternext@ */
1179   0,                                    /* @tp_methods@ */
1180   0,                                    /* @tp_members@ */
1181   PYGETSET(primegroup),                 /* @tp_getset@ */
1182   0,                                    /* @tp_base@ */
1183   0,                                    /* @tp_dict@ */
1184   0,                                    /* @tp_descr_get@ */
1185   0,                                    /* @tp_descr_set@ */
1186   0,                                    /* @tp_dictoffset@ */
1187   0,                                    /* @tp_init@ */
1188   PyType_GenericAlloc,                  /* @tp_alloc@ */
1189   primegroup_pynew,                     /* @tp_new@ */
1190   0,                                    /* @tp_free@ */
1191   0                                     /* @tp_is_gc@ */
1192 };
1193
1194 static PyObject *bgget_info(PyObject *me, void *hunoz)
1195 {
1196   gbin_param dp;
1197   gctx_bin *gg = (gctx_bin *)GROUP_G(me);
1198   dp.p = MP_COPY(gg->r.p);
1199   dp.q = MP_COPY(gg->g.r);
1200   dp.g = MP_COPY(gg->gen.x);
1201   return (fginfo_pywrap(&dp, bindhinfo_pytype));
1202 }
1203
1204 static const PyGetSetDef bingroup_pygetset[] = {
1205 #define GETSETNAME(op, name) bg##op##_##name
1206   GET   (info,          "G.info -> information about the group")
1207 #undef GETSETNAME
1208   { 0 }
1209 };
1210
1211 static PyObject *bingroup_pynew(PyTypeObject *ty,
1212                                 PyObject *arg, PyObject *kw)
1213 {
1214   PyObject *i;
1215   static const char *const kwlist[] = { "info", 0 };
1216
1217   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O!:new", KWLIST,
1218                                    bindhinfo_pytype, &i))
1219     return (0);
1220   return (group_dopywrap(ty, group_binary(FGINFO_DP(i))));
1221 }
1222
1223 static const PyTypeObject bingroup_pytype_skel = {
1224   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1225   "BinGroup",                           /* @tp_name@ */
1226   sizeof(group_pyobj),                  /* @tp_basicsize@ */
1227   0,                                    /* @tp_itemsize@ */
1228
1229   group_pydealloc,                      /* @tp_dealloc@ */
1230   0,                                    /* @tp_print@ */
1231   0,                                    /* @tp_getattr@ */
1232   0,                                    /* @tp_setattr@ */
1233   0,                                    /* @tp_compare@ */
1234   0,                                    /* @tp_repr@ */
1235   0,                                    /* @tp_as_number@ */
1236   0,                                    /* @tp_as_sequence@ */
1237   0,                                    /* @tp_as_mapping@ */
1238   0,                                    /* @tp_hash@ */
1239   0,                                    /* @tp_call@ */
1240   0,                                    /* @tp_str@ */
1241   0,                                    /* @tp_getattro@ */
1242   0,                                    /* @tp_setattro@ */
1243   0,                                    /* @tp_as_buffer@ */
1244   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1245     Py_TPFLAGS_BASETYPE,
1246
1247   /* @tp_doc@ */
1248   "BinGroup(INFO): subgroups of binary fields.",
1249
1250   0,                                    /* @tp_traverse@ */
1251   0,                                    /* @tp_clear@ */
1252   0,                                    /* @tp_richcompare@ */
1253   0,                                    /* @tp_weaklistoffset@ */
1254   0,                                    /* @tp_iter@ */
1255   0,                                    /* @tp_iternext@ */
1256   0,                                    /* @tp_methods@ */
1257   0,                                    /* @tp_members@ */
1258   PYGETSET(bingroup),                   /* @tp_getset@ */
1259   0,                                    /* @tp_base@ */
1260   0,                                    /* @tp_dict@ */
1261   0,                                    /* @tp_descr_get@ */
1262   0,                                    /* @tp_descr_set@ */
1263   0,                                    /* @tp_dictoffset@ */
1264   0,                                    /* @tp_init@ */
1265   PyType_GenericAlloc,                  /* @tp_alloc@ */
1266   bingroup_pynew,                       /* @tp_new@ */
1267   0,                                    /* @tp_free@ */
1268   0                                     /* @tp_is_gc@ */
1269 };
1270
1271 static PyObject *egget_info(PyObject *me, void *hunoz)
1272 {
1273   ec_info ei;
1274   gctx_ec *gg = (gctx_ec *)GROUP_G(me);
1275
1276   ecinfo_copy(&ei, &gg->ei);
1277   return (ecinfo_pywrap(&ei));
1278 }
1279
1280 static const PyGetSetDef ecgroup_pygetset[] = {
1281 #define GETSETNAME(op, name) eg##op##_##name
1282   GET   (info,          "G.info -> information about the group")
1283 #undef GETSETNAME
1284   { 0 }
1285 };
1286
1287 static PyObject *ecgroup_pynew(PyTypeObject *ty,
1288                                PyObject *arg, PyObject *kw)
1289 {
1290   PyObject *i;
1291   ec_info ei;
1292   static const char *const kwlist[] = { "info", 0 };
1293
1294   if (!PyArg_ParseTupleAndKeywords(arg, kw, "O!:new", KWLIST,
1295                                    ecinfo_pytype, &i))
1296     return (0);
1297   ecinfo_copy(&ei, ECINFO_EI(i));
1298   return (group_dopywrap(ty, group_ec(&ei)));
1299 }
1300
1301 static const PyTypeObject ecgroup_pytype_skel = {
1302   PyVarObject_HEAD_INIT(0, 0)           /* Header */
1303   "ECGroup",                            /* @tp_name@ */
1304   sizeof(group_pyobj),                  /* @tp_basicsize@ */
1305   0,                                    /* @tp_itemsize@ */
1306
1307   group_pydealloc,                      /* @tp_dealloc@ */
1308   0,                                    /* @tp_print@ */
1309   0,                                    /* @tp_getattr@ */
1310   0,                                    /* @tp_setattr@ */
1311   0,                                    /* @tp_compare@ */
1312   0,                                    /* @tp_repr@ */
1313   0,                                    /* @tp_as_number@ */
1314   0,                                    /* @tp_as_sequence@ */
1315   0,                                    /* @tp_as_mapping@ */
1316   0,                                    /* @tp_hash@ */
1317   0,                                    /* @tp_call@ */
1318   0,                                    /* @tp_str@ */
1319   0,                                    /* @tp_getattro@ */
1320   0,                                    /* @tp_setattro@ */
1321   0,                                    /* @tp_as_buffer@ */
1322   Py_TPFLAGS_DEFAULT |                  /* @tp_flags@ */
1323     Py_TPFLAGS_BASETYPE,
1324
1325   /* @tp_doc@ */
1326   "ECGroup(INFO): elliptic curve groups.",
1327
1328   0,                                    /* @tp_traverse@ */
1329   0,                                    /* @tp_clear@ */
1330   0,                                    /* @tp_richcompare@ */
1331   0,                                    /* @tp_weaklistoffset@ */
1332   0,                                    /* @tp_iter@ */
1333   0,                                    /* @tp_iternext@ */
1334   0,                                    /* @tp_methods@ */
1335   0,                                    /* @tp_members@ */
1336   PYGETSET(ecgroup),                    /* @tp_getset@ */
1337   0,                                    /* @tp_base@ */
1338   0,                                    /* @tp_dict@ */
1339   0,                                    /* @tp_descr_get@ */
1340   0,                                    /* @tp_descr_set@ */
1341   0,                                    /* @tp_dictoffset@ */
1342   0,                                    /* @tp_init@ */
1343   PyType_GenericAlloc,                  /* @tp_alloc@ */
1344   ecgroup_pynew,                        /* @tp_new@ */
1345   0,                                    /* @tp_free@ */
1346   0                                     /* @tp_is_gc@ */
1347 };
1348
1349 /*----- Global stuff ------------------------------------------------------*/
1350
1351 void group_pyinit(void)
1352 {
1353   INITTYPE(fginfo, root);
1354   INITTYPE(dhinfo, fginfo);
1355   INITTYPE(bindhinfo, dhinfo);
1356   INITTYPE(ge, root);
1357   INITTYPE(group, type);
1358   INITTYPE(primegroup, group);
1359   INITTYPE(bingroup, group);
1360   INITTYPE(ecgroup, group);
1361 }
1362
1363 static const char *grp_namefn(const void *p)
1364   { const pentry *pt = p; return (pt->name); }
1365
1366 static int grp_ixfn(const pentry *tab, const pentry *pt)
1367 {
1368   int i;
1369
1370   for (i = 0; tab[i].name; i++)
1371     if (tab[i].data == pt->data) return (i);
1372   return (-1);
1373 }
1374 static int pgrp_ixfn(const void *p) { return (grp_ixfn(ptab, p)); }
1375 static int bgrp_ixfn(const void *p) { return (grp_ixfn(bintab, p)); }
1376
1377 static PyObject *grp_valfn(const pentry *tab, PyTypeObject *ty, int i)
1378 {
1379   gprime_param gp;
1380
1381   dh_infofromdata(&gp, tab[i].data);
1382   return (fginfo_pywrap(&gp, ty));
1383 }
1384 static PyObject *pgrp_valfn(int i)
1385   { return (grp_valfn(ptab, dhinfo_pytype, i)); }
1386 static PyObject *bgrp_valfn(int i)
1387   { return (grp_valfn(bintab, bindhinfo_pytype, i)); }
1388
1389 void group_pyinsert(PyObject *mod)
1390 {
1391   INSERT("FGInfo", fginfo_pytype);
1392   INSERT("DHInfo", dhinfo_pytype);
1393   INSERT("BinDHInfo", bindhinfo_pytype);
1394   INSERT("GE", ge_pytype);
1395   INSERT("Group", group_pytype);
1396   INSERT("PrimeGroup", primegroup_pytype);
1397   INSERT("BinGroup", bingroup_pytype);
1398   INSERT("ECGroup", ecgroup_pytype);
1399   INSERT("primegroups", make_grouptab(ptab, sizeof(*ptab),
1400                                       grp_namefn, pgrp_ixfn, pgrp_valfn));
1401   INSERT("bingroups", make_grouptab(bintab, sizeof(*bintab),
1402                                     grp_namefn, bgrp_ixfn, bgrp_valfn));
1403 }
1404
1405 /*----- That's all, folks -------------------------------------------------*/