Skip to content

Commit b0cfbcc

Browse files
elichaijonasnick
andcommitted
Add a Schnorr signing and verifying example
Co-authored-by: Jonas Nick <jonasd.nick@gmail.com>
1 parent fee7d4b commit b0cfbcc

File tree

1 file changed

+136
-0
lines changed

1 file changed

+136
-0
lines changed

examples/schnorr.c

+136
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,136 @@
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+
/* Instead of signing the message directly, we must sign a 32-byte hash.
22+
* Here the message is "Hello, world!" and the hash function was SHA-256.
23+
* An actual implementation should just call SHA-256, but this example
24+
* hardcodes the output to avoid depending on an additional library. */
25+
unsigned char msg_hash[32] = {
26+
0x31, 0x5F, 0x5B, 0xDB, 0x76, 0xD0, 0x78, 0xC4,
27+
0x3B, 0x8A, 0xC0, 0x06, 0x4E, 0x4A, 0x01, 0x64,
28+
0x61, 0x2B, 0x1F, 0xCE, 0x77, 0xC8, 0x69, 0x34,
29+
0x5B, 0xFC, 0x94, 0xC7, 0x58, 0x94, 0xED, 0xD3,
30+
};
31+
unsigned char seckey[32];
32+
unsigned char randomize[32];
33+
unsigned char auxiliary_rand[32];
34+
unsigned char serialized_pubkey[32];
35+
unsigned char signature[64];
36+
int is_signature_valid;
37+
int return_val;
38+
secp256k1_xonly_pubkey pubkey;
39+
secp256k1_keypair keypair;
40+
/* The specification in secp256k1_extrakeys.h states that `secp256k1_keypair_create`
41+
* needs a context object initialized for signing. And in secp256k1_schnorrsig.h
42+
* they state that `secp256k1_schnorrsig_verify` needs a context initialized for
43+
* verification, which is why we create a context for both signing and verification
44+
* with the SECP256K1_CONTEXT_SIGN and SECP256K1_CONTEXT_VERIFY flags. */
45+
secp256k1_context* ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN | SECP256K1_CONTEXT_VERIFY);
46+
if (!fill_random(randomize, sizeof(randomize))) {
47+
printf("Failed to generate randomness\n");
48+
return 1;
49+
}
50+
/* Randomizing the context is recommended to protect against side-channel
51+
* leakage See `secp256k1_context_randomize` in secp256k1.h for more
52+
* information about it. This should never fail. */
53+
return_val = secp256k1_context_randomize(ctx, randomize);
54+
assert(return_val);
55+
56+
/*** Key Generation ***/
57+
58+
/* If the secret key is zero or out of range (bigger than secp256k1's
59+
* order), we try to sample a new key. Note that the probability of this
60+
* happening is negligible. */
61+
while (1) {
62+
if (!fill_random(seckey, sizeof(seckey))) {
63+
printf("Failed to generate randomness\n");
64+
return 1;
65+
}
66+
/* Try to create a keypair with a valid context, it should only fail if
67+
* the secret key is zero or out of range. */
68+
if (secp256k1_keypair_create(ctx, &keypair, seckey)) {
69+
break;
70+
}
71+
}
72+
73+
/* Extract the X-only public key from the keypair. We pass NULL for
74+
* `pk_parity` as the parity isn't needed for signing or verification.
75+
* `secp256k1_keypair_xonly_pub` supports returning the parity for
76+
* other use cases such as tests or verifying Taproot tweaks.
77+
* This should never fail with a valid context and public key. */
78+
return_val = secp256k1_keypair_xonly_pub(ctx, &pubkey, NULL, &keypair);
79+
assert(return_val);
80+
81+
/* Serialize the public key. Should always return 1 for a valid public key. */
82+
return_val = secp256k1_xonly_pubkey_serialize(ctx, serialized_pubkey, &pubkey);
83+
assert(return_val);
84+
85+
/*** Signing ***/
86+
87+
/* Generate 32 bytes of randomness to use with BIP-340 schnorr signing. */
88+
if (!fill_random(auxiliary_rand, sizeof(auxiliary_rand))) {
89+
printf("Failed to generate randomness\n");
90+
return 1;
91+
}
92+
93+
/* Generate a Schnorr signature `noncefp` and `ndata` allows you to pass a
94+
* custom nonce function, passing `NULL` will use the BIP-340 safe default.
95+
* BIP-340 recommends passing 32 bytes of randomness to the nonce function to
96+
* improve security against side-channel attacks. Signing with a valid
97+
* context, verified keypair and the default nonce function should never
98+
* fail. */
99+
return_val = secp256k1_schnorrsig_sign(ctx, signature, msg_hash, &keypair, auxiliary_rand);
100+
assert(return_val);
101+
102+
/*** Verification ***/
103+
104+
/* Deserialize the public key. This will return 0 if the public key can't
105+
* be parsed correctly */
106+
if (!secp256k1_xonly_pubkey_parse(ctx, &pubkey, serialized_pubkey)) {
107+
printf("Failed parsing the public key\n");
108+
return 1;
109+
}
110+
111+
/* Verify a signature. This will return 1 if it's valid and 0 if it's not. */
112+
is_signature_valid = secp256k1_schnorrsig_verify(ctx, signature, msg_hash, 32, &pubkey);
113+
114+
115+
printf("Is the signature valid? %s\n", is_signature_valid ? "true" : "false");
116+
printf("Secret Key: ");
117+
print_hex(seckey, sizeof(seckey));
118+
printf("Public Key: ");
119+
print_hex(serialized_pubkey, sizeof(serialized_pubkey));
120+
printf("Signature: ");
121+
print_hex(signature, sizeof(signature));
122+
123+
/* This will clear everything from the context and free the memory */
124+
secp256k1_context_destroy(ctx);
125+
126+
/* It's best practice to try to clear secrets from memory after using them.
127+
* This is done because some bugs can allow an attacker to leak memory, for
128+
* example through "out of bounds" array access (see Heartbleed), Or the OS
129+
* swapping them to disk. Hence, we overwrite the secret key buffer with zeros.
130+
*
131+
* TODO: Prevent these writes from being optimized out, as any good compiler
132+
* will remove any writes that aren't used. */
133+
memset(seckey, 0, sizeof(seckey));
134+
135+
return 0;
136+
}

0 commit comments

Comments
 (0)