secp256k1mod.c 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. /*
  2. mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  3. Copyright (C)2013-2024 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. /*
  16. NOTE: deprecated context flags SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY
  17. must be used for now instead of SECP256K1_CONTEXT_NONE (see libsecp256k1 CHANGELOG)
  18. for backward compatibility with libsecp256k1 <v0.2.0 (i.e. pre-bookworm distros).
  19. */
  20. #define PY_SSIZE_T_CLEAN
  21. #include <Python.h>
  22. #include <secp256k1.h>
  23. int privkey_check(
  24. const secp256k1_context * ctx,
  25. const unsigned char * privkey_bytes,
  26. const Py_ssize_t privkey_bytes_len,
  27. const char * desc
  28. ) {
  29. if (privkey_bytes_len != 32) {
  30. char buf[64 + strlen(desc)];
  31. sprintf(buf, "%s length not 32 bytes", desc);
  32. PyErr_SetString(PyExc_ValueError, buf);
  33. return 0;
  34. }
  35. if (secp256k1_ec_seckey_verify(ctx, privkey_bytes) != 1) {
  36. char buf[64 + strlen(desc)];
  37. sprintf(buf, "%s not in allowable range", desc);
  38. PyErr_SetString(PyExc_ValueError, buf);
  39. return 0;
  40. }
  41. return 1;
  42. }
  43. int pubkey_parse_with_check(
  44. const secp256k1_context * ctx,
  45. secp256k1_pubkey * pubkey_ptr,
  46. const unsigned char * pubkey_bytes,
  47. const Py_ssize_t pubkey_bytes_len
  48. ) {
  49. if (ctx == NULL) {
  50. PyErr_SetString(PyExc_RuntimeError, "Context initialization failed");
  51. return 0;
  52. }
  53. if (pubkey_bytes_len == 33) {
  54. if (pubkey_bytes[0] != 3 && pubkey_bytes[0] != 2) {
  55. PyErr_SetString(PyExc_ValueError, "Invalid first byte for serialized compressed public key");
  56. return 0;
  57. }
  58. } else if (pubkey_bytes_len == 65) {
  59. if (pubkey_bytes[0] != 4) {
  60. PyErr_SetString(PyExc_ValueError, "Invalid first byte for serialized uncompressed public key");
  61. return 0;
  62. }
  63. } else {
  64. PyErr_SetString(PyExc_ValueError, "Serialized public key length not 33 or 65 bytes");
  65. return 0;
  66. }
  67. /* checks for point-at-infinity (via secp256k1_pubkey_save) */
  68. if (secp256k1_ec_pubkey_parse(ctx, pubkey_ptr, pubkey_bytes, pubkey_bytes_len) != 1) {
  69. PyErr_SetString(PyExc_ValueError, "Public key could not be parsed or encodes point-at-infinity");
  70. return 0;
  71. }
  72. return 1;
  73. }
  74. static PyObject * pubkey_gen(PyObject *self, PyObject *args) {
  75. const unsigned char * privkey_bytes;
  76. Py_ssize_t privkey_bytes_len;
  77. int compressed;
  78. if (!PyArg_ParseTuple(args, "y#I", &privkey_bytes, &privkey_bytes_len, &compressed)) {
  79. PyErr_SetString(PyExc_ValueError, "Unable to parse extension mod arguments");
  80. return NULL;
  81. }
  82. size_t pubkey_bytes_len = compressed == 1 ? 33 : 65;
  83. unsigned char pubkey_bytes[pubkey_bytes_len];
  84. secp256k1_pubkey pubkey;
  85. /* see NOTE */
  86. secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
  87. if (ctx == NULL) {
  88. PyErr_SetString(PyExc_RuntimeError, "Context initialization failed");
  89. return NULL;
  90. }
  91. if (!privkey_check(ctx, privkey_bytes, privkey_bytes_len, "Private key")) {
  92. return NULL;
  93. }
  94. if (secp256k1_ec_pubkey_create(ctx, &pubkey, privkey_bytes) != 1) {
  95. PyErr_SetString(PyExc_RuntimeError, "Public key creation failed");
  96. return NULL;
  97. }
  98. if (secp256k1_ec_pubkey_serialize(ctx, pubkey_bytes, &pubkey_bytes_len, &pubkey,
  99. compressed == 1 ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED) != 1) {
  100. PyErr_SetString(PyExc_RuntimeError, "Public key serialization failed");
  101. return NULL;
  102. }
  103. return Py_BuildValue("y#", pubkey_bytes, pubkey_bytes_len);
  104. }
  105. static PyObject * pubkey_tweak_add(PyObject *self, PyObject *args) {
  106. const unsigned char * pubkey_bytes;
  107. const unsigned char * tweak_bytes;
  108. Py_ssize_t pubkey_bytes_len;
  109. Py_ssize_t tweak_bytes_len;
  110. if (!PyArg_ParseTuple(args, "y#y#", &pubkey_bytes, &pubkey_bytes_len, &tweak_bytes, &tweak_bytes_len)) {
  111. PyErr_SetString(PyExc_ValueError, "Unable to parse extension mod arguments");
  112. return NULL;
  113. }
  114. /* see NOTE */
  115. secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
  116. secp256k1_pubkey pubkey;
  117. if (!pubkey_parse_with_check(ctx, &pubkey, pubkey_bytes, pubkey_bytes_len)) {
  118. return NULL;
  119. }
  120. if (!privkey_check(ctx, tweak_bytes, tweak_bytes_len, "Tweak")) {
  121. return NULL;
  122. }
  123. /* checks for point-at-infinity (via secp256k1_pubkey_save) */
  124. if (secp256k1_ec_pubkey_tweak_add(ctx, &pubkey, tweak_bytes) != 1) {
  125. PyErr_SetString(PyExc_RuntimeError, "Adding public key points failed or result was point-at-infinity");
  126. return NULL;
  127. }
  128. unsigned char new_pubkey_bytes[pubkey_bytes_len];
  129. if (secp256k1_ec_pubkey_serialize(
  130. ctx,
  131. new_pubkey_bytes,
  132. (size_t*) &pubkey_bytes_len,
  133. &pubkey,
  134. pubkey_bytes_len == 33 ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED) != 1) {
  135. PyErr_SetString(PyExc_RuntimeError, "Public key serialization failed");
  136. return NULL;
  137. }
  138. return Py_BuildValue("y#", new_pubkey_bytes, pubkey_bytes_len);
  139. }
  140. static PyObject * pubkey_check(PyObject *self, PyObject *args) {
  141. const unsigned char * pubkey_bytes;
  142. Py_ssize_t pubkey_bytes_len;
  143. if (!PyArg_ParseTuple(args, "y#", &pubkey_bytes, &pubkey_bytes_len)) {
  144. PyErr_SetString(PyExc_ValueError, "Unable to parse extension mod arguments");
  145. return NULL;
  146. }
  147. /* see NOTE */
  148. secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
  149. secp256k1_pubkey pubkey;
  150. if (!pubkey_parse_with_check(ctx, &pubkey, pubkey_bytes, pubkey_bytes_len)) {
  151. return NULL;
  152. }
  153. return Py_BuildValue("I", 1);
  154. }
  155. /* https://docs.python.org/3/howto/cporting.html */
  156. struct module_state {
  157. PyObject *error;
  158. };
  159. #define GETSTATE(m) ((struct module_state*)PyModule_GetState(m))
  160. static PyMethodDef secp256k1_methods[] = {
  161. {
  162. "pubkey_gen",
  163. pubkey_gen,
  164. METH_VARARGS,
  165. "Generate a serialized pubkey from privkey bytes"
  166. },
  167. {
  168. "pubkey_tweak_add",
  169. pubkey_tweak_add,
  170. METH_VARARGS,
  171. "Add scalar bytes to a serialized pubkey, returning a serialized pubkey"
  172. },
  173. {
  174. "pubkey_check",
  175. pubkey_check,
  176. METH_VARARGS,
  177. "Check a serialized pubkey, ensuring the encoded point is not point-at-infinity"
  178. },
  179. {NULL, NULL}
  180. };
  181. static int secp256k1_traverse(PyObject *m, visitproc visit, void *arg) {
  182. Py_VISIT(GETSTATE(m)->error);
  183. return 0;
  184. }
  185. static int secp256k1_clear(PyObject *m) {
  186. Py_CLEAR(GETSTATE(m)->error);
  187. return 0;
  188. }
  189. static struct PyModuleDef moduledef = {
  190. PyModuleDef_HEAD_INIT,
  191. "secp256k1",
  192. NULL,
  193. sizeof(struct module_state),
  194. secp256k1_methods,
  195. NULL,
  196. secp256k1_traverse,
  197. secp256k1_clear,
  198. NULL
  199. };
  200. #define INITERROR return NULL
  201. PyMODINIT_FUNC PyInit_secp256k1(void) {
  202. PyObject *module = PyModule_Create(&moduledef);
  203. if (module == NULL)
  204. INITERROR;
  205. struct module_state *st = GETSTATE(module);
  206. st->error = PyErr_NewException("secp256k1.Error", NULL, NULL);
  207. if (st->error == NULL) {
  208. Py_DECREF(module);
  209. INITERROR;
  210. }
  211. return module;
  212. }