secp256k1mod.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. #include <Python.h>
  2. #include <secp256k1.h>
  3. static PyObject * priv2pub(PyObject *self, PyObject *args) {
  4. const unsigned char * privkey;
  5. const int klen;
  6. const int compressed;
  7. if (!PyArg_ParseTuple(args, "t#I", &privkey, &klen, &compressed))
  8. return NULL;
  9. if (klen != 32) return NULL;
  10. secp256k1_pubkey pubkey;
  11. size_t pubkeyclen = compressed == 1 ? 33: 65;
  12. unsigned char pubkeyc[pubkeyclen];
  13. static secp256k1_context *ctx = NULL;
  14. if (ctx == NULL) {
  15. /* puts ("Initializing context"); */
  16. ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
  17. }
  18. if (secp256k1_ec_pubkey_create(ctx, &pubkey, privkey) != 1) return NULL;
  19. if (secp256k1_ec_pubkey_serialize(ctx, pubkeyc, &pubkeyclen, &pubkey,
  20. compressed == 1 ? SECP256K1_EC_COMPRESSED: SECP256K1_EC_UNCOMPRESSED) != 1)
  21. return NULL;
  22. return Py_BuildValue("s#", pubkeyc,pubkeyclen);
  23. }
  24. static PyMethodDef secp256k1Methods[] = {
  25. {"priv2pub", priv2pub, METH_VARARGS, "Generate pubkey from privkey using libsecp256k1"},
  26. {NULL, NULL, 0, NULL} /* Sentinel */
  27. };
  28. PyMODINIT_FUNC initsecp256k1(void) {
  29. PyObject *m;
  30. m = Py_InitModule("secp256k1", secp256k1Methods);
  31. if (m == NULL) return;
  32. }