Bitcoin Core  24.99.0
P2P Digital Currency
schnorr.c
Go to the documentation of this file.
1 /*************************************************************************
2  * Written in 2020-2022 by Elichai Turkel *
3  * To the extent possible under law, the author(s) have dedicated all *
4  * copyright and related and neighboring rights to the software in this *
5  * file to the public domain worldwide. This software is distributed *
6  * without any warranty. For the CC0 Public Domain Dedication, see *
7  * EXAMPLES_COPYING or https://creativecommons.org/publicdomain/zero/1.0 *
8  *************************************************************************/
9 
10 #include <stdio.h>
11 #include <assert.h>
12 #include <string.h>
13 
14 #include <secp256k1.h>
15 #include <secp256k1_extrakeys.h>
16 #include <secp256k1_schnorrsig.h>
17 
18 #include "random.h"
19 
20 int main(void) {
21  unsigned char msg[12] = "Hello World!";
22  unsigned char msg_hash[32];
23  unsigned char tag[17] = "my_fancy_protocol";
24  unsigned char seckey[32];
25  unsigned char randomize[32];
26  unsigned char auxiliary_rand[32];
27  unsigned char serialized_pubkey[32];
28  unsigned char signature[64];
29  int is_signature_valid;
30  int return_val;
32  secp256k1_keypair keypair;
33  /* The specification in secp256k1_extrakeys.h states that `secp256k1_keypair_create`
34  * needs a context object initialized for signing. And in secp256k1_schnorrsig.h
35  * they state that `secp256k1_schnorrsig_verify` needs a context initialized for
36  * verification, which is why we create a context for both signing and verification
37  * with the SECP256K1_CONTEXT_SIGN and SECP256K1_CONTEXT_VERIFY flags. */
39  if (!fill_random(randomize, sizeof(randomize))) {
40  printf("Failed to generate randomness\n");
41  return 1;
42  }
43  /* Randomizing the context is recommended to protect against side-channel
44  * leakage See `secp256k1_context_randomize` in secp256k1.h for more
45  * information about it. This should never fail. */
46  return_val = secp256k1_context_randomize(ctx, randomize);
47  assert(return_val);
48 
49  /*** Key Generation ***/
50 
51  /* If the secret key is zero or out of range (bigger than secp256k1's
52  * order), we try to sample a new key. Note that the probability of this
53  * happening is negligible. */
54  while (1) {
55  if (!fill_random(seckey, sizeof(seckey))) {
56  printf("Failed to generate randomness\n");
57  return 1;
58  }
59  /* Try to create a keypair with a valid context, it should only fail if
60  * the secret key is zero or out of range. */
61  if (secp256k1_keypair_create(ctx, &keypair, seckey)) {
62  break;
63  }
64  }
65 
66  /* Extract the X-only public key from the keypair. We pass NULL for
67  * `pk_parity` as the parity isn't needed for signing or verification.
68  * `secp256k1_keypair_xonly_pub` supports returning the parity for
69  * other use cases such as tests or verifying Taproot tweaks.
70  * This should never fail with a valid context and public key. */
71  return_val = secp256k1_keypair_xonly_pub(ctx, &pubkey, NULL, &keypair);
72  assert(return_val);
73 
74  /* Serialize the public key. Should always return 1 for a valid public key. */
75  return_val = secp256k1_xonly_pubkey_serialize(ctx, serialized_pubkey, &pubkey);
76  assert(return_val);
77 
78  /*** Signing ***/
79 
80  /* Instead of signing (possibly very long) messages directly, we sign a
81  * 32-byte hash of the message in this example.
82  *
83  * We use secp256k1_tagged_sha256 to create this hash. This function expects
84  * a context-specific "tag", which restricts the context in which the signed
85  * messages should be considered valid. For example, if protocol A mandates
86  * to use the tag "my_fancy_protocol" and protocol B mandates to use the tag
87  * "my_boring_protocol", then signed messages from protocol A will never be
88  * valid in protocol B (and vice versa), even if keys are reused across
89  * protocols. This implements "domain separation", which is considered good
90  * practice. It avoids attacks in which users are tricked into signing a
91  * message that has intended consequences in the intended context (e.g.,
92  * protocol A) but would have unintended consequences if it were valid in
93  * some other context (e.g., protocol B). */
94  return_val = secp256k1_tagged_sha256(ctx, msg_hash, tag, sizeof(tag), msg, sizeof(msg));
95  assert(return_val);
96 
97  /* Generate 32 bytes of randomness to use with BIP-340 schnorr signing. */
98  if (!fill_random(auxiliary_rand, sizeof(auxiliary_rand))) {
99  printf("Failed to generate randomness\n");
100  return 1;
101  }
102 
103  /* Generate a Schnorr signature.
104  *
105  * We use the secp256k1_schnorrsig_sign32 function that provides a simple
106  * interface for signing 32-byte messages (which in our case is a hash of
107  * the actual message). BIP-340 recommends passing 32 bytes of randomness
108  * to the signing function to improve security against side-channel attacks.
109  * Signing with a valid context, a 32-byte message, a verified keypair, and
110  * any 32 bytes of auxiliary random data should never fail. */
111  return_val = secp256k1_schnorrsig_sign32(ctx, signature, msg_hash, &keypair, auxiliary_rand);
112  assert(return_val);
113 
114  /*** Verification ***/
115 
116  /* Deserialize the public key. This will return 0 if the public key can't
117  * be parsed correctly */
118  if (!secp256k1_xonly_pubkey_parse(ctx, &pubkey, serialized_pubkey)) {
119  printf("Failed parsing the public key\n");
120  return 1;
121  }
122 
123  /* Compute the tagged hash on the received messages using the same tag as the signer. */
124  return_val = secp256k1_tagged_sha256(ctx, msg_hash, tag, sizeof(tag), msg, sizeof(msg));
125  assert(return_val);
126 
127  /* Verify a signature. This will return 1 if it's valid and 0 if it's not. */
128  is_signature_valid = secp256k1_schnorrsig_verify(ctx, signature, msg_hash, 32, &pubkey);
129 
130 
131  printf("Is the signature valid? %s\n", is_signature_valid ? "true" : "false");
132  printf("Secret Key: ");
133  print_hex(seckey, sizeof(seckey));
134  printf("Public Key: ");
135  print_hex(serialized_pubkey, sizeof(serialized_pubkey));
136  printf("Signature: ");
137  print_hex(signature, sizeof(signature));
138 
139  /* This will clear everything from the context and free the memory */
141 
142  /* It's best practice to try to clear secrets from memory after using them.
143  * This is done because some bugs can allow an attacker to leak memory, for
144  * example through "out of bounds" array access (see Heartbleed), Or the OS
145  * swapping them to disk. Hence, we overwrite the secret key buffer with zeros.
146  *
147  * TODO: Prevent these writes from being optimized out, as any good compiler
148  * will remove any writes that aren't used. */
149  memset(seckey, 0, sizeof(seckey));
150 
151  return 0;
152 }
void printf(const char *fmt, const Args &... args)
Format list of arguments to std::cout, according to the given format string.
Definition: tinyformat.h:1079
int main(void)
Definition: schnorr.c:20
static int fill_random(unsigned char *data, size_t size)
Definition: random.h:37
static void print_hex(unsigned char *data, size_t size)
Definition: random.h:66
SECP256K1_API void secp256k1_context_destroy(secp256k1_context *ctx) SECP256K1_ARG_NONNULL(1)
Destroy a secp256k1 context object (created in dynamically allocated memory).
Definition: secp256k1.c:146
#define SECP256K1_CONTEXT_SIGN
Definition: secp256k1.h:200
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_context_randomize(secp256k1_context *ctx, const unsigned char *seed32) SECP256K1_ARG_NONNULL(1)
Updates the context randomization to protect against side-channel leakage.
Definition: secp256k1.c:706
SECP256K1_API secp256k1_context * secp256k1_context_create(unsigned int flags) SECP256K1_WARN_UNUSED_RESULT
Create a secp256k1 context object (in dynamically allocated memory).
Definition: secp256k1.c:107
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_tagged_sha256(const secp256k1_context *ctx, unsigned char *hash32, const unsigned char *tag, size_t taglen, const unsigned char *msg, size_t msglen) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5)
Compute a tagged hash as defined in BIP-340.
Definition: secp256k1.c:740
#define SECP256K1_CONTEXT_VERIFY
Flags to pass to secp256k1_context_create, secp256k1_context_preallocated_size, and secp256k1_context...
Definition: secp256k1.h:199
SECP256K1_API int secp256k1_xonly_pubkey_serialize(const secp256k1_context *ctx, unsigned char *output32, const secp256k1_xonly_pubkey *pubkey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Serialize an xonly_pubkey object into a 32-byte sequence.
Definition: main_impl.h:43
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_create(const secp256k1_context *ctx, secp256k1_keypair *keypair, const unsigned char *seckey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Compute the keypair for a secret key.
Definition: main_impl.h:195
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_xonly_pub(const secp256k1_context *ctx, secp256k1_xonly_pubkey *pubkey, int *pk_parity, const secp256k1_keypair *keypair) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4)
Get the x-only public key from a keypair.
Definition: main_impl.h:233
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_parse(const secp256k1_context *ctx, secp256k1_xonly_pubkey *pubkey, const unsigned char *input32) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
Parse a 32-byte sequence into a xonly_pubkey object.
Definition: main_impl.h:21
SECP256K1_API int secp256k1_schnorrsig_sign32(const secp256k1_context *ctx, unsigned char *sig64, const unsigned char *msg32, const secp256k1_keypair *keypair, const unsigned char *aux_rand32) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4)
Create a Schnorr signature.
Definition: main_impl.h:195
SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_schnorrsig_verify(const secp256k1_context *ctx, const unsigned char *sig64, const unsigned char *msg, size_t msglen, const secp256k1_xonly_pubkey *pubkey) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(5)
Verify a Schnorr signature.
Definition: main_impl.h:219
Opaque data structure that holds a keypair consisting of a secret and a public key.
Opaque data structure that holds a parsed and valid "x-only" public key.
static secp256k1_context * ctx
Definition: tests.c:34
assert(!tx.IsCoinBase())