secp256k1mod.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  3. Copyright (C)2013-2018 The MMGen Project <mmgen@tuta.io>
  4. This program is free software: you can redistribute it and/or modify it under
  5. the terms of the GNU General Public License as published by the Free Software
  6. Foundation, either version 3 of the License, or (at your option) any later
  7. version.
  8. This program is distributed in the hope that it will be useful, but WITHOUT
  9. ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  10. FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
  11. details.
  12. You should have received a copy of the GNU General Public License along with
  13. this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. #include <Python.h>
  16. #include <secp256k1.h>
  17. static PyObject * priv2pub(PyObject *self, PyObject *args) {
  18. const unsigned char * privkey;
  19. const int klen;
  20. const int compressed;
  21. if (!PyArg_ParseTuple(args, "t#I", &privkey, &klen, &compressed))
  22. return NULL;
  23. if (klen != 32) {
  24. PyErr_SetString(PyExc_ValueError, "Private key length not 32 bytes");
  25. return NULL;
  26. }
  27. secp256k1_pubkey pubkey;
  28. size_t pubkeyclen = compressed == 1 ? 33: 65;
  29. unsigned char pubkeyc[pubkeyclen];
  30. static secp256k1_context *ctx = NULL;
  31. if (ctx == NULL) {
  32. /* puts ("Initializing context"); */
  33. ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
  34. }
  35. if (secp256k1_ec_pubkey_create(ctx, &pubkey, privkey) != 1) {
  36. PyErr_SetString(PyExc_RuntimeError, "Public key creation failed");
  37. return NULL;
  38. }
  39. if (secp256k1_ec_pubkey_serialize(ctx, pubkeyc, &pubkeyclen, &pubkey,
  40. compressed == 1 ? SECP256K1_EC_COMPRESSED: SECP256K1_EC_UNCOMPRESSED) != 1) {
  41. PyErr_SetString(PyExc_RuntimeError, "Public key serialization failed");
  42. return NULL;
  43. }
  44. return Py_BuildValue("s#", pubkeyc,pubkeyclen);
  45. }
  46. static PyMethodDef secp256k1Methods[] = {
  47. {"priv2pub", priv2pub, METH_VARARGS, "Generate pubkey from privkey using libsecp256k1"},
  48. {NULL, NULL, 0, NULL} /* Sentinel */
  49. };
  50. PyMODINIT_FUNC initsecp256k1(void) {
  51. PyObject *m;
  52. m = Py_InitModule("secp256k1", secp256k1Methods);
  53. if (m == NULL) return;
  54. }