secp256k1.h raw

   1  #ifndef SECP256K1_H
   2  #define SECP256K1_H
   3  
   4  #ifdef __cplusplus
   5  extern "C" {
   6  #endif
   7  
   8  #include <stddef.h>
   9  #include <stdint.h>
  10  
  11  /** Unless explicitly stated all pointer arguments must not be NULL.
  12   *
  13   * The following rules specify the order of arguments in API calls:
  14   *
  15   * 1. Context pointers go first, followed by output arguments, combined
  16   *    output/input arguments, and finally input-only arguments.
  17   * 2. Array lengths always immediately follow the argument whose length
  18   *    they describe, even if this violates rule 1.
  19   * 3. Within the OUT/OUTIN/IN groups, pointers to data that is typically generated
  20   *    later go first. This means: signatures, public nonces, secret nonces,
  21   *    messages, public keys, secret keys, tweaks.
  22   * 4. Arguments that are not data pointers go last, from more complex to less
  23   *    complex: function pointers, algorithm names, messages, void pointers,
  24   *    counts, flags, booleans.
  25   * 5. Opaque data pointers follow the function pointer they are to be passed to.
  26   */
  27  
  28  /** Opaque data structure that holds context information
  29   *
  30   *  The primary purpose of context objects is to store randomization data for
  31   *  enhanced protection against side-channel leakage. This protection is only
  32   *  effective if the context is randomized after its creation. See
  33   *  secp256k1_context_create for creation of contexts and
  34   *  secp256k1_context_randomize for randomization.
  35   *
  36   *  A secondary purpose of context objects is to store pointers to callback
  37   *  functions that the library will call when certain error states arise. See
  38   *  secp256k1_context_set_error_callback as well as
  39   *  secp256k1_context_set_illegal_callback for details. Future library versions
  40   *  may use context objects for additional purposes.
  41   *
  42   *  A constructed context can safely be used from multiple threads
  43   *  simultaneously, but API calls that take a non-const pointer to a context
  44   *  need exclusive access to it. In particular this is the case for
  45   *  secp256k1_context_destroy, secp256k1_context_preallocated_destroy,
  46   *  and secp256k1_context_randomize.
  47   *
  48   *  Regarding randomization, either do it once at creation time (in which case
  49   *  you do not need any locking for the other calls), or use a read-write lock.
  50   */
  51  typedef struct secp256k1_context_struct secp256k1_context;
  52  
  53  /** Opaque data structure that holds a parsed and valid public key.
  54   *
  55   *  The exact representation of data inside is implementation defined and not
  56   *  guaranteed to be portable between different platforms or versions. It is
  57   *  however guaranteed to be 64 bytes in size, and can be safely copied/moved.
  58   *  If you need to convert to a format suitable for storage or transmission,
  59   *  use secp256k1_ec_pubkey_serialize and secp256k1_ec_pubkey_parse. To
  60   *  compare keys, use secp256k1_ec_pubkey_cmp.
  61   */
  62  typedef struct secp256k1_pubkey {
  63      unsigned char data[64];
  64  } secp256k1_pubkey;
  65  
  66  /** Opaque data structure that holds a parsed ECDSA signature.
  67   *
  68   *  The exact representation of data inside is implementation defined and not
  69   *  guaranteed to be portable between different platforms or versions. It is
  70   *  however guaranteed to be 64 bytes in size, and can be safely copied/moved.
  71   *  If you need to convert to a format suitable for storage, transmission, or
  72   *  comparison, use the secp256k1_ecdsa_signature_serialize_* and
  73   *  secp256k1_ecdsa_signature_parse_* functions.
  74   */
  75  typedef struct secp256k1_ecdsa_signature {
  76      unsigned char data[64];
  77  } secp256k1_ecdsa_signature;
  78  
  79  /** A pointer to a function to deterministically generate a nonce.
  80   *
  81   * Returns: 1 if a nonce was successfully generated. 0 will cause signing to fail.
  82   * Out:     nonce32:   pointer to a 32-byte array to be filled by the function.
  83   * In:      msg32:     the 32-byte message hash being verified (will not be NULL)
  84   *          key32:     pointer to a 32-byte secret key (will not be NULL)
  85   *          algo16:    pointer to a 16-byte array describing the signature
  86   *                     algorithm (will be NULL for ECDSA for compatibility).
  87   *          data:      Arbitrary data pointer that is passed through.
  88   *          attempt:   how many iterations we have tried to find a nonce.
  89   *                     This will almost always be 0, but different attempt values
  90   *                     are required to result in a different nonce.
  91   *
  92   * Except for test cases, this function should compute some cryptographic hash of
  93   * the message, the algorithm, the key and the attempt.
  94   */
  95  typedef int (*secp256k1_nonce_function)(
  96      unsigned char *nonce32,
  97      const unsigned char *msg32,
  98      const unsigned char *key32,
  99      const unsigned char *algo16,
 100      void *data,
 101      unsigned int attempt
 102  );
 103  
 104  # if !defined(SECP256K1_GNUC_PREREQ)
 105  #  if defined(__GNUC__)&&defined(__GNUC_MINOR__)
 106  #   define SECP256K1_GNUC_PREREQ(_maj,_min) \
 107   ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min))
 108  #  else
 109  #   define SECP256K1_GNUC_PREREQ(_maj,_min) 0
 110  #  endif
 111  # endif
 112  
 113  /*  When this header is used at build-time the SECP256K1_BUILD define needs to be set
 114   *  to correctly setup export attributes and nullness checks.  This is normally done
 115   *  by secp256k1.c but to guard against this header being included before secp256k1.c
 116   *  has had a chance to set the define (e.g. via test harnesses that just includes
 117   *  secp256k1.c) we set SECP256K1_NO_BUILD when this header is processed without the
 118   *  BUILD define so this condition can be caught.
 119   */
 120  #ifndef SECP256K1_BUILD
 121  # define SECP256K1_NO_BUILD
 122  #endif
 123  
 124  /* Symbol visibility. */
 125  #if !defined(SECP256K1_API) && defined(SECP256K1_NO_API_VISIBILITY_ATTRIBUTES)
 126       /* The user has requested that we don't specify visibility attributes in
 127        * the public API.
 128        *
 129        * Since all our non-API declarations use the static qualifier, this means
 130        * that the user can use -fvisibility=<value> to set the visibility of the
 131        * API symbols. For instance, -fvisibility=hidden can be useful *even for
 132        * the API symbols*, e.g., when building a static library which is linked
 133        * into a shared library, and the latter should not re-export the
 134        * libsecp256k1 API.
 135        *
 136        * While visibility is a concept that applies only to shared libraries,
 137        * setting visibility will still make a difference when building a static
 138        * library: the visibility settings will be stored in the static library,
 139        * solely for the potential case that the static library will be linked into
 140        * a shared library. In that case, the stored visibility settings will
 141        * resurface and be honored for the shared library. */
 142  #    define SECP256K1_API extern
 143  #endif
 144  #if !defined(SECP256K1_API)
 145  #    if defined(SECP256K1_BUILD)
 146           /* On Windows, assume a shared library only if explicitly requested.
 147            *   1. If using Libtool, it defines DLL_EXPORT automatically.
 148            *   2. In other cases, SECP256K1_DLL_EXPORT must be defined. */
 149  #        if defined(_WIN32) && (defined(SECP256K1_DLL_EXPORT) || defined(DLL_EXPORT))
 150               /* GCC for Windows (e.g., MinGW) accepts the __declspec syntax for
 151                * MSVC compatibility. A __declspec declaration implies (but is not
 152                * exactly equivalent to) __attribute__ ((visibility("default"))),
 153                * and so we actually want __declspec even on GCC, see "Microsoft
 154                * Windows Function Attributes" in the GCC manual and the
 155                * recommendations in https://gcc.gnu.org/wiki/Visibility . */
 156  #            define SECP256K1_API extern __declspec(dllexport)
 157           /* Avoid __attribute__ ((visibility("default"))) on Windows to get rid
 158            * of warnings when compiling with -flto due to a bug in GCC, see
 159            * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=116478 . */
 160  #        elif !defined(_WIN32) && defined (__GNUC__) && (__GNUC__ >= 4)
 161  #            define SECP256K1_API extern __attribute__ ((visibility("default")))
 162  #        else
 163  #            define SECP256K1_API extern
 164  #        endif
 165  #    else
 166           /* On Windows, SECP256K1_STATIC must be defined when consuming
 167            * libsecp256k1 as a static library. Note that SECP256K1_STATIC is a
 168            * "consumer-only" macro, and it has no meaning when building
 169            * libsecp256k1. */
 170  #        if defined(_WIN32) && !defined(SECP256K1_STATIC)
 171  #            define SECP256K1_API extern __declspec(dllimport)
 172  #        else
 173  #            define SECP256K1_API extern
 174  #        endif
 175  #    endif
 176  #endif
 177  
 178  /* Warning attributes
 179   * NONNULL is not used if SECP256K1_BUILD is set to avoid the compiler optimizing out
 180   * some paranoid null checks. */
 181  # if defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4)
 182  #  define SECP256K1_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__))
 183  # else
 184  #  define SECP256K1_WARN_UNUSED_RESULT
 185  # endif
 186  # if !defined(SECP256K1_BUILD) && defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4)
 187  #  define SECP256K1_ARG_NONNULL(_x)  __attribute__ ((__nonnull__(_x)))
 188  # else
 189  #  define SECP256K1_ARG_NONNULL(_x)
 190  # endif
 191  
 192  /* Attribute for marking functions, types, and variables as deprecated */
 193  #if !defined(SECP256K1_BUILD) && defined(__has_attribute)
 194  # if __has_attribute(__deprecated__)
 195  #  define SECP256K1_DEPRECATED(_msg) __attribute__ ((__deprecated__(_msg)))
 196  # else
 197  #  define SECP256K1_DEPRECATED(_msg)
 198  # endif
 199  #else
 200  # define SECP256K1_DEPRECATED(_msg)
 201  #endif
 202  
 203  /* All flags' lower 8 bits indicate what they're for. Do not use directly. */
 204  #define SECP256K1_FLAGS_TYPE_MASK ((1 << 8) - 1)
 205  #define SECP256K1_FLAGS_TYPE_CONTEXT (1 << 0)
 206  #define SECP256K1_FLAGS_TYPE_COMPRESSION (1 << 1)
 207  /* The higher bits contain the actual data. Do not use directly. */
 208  #define SECP256K1_FLAGS_BIT_CONTEXT_VERIFY (1 << 8)
 209  #define SECP256K1_FLAGS_BIT_CONTEXT_SIGN (1 << 9)
 210  #define SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY (1 << 10)
 211  #define SECP256K1_FLAGS_BIT_COMPRESSION (1 << 8)
 212  
 213  /** Context flags to pass to secp256k1_context_create, secp256k1_context_preallocated_size, and
 214   *  secp256k1_context_preallocated_create. */
 215  #define SECP256K1_CONTEXT_NONE (SECP256K1_FLAGS_TYPE_CONTEXT)
 216  
 217  /** Deprecated context flags. These flags are treated equivalent to SECP256K1_CONTEXT_NONE. */
 218  #define SECP256K1_CONTEXT_VERIFY (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_VERIFY)
 219  #define SECP256K1_CONTEXT_SIGN (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_SIGN)
 220  
 221  /* Testing flag. Do not use. */
 222  #define SECP256K1_CONTEXT_DECLASSIFY (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY)
 223  
 224  /** Flag to pass to secp256k1_ec_pubkey_serialize. */
 225  #define SECP256K1_EC_COMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION | SECP256K1_FLAGS_BIT_COMPRESSION)
 226  #define SECP256K1_EC_UNCOMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION)
 227  
 228  /** Prefix byte used to tag various encoded curvepoints for specific purposes */
 229  #define SECP256K1_TAG_PUBKEY_EVEN 0x02
 230  #define SECP256K1_TAG_PUBKEY_ODD 0x03
 231  #define SECP256K1_TAG_PUBKEY_UNCOMPRESSED 0x04
 232  #define SECP256K1_TAG_PUBKEY_HYBRID_EVEN 0x06
 233  #define SECP256K1_TAG_PUBKEY_HYBRID_ODD 0x07
 234  
 235  /** A built-in constant secp256k1 context object with static storage duration, to be
 236   *  used in conjunction with secp256k1_selftest.
 237   *
 238   *  This context object offers *only limited functionality* , i.e., it cannot be used
 239   *  for API functions that perform computations involving secret keys, e.g., signing
 240   *  and public key generation. If this restriction applies to a specific API function,
 241   *  it is mentioned in its documentation. See secp256k1_context_create if you need a
 242   *  full context object that supports all functionality offered by the library.
 243   *
 244   *  It is highly recommended to call secp256k1_selftest before using this context.
 245   */
 246  SECP256K1_API const secp256k1_context * const secp256k1_context_static;
 247  
 248  /** Deprecated alias for secp256k1_context_static. */
 249  SECP256K1_API const secp256k1_context * const secp256k1_context_no_precomp
 250  SECP256K1_DEPRECATED("Use secp256k1_context_static instead");
 251  
 252  /** Perform basic self tests (to be used in conjunction with secp256k1_context_static)
 253   *
 254   *  This function performs self tests that detect some serious usage errors and
 255   *  similar conditions, e.g., when the library is compiled for the wrong endianness.
 256   *  This is a last resort measure to be used in production. The performed tests are
 257   *  very rudimentary and are not intended as a replacement for running the test
 258   *  binaries.
 259   *
 260   *  It is highly recommended to call this before using secp256k1_context_static.
 261   *  It is not necessary to call this function before using a context created with
 262   *  secp256k1_context_create (or secp256k1_context_preallocated_create), which will
 263   *  take care of performing the self tests.
 264   *
 265   *  If the tests fail, this function will call the default error callback to abort the
 266   *  program (see secp256k1_context_set_error_callback).
 267   */
 268  SECP256K1_API void secp256k1_selftest(void);
 269  
 270  
 271  /** Create a secp256k1 context object (in dynamically allocated memory).
 272   *
 273   *  This function uses malloc to allocate memory. It is guaranteed that malloc is
 274   *  called at most once for every call of this function. If you need to avoid dynamic
 275   *  memory allocation entirely, see secp256k1_context_static and the functions in
 276   *  secp256k1_preallocated.h.
 277   *
 278   *  Returns: pointer to a newly created context object.
 279   *  In:      flags: Always set to SECP256K1_CONTEXT_NONE (see below).
 280   *
 281   *  The only valid non-deprecated flag in recent library versions is
 282   *  SECP256K1_CONTEXT_NONE, which will create a context sufficient for all functionality
 283   *  offered by the library. All other (deprecated) flags will be treated as equivalent
 284   *  to the SECP256K1_CONTEXT_NONE flag. Though the flags parameter primarily exists for
 285   *  historical reasons, future versions of the library may introduce new flags.
 286   *
 287   *  If the context is intended to be used for API functions that perform computations
 288   *  involving secret keys, e.g., signing and public key generation, then it is highly
 289   *  recommended to call secp256k1_context_randomize on the context before calling
 290   *  those API functions. This will provide enhanced protection against side-channel
 291   *  leakage, see secp256k1_context_randomize for details.
 292   *
 293   *  Do not create a new context object for each operation, as construction and
 294   *  randomization can take non-negligible time.
 295   */
 296  SECP256K1_API secp256k1_context *secp256k1_context_create(
 297      unsigned int flags
 298  ) SECP256K1_WARN_UNUSED_RESULT;
 299  
 300  /** Copy a secp256k1 context object (into dynamically allocated memory).
 301   *
 302   *  This function uses malloc to allocate memory. It is guaranteed that malloc is
 303   *  called at most once for every call of this function. If you need to avoid dynamic
 304   *  memory allocation entirely, see the functions in secp256k1_preallocated.h.
 305   *
 306   *  Cloning secp256k1_context_static is not possible, and should not be emulated by
 307   *  the caller (e.g., using memcpy). Create a new context instead.
 308   *
 309   *  Returns: pointer to a newly created context object.
 310   *  Args:    ctx: pointer to a context to copy (not secp256k1_context_static).
 311   */
 312  SECP256K1_API secp256k1_context *secp256k1_context_clone(
 313      const secp256k1_context *ctx
 314  ) SECP256K1_ARG_NONNULL(1) SECP256K1_WARN_UNUSED_RESULT;
 315  
 316  /** Destroy a secp256k1 context object (created in dynamically allocated memory).
 317   *
 318   *  The context pointer may not be used afterwards.
 319   *
 320   *  The context to destroy must have been created using secp256k1_context_create
 321   *  or secp256k1_context_clone. If the context has instead been created using
 322   *  secp256k1_context_preallocated_create or secp256k1_context_preallocated_clone, the
 323   *  behaviour is undefined. In that case, secp256k1_context_preallocated_destroy must
 324   *  be used instead.
 325   *
 326   *  Args:   ctx: pointer to a context to destroy, constructed using
 327   *               secp256k1_context_create or secp256k1_context_clone
 328   *               (i.e., not secp256k1_context_static).
 329   */
 330  SECP256K1_API void secp256k1_context_destroy(
 331      secp256k1_context *ctx
 332  ) SECP256K1_ARG_NONNULL(1);
 333  
 334  /** Set a callback function to be called when an illegal argument is passed to
 335   *  an API call. It will only trigger for violations that are mentioned
 336   *  explicitly in the header.
 337   *
 338   *  The philosophy is that these shouldn't be dealt with through a specific
 339   *  return value, as calling code should not have branches to deal with the case
 340   *  that this code itself is broken.
 341   *
 342   *  On the other hand, during debug stage, one would want to be informed about
 343   *  such mistakes, and the default (crashing) may be inadvisable. Should this
 344   *  callback return instead of crashing, the return value and output arguments
 345   *  of the API function call are undefined. Moreover, the same API call may
 346   *  trigger the callback again in this case.
 347   *
 348   *  When this function has not been called (or called with fun==NULL), then the
 349   *  default callback will be used. The library provides a default callback which
 350   *  writes the message to stderr and calls abort. This default callback can be
 351   *  replaced at link time if the preprocessor macro
 352   *  USE_EXTERNAL_DEFAULT_CALLBACKS is defined, which is the case if the build
 353   *  has been configured with --enable-external-default-callbacks (GNU Autotools) or
 354   *  -DSECP256K1_USE_EXTERNAL_DEFAULT_CALLBACKS=ON (CMake). Then the
 355   *  following two symbols must be provided to link against:
 356   *   - void secp256k1_default_illegal_callback_fn(const char *message, void *data);
 357   *   - void secp256k1_default_error_callback_fn(const char *message, void *data);
 358   *  The library may call a default callback even before a proper callback data
 359   *  pointer could have been set using secp256k1_context_set_illegal_callback or
 360   *  secp256k1_context_set_error_callback, e.g., when the creation of a context
 361   *  fails. In this case, the corresponding default callback will be called with
 362   *  the data pointer argument set to NULL.
 363   *
 364   *  Args: ctx:  pointer to a context object.
 365   *  In:   fun:  pointer to a function to call when an illegal argument is
 366   *              passed to the API, taking a message and an opaque pointer.
 367   *              (NULL restores the default callback.)
 368   *        data: the opaque pointer to pass to fun above, must be NULL for the
 369   *              default callback.
 370   *
 371   *  See also secp256k1_context_set_error_callback.
 372   */
 373  SECP256K1_API void secp256k1_context_set_illegal_callback(
 374      secp256k1_context *ctx,
 375      void (*fun)(const char *message, void *data),
 376      const void *data
 377  ) SECP256K1_ARG_NONNULL(1);
 378  
 379  /** Set a callback function to be called when an internal consistency check
 380   *  fails.
 381   *
 382   *  The default callback writes an error message to stderr and calls abort
 383   *  to abort the program.
 384   *
 385   *  This can only trigger in case of a hardware failure, miscompilation,
 386   *  memory corruption, serious bug in the library, or other error that would
 387   *  result in undefined behaviour. It will not trigger due to mere
 388   *  incorrect usage of the API (see secp256k1_context_set_illegal_callback
 389   *  for that). After this callback returns, anything may happen, including
 390   *  crashing.
 391   *
 392   *  Args: ctx:  pointer to a context object.
 393   *  In:   fun:  pointer to a function to call when an internal error occurs,
 394   *              taking a message and an opaque pointer (NULL restores the
 395   *              default callback, see secp256k1_context_set_illegal_callback
 396   *              for details).
 397   *        data: the opaque pointer to pass to fun above, must be NULL for the
 398   *              default callback.
 399   *
 400   *  See also secp256k1_context_set_illegal_callback.
 401   */
 402  SECP256K1_API void secp256k1_context_set_error_callback(
 403      secp256k1_context *ctx,
 404      void (*fun)(const char *message, void *data),
 405      const void *data
 406  ) SECP256K1_ARG_NONNULL(1);
 407  
 408  /** A pointer to a function implementing SHA256's internal compression function.
 409   *
 410   * This function processes one or more contiguous 64-byte message blocks and
 411   * updates the internal SHA256 state accordingly. The function is not responsible
 412   * for counting consumed blocks or bytes, nor for performing padding.
 413   *
 414   * In/Out:  state:     pointer to eight 32-bit words representing the current internal state;
 415   *                     the state is updated in place.
 416   * In:      blocks64:  pointer to concatenation of n_blocks blocks, of 64 bytes each.
 417   *                     no alignment guarantees are made for this pointer.
 418   *          n_blocks:  number of contiguous 64-byte blocks to process.
 419   */
 420  typedef void (*secp256k1_sha256_compression_function)(
 421      uint32_t *state,
 422      const unsigned char *blocks64,
 423      size_t n_blocks
 424  );
 425  
 426  /**
 427   * Set a callback function to override the internal SHA256 compression function.
 428   *
 429   * This installs a function to replace the built-in block-compression
 430   * step used by the library's internal SHA256 implementation.
 431   * The provided callback must exactly implement the effect of n_blocks
 432   * repeated applications of the SHA256 compression function.
 433   *
 434   * This API exists to support environments that wish to route the
 435   * SHA256 compression step through a hardware-accelerated or otherwise
 436   * specialized implementation. It is NOT meant for replacing SHA256
 437   * with a different hash function.
 438   *
 439   * Args:    ctx:             pointer to a context object.
 440   * In:      fn_compression:  pointer to a function implementing the compression function;
 441   *                           passing NULL restores the default implementation.
 442   */
 443  SECP256K1_API void secp256k1_context_set_sha256_compression(
 444          secp256k1_context *ctx,
 445          secp256k1_sha256_compression_function fn_compression
 446  ) SECP256K1_ARG_NONNULL(1);
 447  
 448  /** Parse a variable-length public key into the pubkey object.
 449   *
 450   *  Returns: 1 if the public key was fully valid.
 451   *           0 if the public key could not be parsed or is invalid.
 452   *  Args: ctx:      pointer to a context object.
 453   *  Out:  pubkey:   pointer to a pubkey object. If 1 is returned, it is set to a
 454   *                  parsed version of input. If not, its value is undefined.
 455   *  In:   input:    pointer to a serialized public key
 456   *        inputlen: length of the array pointed to by input
 457   *
 458   *  This function supports parsing compressed (33 bytes, header byte 0x02 or
 459   *  0x03), uncompressed (65 bytes, header byte 0x04), or hybrid (65 bytes, header
 460   *  byte 0x06 or 0x07) format public keys.
 461   */
 462  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_parse(
 463      const secp256k1_context *ctx,
 464      secp256k1_pubkey *pubkey,
 465      const unsigned char *input,
 466      size_t inputlen
 467  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 468  
 469  /** Serialize a pubkey object into a serialized byte sequence.
 470   *
 471   *  Returns: 1 always.
 472   *  Args:   ctx:        pointer to a context object.
 473   *  Out:    output:     pointer to a 65-byte (if compressed==0) or 33-byte (if
 474   *                      compressed==1) byte array to place the serialized key
 475   *                      in.
 476   *  In/Out: outputlen:  pointer to an integer which is initially set to the
 477   *                      size of output, and is overwritten with the written
 478   *                      size.
 479   *  In:     pubkey:     pointer to a secp256k1_pubkey containing an
 480   *                      initialized public key.
 481   *          flags:      SECP256K1_EC_COMPRESSED if serialization should be in
 482   *                      compressed format, otherwise SECP256K1_EC_UNCOMPRESSED.
 483   */
 484  SECP256K1_API int secp256k1_ec_pubkey_serialize(
 485      const secp256k1_context *ctx,
 486      unsigned char *output,
 487      size_t *outputlen,
 488      const secp256k1_pubkey *pubkey,
 489      unsigned int flags
 490  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
 491  
 492  /** Compare two public keys using lexicographic (of compressed serialization) order
 493   *
 494   *  Returns: <0 if the first public key is less than the second
 495   *           >0 if the first public key is greater than the second
 496   *           0 if the two public keys are equal
 497   *  Args: ctx:      pointer to a context object
 498   *  In:   pubkey1:  first public key to compare
 499   *        pubkey2:  second public key to compare
 500   */
 501  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_cmp(
 502      const secp256k1_context *ctx,
 503      const secp256k1_pubkey *pubkey1,
 504      const secp256k1_pubkey *pubkey2
 505  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 506  
 507  /** Sort public keys using lexicographic (of compressed serialization) order
 508   *
 509   *  Returns: 0 if the arguments are invalid. 1 otherwise.
 510   *
 511   *  Args:     ctx: pointer to a context object
 512   *  In:   pubkeys: array of pointers to pubkeys to sort
 513   *      n_pubkeys: number of elements in the pubkeys array
 514   */
 515  SECP256K1_API int secp256k1_ec_pubkey_sort(
 516      const secp256k1_context *ctx,
 517      const secp256k1_pubkey **pubkeys,
 518      size_t n_pubkeys
 519  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
 520  
 521  /** Parse an ECDSA signature in compact (64 bytes) format.
 522   *
 523   *  Returns: 1 when the signature could be parsed, 0 otherwise.
 524   *  Args: ctx:      pointer to a context object
 525   *  Out:  sig:      pointer to a signature object
 526   *  In:   input64:  pointer to the 64-byte array to parse
 527   *
 528   *  The signature must consist of a 32-byte big endian R value, followed by a
 529   *  32-byte big endian S value. If R or S fall outside of [0..order-1], the
 530   *  encoding is invalid. R and S with value 0 are allowed in the encoding.
 531   *
 532   *  After the call, sig will always be initialized. If parsing failed or R or
 533   *  S are zero, the resulting sig value is guaranteed to fail verification for
 534   *  any message and public key.
 535   */
 536  SECP256K1_API int secp256k1_ecdsa_signature_parse_compact(
 537      const secp256k1_context *ctx,
 538      secp256k1_ecdsa_signature *sig,
 539      const unsigned char *input64
 540  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 541  
 542  /** Parse a DER ECDSA signature.
 543   *
 544   *  Returns: 1 when the signature could be parsed, 0 otherwise.
 545   *  Args: ctx:      pointer to a context object
 546   *  Out:  sig:      pointer to a signature object
 547   *  In:   input:    pointer to the signature to be parsed
 548   *        inputlen: the length of the array pointed to be input
 549   *
 550   *  This function will accept any valid DER encoded signature, even if the
 551   *  encoded numbers are out of range.
 552   *
 553   *  After the call, sig will always be initialized. If parsing failed or the
 554   *  encoded numbers are out of range, signature verification with it is
 555   *  guaranteed to fail for every message and public key.
 556   */
 557  SECP256K1_API int secp256k1_ecdsa_signature_parse_der(
 558      const secp256k1_context *ctx,
 559      secp256k1_ecdsa_signature *sig,
 560      const unsigned char *input,
 561      size_t inputlen
 562  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 563  
 564  /** Serialize an ECDSA signature in DER format.
 565   *
 566   *  Returns: 1 if enough space was available to serialize, 0 otherwise
 567   *  Args:   ctx:       pointer to a context object
 568   *  Out:    output:    pointer to an array to store the DER serialization
 569   *  In/Out: outputlen: pointer to a length integer. Initially, this integer
 570   *                     should be set to the length of output. After the call
 571   *                     it will be set to the length of the serialization (even
 572   *                     if 0 was returned).
 573   *  In:     sig:       pointer to an initialized signature object
 574   */
 575  SECP256K1_API int secp256k1_ecdsa_signature_serialize_der(
 576      const secp256k1_context *ctx,
 577      unsigned char *output,
 578      size_t *outputlen,
 579      const secp256k1_ecdsa_signature *sig
 580  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
 581  
 582  /** Serialize an ECDSA signature in compact (64 byte) format.
 583   *
 584   *  Returns: 1
 585   *  Args:   ctx:       pointer to a context object
 586   *  Out:    output64:  pointer to a 64-byte array to store the compact serialization
 587   *  In:     sig:       pointer to an initialized signature object
 588   *
 589   *  See secp256k1_ecdsa_signature_parse_compact for details about the encoding.
 590   */
 591  SECP256K1_API int secp256k1_ecdsa_signature_serialize_compact(
 592      const secp256k1_context *ctx,
 593      unsigned char *output64,
 594      const secp256k1_ecdsa_signature *sig
 595  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 596  
 597  /** Verify an ECDSA signature.
 598   *
 599   *  Returns: 1: correct signature
 600   *           0: incorrect or unparseable signature
 601   *  Args:    ctx:       pointer to a context object
 602   *  In:      sig:       the signature being verified.
 603   *           msghash32: the 32-byte message hash being verified.
 604   *                      The verifier must make sure to apply a cryptographic
 605   *                      hash function to the message by itself and not accept an
 606   *                      msghash32 value directly. Otherwise, it would be easy to
 607   *                      create a "valid" signature without knowledge of the
 608   *                      secret key. See also
 609   *                      https://bitcoin.stackexchange.com/a/81116/35586 for more
 610   *                      background on this topic.
 611   *           pubkey:    pointer to an initialized public key to verify with.
 612   *
 613   * To avoid accepting malleable signatures, only ECDSA signatures in lower-S
 614   * form are accepted.
 615   *
 616   * If you need to accept ECDSA signatures from sources that do not obey this
 617   * rule, apply secp256k1_ecdsa_signature_normalize to the signature prior to
 618   * verification, but be aware that doing so results in malleable signatures.
 619   *
 620   * For details, see the comments for that function.
 621   */
 622  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_verify(
 623      const secp256k1_context *ctx,
 624      const secp256k1_ecdsa_signature *sig,
 625      const unsigned char *msghash32,
 626      const secp256k1_pubkey *pubkey
 627  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
 628  
 629  /** Convert a signature to a normalized lower-S form.
 630   *
 631   *  Returns: 1 if sigin was not normalized, 0 if it already was.
 632   *  Args: ctx:    pointer to a context object
 633   *  Out:  sigout: pointer to a signature to fill with the normalized form,
 634   *                or copy if the input was already normalized. (can be NULL if
 635   *                you're only interested in whether the input was already
 636   *                normalized).
 637   *  In:   sigin:  pointer to a signature to check/normalize (can be identical to sigout)
 638   *
 639   *  With ECDSA a third-party can forge a second distinct signature of the same
 640   *  message, given a single initial signature, but without knowing the key. This
 641   *  is done by negating the S value modulo the order of the curve, 'flipping'
 642   *  the sign of the random point R which is not included in the signature.
 643   *
 644   *  Forgery of the same message isn't universally problematic, but in systems
 645   *  where message malleability or uniqueness of signatures is important this can
 646   *  cause issues. This forgery can be blocked by all verifiers forcing signers
 647   *  to use a normalized form.
 648   *
 649   *  The lower-S form reduces the size of signatures slightly on average when
 650   *  variable length encodings (such as DER) are used and is cheap to verify,
 651   *  making it a good choice. Security of always using lower-S is assured because
 652   *  anyone can trivially modify a signature after the fact to enforce this
 653   *  property anyway.
 654   *
 655   *  The lower S value is always between 0x1 and
 656   *  0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
 657   *  inclusive.
 658   *
 659   *  No other forms of ECDSA malleability are known and none seem likely, but
 660   *  there is no formal proof that ECDSA, even with this additional restriction,
 661   *  is free of other malleability. Commonly used serialization schemes will also
 662   *  accept various non-unique encodings, so care should be taken when this
 663   *  property is required for an application.
 664   *
 665   *  The secp256k1_ecdsa_sign function will by default create signatures in the
 666   *  lower-S form, and secp256k1_ecdsa_verify will not accept others. In case
 667   *  signatures come from a system that cannot enforce this property,
 668   *  secp256k1_ecdsa_signature_normalize must be called before verification.
 669   */
 670  SECP256K1_API int secp256k1_ecdsa_signature_normalize(
 671      const secp256k1_context *ctx,
 672      secp256k1_ecdsa_signature *sigout,
 673      const secp256k1_ecdsa_signature *sigin
 674  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3);
 675  
 676  /** An implementation of RFC6979 (using HMAC-SHA256) as nonce generation function.
 677   * If a data pointer is passed, it is assumed to be a pointer to 32 bytes of
 678   * extra entropy.
 679   */
 680  SECP256K1_API const secp256k1_nonce_function secp256k1_nonce_function_rfc6979;
 681  
 682  /** A default safe nonce generation function (currently equal to secp256k1_nonce_function_rfc6979). */
 683  SECP256K1_API const secp256k1_nonce_function secp256k1_nonce_function_default;
 684  
 685  /** Create an ECDSA signature.
 686   *
 687   *  Returns: 1: signature created
 688   *           0: the nonce generation function failed, or the secret key was invalid.
 689   *  Args:    ctx:       pointer to a context object (not secp256k1_context_static).
 690   *  Out:     sig:       pointer to a signature object.
 691   *  In:      msghash32: the 32-byte message hash being signed.
 692   *           seckey:    pointer to a 32-byte secret key.
 693   *           noncefp:   pointer to a nonce generation function. If NULL,
 694   *                      secp256k1_nonce_function_default is used.
 695   *           ndata:     pointer to arbitrary data used by the nonce generation function
 696   *                      (can be NULL). If it is non-NULL and
 697   *                      secp256k1_nonce_function_default is used, then ndata must be a
 698   *                      pointer to 32-bytes of additional data.
 699   *
 700   * The created signature is always in lower-S form. See
 701   * secp256k1_ecdsa_signature_normalize for more details.
 702   */
 703  SECP256K1_API int secp256k1_ecdsa_sign(
 704      const secp256k1_context *ctx,
 705      secp256k1_ecdsa_signature *sig,
 706      const unsigned char *msghash32,
 707      const unsigned char *seckey,
 708      secp256k1_nonce_function noncefp,
 709      const void *ndata
 710  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
 711  
 712  /** Verify an elliptic curve secret key.
 713   *
 714   *  A secret key is valid if it is not 0 and less than the secp256k1 curve order
 715   *  when interpreted as an integer (most significant byte first). The
 716   *  probability of choosing a 32-byte string uniformly at random which is an
 717   *  invalid secret key is negligible. However, if it does happen it should
 718   *  be assumed that the randomness source is severely broken and there should
 719   *  be no retry.
 720   *
 721   *  Returns: 1: secret key is valid
 722   *           0: secret key is invalid
 723   *  Args:    ctx: pointer to a context object.
 724   *  In:      seckey: pointer to a 32-byte secret key.
 725   */
 726  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_verify(
 727      const secp256k1_context *ctx,
 728      const unsigned char *seckey
 729  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
 730  
 731  /** Compute the public key for a secret key.
 732   *
 733   *  Returns: 1: secret was valid, public key stores.
 734   *           0: secret was invalid, try again.
 735   *  Args:    ctx:    pointer to a context object (not secp256k1_context_static).
 736   *  Out:     pubkey: pointer to the created public key.
 737   *  In:      seckey: pointer to a 32-byte secret key.
 738   */
 739  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_create(
 740      const secp256k1_context *ctx,
 741      secp256k1_pubkey *pubkey,
 742      const unsigned char *seckey
 743  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 744  
 745  /** Negates a secret key in place.
 746   *
 747   *  Returns: 0 if the given secret key is invalid according to
 748   *           secp256k1_ec_seckey_verify. 1 otherwise
 749   *  Args:   ctx:    pointer to a context object
 750   *  In/Out: seckey: pointer to the 32-byte secret key to be negated. If the
 751   *                  secret key is invalid according to
 752   *                  secp256k1_ec_seckey_verify, this function returns 0 and
 753   *                  seckey will be set to some unspecified value.
 754   */
 755  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_negate(
 756      const secp256k1_context *ctx,
 757      unsigned char *seckey
 758  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
 759  
 760  /** Negates a public key in place.
 761   *
 762   *  Returns: 1 always
 763   *  Args:   ctx:        pointer to a context object
 764   *  In/Out: pubkey:     pointer to the public key to be negated.
 765   */
 766  SECP256K1_API int secp256k1_ec_pubkey_negate(
 767      const secp256k1_context *ctx,
 768      secp256k1_pubkey *pubkey
 769  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
 770  
 771  /** Tweak a secret key by adding tweak to it.
 772   *
 773   *  Returns: 0 if the arguments are invalid or the resulting secret key would be
 774   *           invalid (only when the tweak is the negation of the secret key). 1
 775   *           otherwise.
 776   *  Args:    ctx:   pointer to a context object.
 777   *  In/Out: seckey: pointer to a 32-byte secret key. If the secret key is
 778   *                  invalid according to secp256k1_ec_seckey_verify, this
 779   *                  function returns 0. seckey will be set to some unspecified
 780   *                  value if this function returns 0.
 781   *  In:    tweak32: pointer to a 32-byte tweak, which must be valid according to
 782   *                  secp256k1_ec_seckey_verify or 32 zero bytes. For uniformly
 783   *                  random 32-byte tweaks, the chance of being invalid is
 784   *                  negligible (around 1 in 2^128).
 785   */
 786  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_tweak_add(
 787      const secp256k1_context *ctx,
 788      unsigned char *seckey,
 789      const unsigned char *tweak32
 790  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 791  
 792  /** Tweak a public key by adding tweak times the generator to it.
 793   *
 794   *  Returns: 0 if the arguments are invalid or the resulting public key would be
 795   *           invalid (only when the tweak is the negation of the corresponding
 796   *           secret key). 1 otherwise.
 797   *  Args:    ctx:   pointer to a context object.
 798   *  In/Out: pubkey: pointer to a public key object. pubkey will be set to an
 799   *                  invalid value if this function returns 0.
 800   *  In:    tweak32: pointer to a 32-byte tweak, which must be valid according to
 801   *                  secp256k1_ec_seckey_verify or 32 zero bytes. For uniformly
 802   *                  random 32-byte tweaks, the chance of being invalid is
 803   *                  negligible (around 1 in 2^128).
 804   */
 805  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_add(
 806      const secp256k1_context *ctx,
 807      secp256k1_pubkey *pubkey,
 808      const unsigned char *tweak32
 809  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 810  
 811  /** Tweak a secret key by multiplying it by a tweak.
 812   *
 813   *  Returns: 0 if the arguments are invalid. 1 otherwise.
 814   *  Args:   ctx:    pointer to a context object.
 815   *  In/Out: seckey: pointer to a 32-byte secret key. If the secret key is
 816   *                  invalid according to secp256k1_ec_seckey_verify, this
 817   *                  function returns 0. seckey will be set to some unspecified
 818   *                  value if this function returns 0.
 819   *  In:    tweak32: pointer to a 32-byte tweak. If the tweak is invalid according to
 820   *                  secp256k1_ec_seckey_verify, this function returns 0. For
 821   *                  uniformly random 32-byte arrays the chance of being invalid
 822   *                  is negligible (around 1 in 2^128).
 823   */
 824  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_tweak_mul(
 825      const secp256k1_context *ctx,
 826      unsigned char *seckey,
 827      const unsigned char *tweak32
 828  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 829  
 830  /** Tweak a public key by multiplying it by a tweak value.
 831   *
 832   *  Returns: 0 if the arguments are invalid. 1 otherwise.
 833   *  Args:    ctx:   pointer to a context object.
 834   *  In/Out: pubkey: pointer to a public key object. pubkey will be set to an
 835   *                  invalid value if this function returns 0.
 836   *  In:    tweak32: pointer to a 32-byte tweak. If the tweak is invalid according to
 837   *                  secp256k1_ec_seckey_verify, this function returns 0. For
 838   *                  uniformly random 32-byte arrays the chance of being invalid
 839   *                  is negligible (around 1 in 2^128).
 840   */
 841  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_mul(
 842      const secp256k1_context *ctx,
 843      secp256k1_pubkey *pubkey,
 844      const unsigned char *tweak32
 845  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 846  
 847  /** Randomizes the context to provide enhanced protection against side-channel leakage.
 848   *
 849   *  Returns: 1: randomization successful
 850   *           0: error
 851   *  Args:    ctx:       pointer to a context object (not secp256k1_context_static).
 852   *  In:      seed32:    pointer to a 32-byte random seed (NULL resets to initial state).
 853   *
 854   * While secp256k1 code is written and tested to be constant-time no matter what
 855   * secret values are, it is possible that a compiler may output code which is not,
 856   * and also that the CPU may not emit the same radio frequencies or draw the same
 857   * amount of power for all values. Randomization of the context shields against
 858   * side-channel observations which aim to exploit secret-dependent behaviour in
 859   * certain computations which involve secret keys.
 860   *
 861   * It is highly recommended to call this function on contexts returned from
 862   * secp256k1_context_create or secp256k1_context_clone (or from the corresponding
 863   * functions in secp256k1_preallocated.h) before using these contexts to call API
 864   * functions that perform computations involving secret keys, e.g., signing and
 865   * public key generation. It is possible to call this function more than once on
 866   * the same context, and doing so before every few computations involving secret
 867   * keys is recommended as a defense-in-depth measure. Randomization of the static
 868   * context secp256k1_context_static is not supported.
 869   *
 870   * Currently, the random seed is mainly used for blinding multiplications of a
 871   * secret scalar with the elliptic curve base point. Multiplications of this
 872   * kind are performed by exactly those API functions which are documented to
 873   * require a context that is not secp256k1_context_static. As a rule of thumb,
 874   * these are all functions which take a secret key (or a keypair) as an input.
 875   * A notable exception to that rule is the ECDH module, which relies on a different
 876   * kind of elliptic curve point multiplication and thus does not benefit from
 877   * enhanced protection against side-channel leakage currently.
 878   */
 879  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_context_randomize(
 880      secp256k1_context *ctx,
 881      const unsigned char *seed32
 882  ) SECP256K1_ARG_NONNULL(1);
 883  
 884  /** Add a number of public keys together.
 885   *
 886   *  Returns: 1: the sum of the public keys is valid.
 887   *           0: the sum of the public keys is not valid.
 888   *  Args:   ctx:        pointer to a context object.
 889   *  Out:    out:        pointer to a public key object for placing the resulting public key.
 890   *  In:     ins:        pointer to array of pointers to public keys.
 891   *          n:          the number of public keys to add together (must be at least 1).
 892   */
 893  SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine(
 894      const secp256k1_context *ctx,
 895      secp256k1_pubkey *out,
 896      const secp256k1_pubkey * const *ins,
 897      size_t n
 898  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
 899  
 900  /** Compute a tagged hash as defined in BIP-340.
 901   *
 902   *  This is useful for creating a message hash and achieving domain separation
 903   *  through an application-specific tag. This function returns
 904   *  SHA256(SHA256(tag)||SHA256(tag)||msg). Therefore, tagged hash
 905   *  implementations optimized for a specific tag can precompute the SHA256 state
 906   *  after hashing the tag hashes.
 907   *
 908   *  Returns: 1 always.
 909   *  Args:    ctx: pointer to a context object
 910   *  Out:  hash32: pointer to a 32-byte array to store the resulting hash
 911   *  In:      tag: pointer to an array containing the tag
 912   *        taglen: length of the tag array
 913   *           msg: pointer to an array containing the message
 914   *        msglen: length of the message array
 915   */
 916  SECP256K1_API int secp256k1_tagged_sha256(
 917      const secp256k1_context *ctx,
 918      unsigned char *hash32,
 919      const unsigned char *tag,
 920      size_t taglen,
 921      const unsigned char *msg,
 922      size_t msglen
 923  ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5);
 924  
 925  #ifdef __cplusplus
 926  }
 927  #endif
 928  
 929  #endif /* SECP256K1_H */
 930