Coverage Report

Created: 2026-04-29 19:21

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/key.cpp
Line
Count
Source
1
// Copyright (c) 2009-present The Bitcoin Core developers
2
// Copyright (c) 2017 The Zcash developers
3
// Distributed under the MIT software license, see the accompanying
4
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6
#include <key.h>
7
8
#include <crypto/common.h>
9
#include <crypto/hmac_sha512.h>
10
#include <hash.h>
11
#include <random.h>
12
13
#include <secp256k1.h>
14
#include <secp256k1_ellswift.h>
15
#include <secp256k1_extrakeys.h>
16
#include <secp256k1_musig.h>
17
#include <secp256k1_recovery.h>
18
#include <secp256k1_schnorrsig.h>
19
20
static secp256k1_context* secp256k1_context_sign = nullptr;
21
22
/** These functions are taken from the libsecp256k1 distribution and are very ugly. */
23
24
/**
25
 * This parses a format loosely based on a DER encoding of the ECPrivateKey type from
26
 * section C.4 of SEC 1 <https://www.secg.org/sec1-v2.pdf>, with the following caveats:
27
 *
28
 * * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not
29
 *   required to be encoded as one octet if it is less than 256, as DER would require.
30
 * * The octet-length of the SEQUENCE must not be greater than the remaining
31
 *   length of the key encoding, but need not match it (i.e. the encoding may contain
32
 *   junk after the encoded SEQUENCE).
33
 * * The privateKey OCTET STRING is zero-filled on the left to 32 octets.
34
 * * Anything after the encoding of the privateKey OCTET STRING is ignored, whether
35
 *   or not it is validly encoded DER.
36
 *
37
 * out32 must point to an output buffer of length at least 32 bytes.
38
 */
39
2.40k
int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *seckey, size_t seckeylen) {
40
2.40k
    const unsigned char *end = seckey + seckeylen;
41
2.40k
    memset(out32, 0, 32);
42
    /* sequence header */
43
2.40k
    if (end - seckey < 1 || *seckey != 0x30u) {
44
0
        return 0;
45
0
    }
46
2.40k
    seckey++;
47
    /* sequence length constructor */
48
2.40k
    if (end - seckey < 1 || !(*seckey & 0x80u)) {
49
0
        return 0;
50
0
    }
51
2.40k
    ptrdiff_t lenb = *seckey & ~0x80u; seckey++;
52
2.40k
    if (lenb < 1 || lenb > 2) {
53
0
        return 0;
54
0
    }
55
2.40k
    if (end - seckey < lenb) {
56
0
        return 0;
57
0
    }
58
    /* sequence length */
59
2.40k
    ptrdiff_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u);
60
2.40k
    seckey += lenb;
61
2.40k
    if (end - seckey < len) {
62
0
        return 0;
63
0
    }
64
    /* sequence element 0: version number (=1) */
65
2.40k
    if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) {
66
0
        return 0;
67
0
    }
68
2.40k
    seckey += 3;
69
    /* sequence element 1: octet string, up to 32 bytes */
70
2.40k
    if (end - seckey < 2 || seckey[0] != 0x04u) {
71
0
        return 0;
72
0
    }
73
2.40k
    ptrdiff_t oslen = seckey[1];
74
2.40k
    seckey += 2;
75
2.40k
    if (oslen > 32 || end - seckey < oslen) {
76
0
        return 0;
77
0
    }
78
2.40k
    memcpy(out32 + (32 - oslen), seckey, oslen);
79
2.40k
    if (!secp256k1_ec_seckey_verify(ctx, out32)) {
80
0
        memset(out32, 0, 32);
81
0
        return 0;
82
0
    }
83
2.40k
    return 1;
84
2.40k
}
85
86
/**
87
 * This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1
88
 * <https://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are
89
 * included.
90
 *
91
 * seckey must point to an output buffer of length at least CKey::SIZE bytes.
92
 * seckeylen must initially be set to the size of the seckey buffer. Upon return it
93
 * will be set to the number of bytes used in the buffer.
94
 * key32 must point to a 32-byte raw private key.
95
 */
96
4.24k
int ec_seckey_export_der(const secp256k1_context *ctx, unsigned char *seckey, size_t *seckeylen, const unsigned char *key32, bool compressed) {
97
4.24k
    assert(*seckeylen >= CKey::SIZE);
98
4.24k
    secp256k1_pubkey pubkey;
99
4.24k
    size_t pubkeylen = 0;
100
4.24k
    if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
101
0
        *seckeylen = 0;
102
0
        return 0;
103
0
    }
104
4.24k
    if (compressed) {
105
4.23k
        static const unsigned char begin[] = {
106
4.23k
            0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
107
4.23k
        };
108
4.23k
        static const unsigned char middle[] = {
109
4.23k
            0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
110
4.23k
            0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
111
4.23k
            0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
112
4.23k
            0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
113
4.23k
            0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
114
4.23k
            0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
115
4.23k
            0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
116
4.23k
            0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
117
4.23k
            0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
118
4.23k
        };
119
4.23k
        unsigned char *ptr = seckey;
120
4.23k
        memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
121
4.23k
        memcpy(ptr, key32, 32); ptr += 32;
122
4.23k
        memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
123
4.23k
        pubkeylen = CPubKey::COMPRESSED_SIZE;
124
4.23k
        secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
125
4.23k
        ptr += pubkeylen;
126
4.23k
        *seckeylen = ptr - seckey;
127
4.23k
        assert(*seckeylen == CKey::COMPRESSED_SIZE);
128
4.23k
    } else {
129
6
        static const unsigned char begin[] = {
130
6
            0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
131
6
        };
132
6
        static const unsigned char middle[] = {
133
6
            0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
134
6
            0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
135
6
            0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
136
6
            0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
137
6
            0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
138
6
            0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
139
6
            0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
140
6
            0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
141
6
            0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
142
6
            0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
143
6
            0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
144
6
        };
145
6
        unsigned char *ptr = seckey;
146
6
        memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
147
6
        memcpy(ptr, key32, 32); ptr += 32;
148
6
        memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
149
6
        pubkeylen = CPubKey::SIZE;
150
6
        secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
151
6
        ptr += pubkeylen;
152
6
        *seckeylen = ptr - seckey;
153
6
        assert(*seckeylen == CKey::SIZE);
154
6
    }
155
4.24k
    return 1;
156
4.24k
}
157
158
115k
bool CKey::Check(const unsigned char *vch) {
159
115k
    return secp256k1_ec_seckey_verify(secp256k1_context_static, vch);
160
115k
}
161
162
1.90k
void CKey::MakeNewKey(bool fCompressedIn) {
163
1.90k
    MakeKeyData();
164
1.90k
    do {
165
1.90k
        GetStrongRandBytes(*keydata);
166
1.90k
    } while (!Check(keydata->data()));
167
1.90k
    fCompressed = fCompressedIn;
168
1.90k
}
169
170
4.24k
CPrivKey CKey::GetPrivKey() const {
171
4.24k
    assert(keydata);
172
4.24k
    CPrivKey seckey;
173
4.24k
    int ret;
174
4.24k
    size_t seckeylen;
175
4.24k
    seckey.resize(SIZE);
176
4.24k
    seckeylen = SIZE;
177
4.24k
    ret = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, UCharCast(begin()), fCompressed);
178
4.24k
    assert(ret);
179
4.24k
    seckey.resize(seckeylen);
180
4.24k
    return seckey;
181
4.24k
}
182
183
245k
CPubKey CKey::GetPubKey() const {
184
245k
    assert(keydata);
185
245k
    secp256k1_pubkey pubkey;
186
245k
    size_t clen = CPubKey::SIZE;
187
245k
    CPubKey result;
188
245k
    int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, UCharCast(begin()));
189
245k
    assert(ret);
190
245k
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
191
245k
    assert(result.size() == clen);
192
245k
    assert(result.IsValid());
193
245k
    return result;
194
245k
}
195
196
// Check that the sig has a low R value and will be less than 71 bytes
197
bool SigHasLowR(const secp256k1_ecdsa_signature* sig)
198
44.6k
{
199
44.6k
    unsigned char compact_sig[64];
200
44.6k
    secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_static, compact_sig, sig);
201
202
    // In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates
203
    // its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted
204
    // to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that
205
    // our highest bit is always 0, and thus we must check that the first byte is less than 0x80.
206
44.6k
    return compact_sig[0] < 0x80;
207
44.6k
}
208
209
22.9k
bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const {
210
22.9k
    if (!keydata)
211
0
        return false;
212
22.9k
    vchSig.resize(CPubKey::SIGNATURE_SIZE);
213
22.9k
    size_t nSigLen = CPubKey::SIGNATURE_SIZE;
214
22.9k
    unsigned char extra_entropy[32] = {0};
215
22.9k
    WriteLE32(extra_entropy, test_case);
216
22.9k
    secp256k1_ecdsa_signature sig;
217
22.9k
    uint32_t counter = 0;
218
22.9k
    int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr);
219
220
    // Grind for low R
221
44.6k
    while (ret && !SigHasLowR(&sig) && grind) {
222
21.6k
        WriteLE32(extra_entropy, ++counter);
223
21.6k
        ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, extra_entropy);
224
21.6k
    }
225
22.9k
    assert(ret);
226
22.9k
    secp256k1_ecdsa_signature_serialize_der(secp256k1_context_static, vchSig.data(), &nSigLen, &sig);
227
22.9k
    vchSig.resize(nSigLen);
228
    // Additional verification step to prevent using a potentially corrupted signature
229
22.9k
    secp256k1_pubkey pk;
230
22.9k
    ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pk, UCharCast(begin()));
231
22.9k
    assert(ret);
232
22.9k
    ret = secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pk);
233
22.9k
    assert(ret);
234
22.9k
    return true;
235
22.9k
}
236
237
4.56k
bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
238
4.56k
    if (pubkey.IsCompressed() != fCompressed) {
239
8
        return false;
240
8
    }
241
4.55k
    unsigned char rnd[8];
242
4.55k
    std::string str = "Bitcoin key verification\n";
243
4.55k
    GetRandBytes(rnd);
244
4.55k
    uint256 hash{Hash(str, rnd)};
245
4.55k
    std::vector<unsigned char> vchSig;
246
4.55k
    Sign(hash, vchSig);
247
4.55k
    return pubkey.Verify(hash, vchSig);
248
4.56k
}
249
250
80
bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
251
80
    if (!keydata)
252
1
        return false;
253
79
    vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
254
79
    int rec = -1;
255
79
    secp256k1_ecdsa_recoverable_signature rsig;
256
79
    int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &rsig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, nullptr);
257
79
    assert(ret);
258
79
    ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_static, &vchSig[1], &rec, &rsig);
259
79
    assert(ret);
260
79
    assert(rec != -1);
261
79
    vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
262
    // Additional verification step to prevent using a potentially corrupted signature
263
79
    secp256k1_pubkey epk, rpk;
264
79
    ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &epk, UCharCast(begin()));
265
79
    assert(ret);
266
79
    ret = secp256k1_ecdsa_recover(secp256k1_context_static, &rpk, &rsig, hash.begin());
267
79
    assert(ret);
268
79
    ret = secp256k1_ec_pubkey_cmp(secp256k1_context_static, &epk, &rpk);
269
79
    assert(ret == 0);
270
79
    return true;
271
79
}
272
273
bool CKey::SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const
274
1.34k
{
275
1.34k
    KeyPair kp = ComputeKeyPair(merkle_root);
276
1.34k
    return kp.SignSchnorr(hash, sig, aux);
277
1.34k
}
278
279
2.40k
bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
280
2.40k
    MakeKeyData();
281
2.40k
    if (!ec_seckey_import_der(secp256k1_context_static, (unsigned char*)begin(), seckey.data(), seckey.size())) {
282
0
        ClearKeyData();
283
0
        return false;
284
0
    }
285
2.40k
    fCompressed = vchPubKey.IsCompressed();
286
287
2.40k
    if (fSkipCheck)
288
2.40k
        return true;
289
290
0
    return VerifyPubKey(vchPubKey);
291
2.40k
}
292
293
107k
bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
294
107k
    assert(IsValid());
295
107k
    assert(IsCompressed());
296
107k
    std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
297
107k
    if ((nChild >> 31) == 0) {
298
32.6k
        CPubKey pubkey = GetPubKey();
299
32.6k
        assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
300
32.6k
        BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
301
74.7k
    } else {
302
74.7k
        assert(size() == 32);
303
74.7k
        BIP32Hash(cc, nChild, 0, UCharCast(begin()), vout.data());
304
74.7k
    }
305
107k
    memcpy(ccChild.begin(), vout.data()+32, 32);
306
107k
    keyChild.Set(begin(), begin() + 32, true);
307
107k
    bool ret = secp256k1_ec_seckey_tweak_add(secp256k1_context_static, (unsigned char*)keyChild.begin(), vout.data());
308
107k
    if (!ret) keyChild.ClearKeyData();
309
107k
    return ret;
310
107k
}
311
312
EllSwiftPubKey CKey::EllSwiftCreate(std::span<const std::byte> ent32) const
313
331
{
314
331
    assert(keydata);
315
331
    assert(ent32.size() == 32);
316
331
    std::array<std::byte, EllSwiftPubKey::size()> encoded_pubkey;
317
318
331
    auto success = secp256k1_ellswift_create(secp256k1_context_sign,
319
331
                                             UCharCast(encoded_pubkey.data()),
320
331
                                             keydata->data(),
321
331
                                             UCharCast(ent32.data()));
322
323
    // Should always succeed for valid keys (asserted above).
324
331
    assert(success);
325
331
    return {encoded_pubkey};
326
331
}
327
328
ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, const EllSwiftPubKey& our_ellswift, bool initiating) const
329
412
{
330
412
    assert(keydata);
331
332
412
    ECDHSecret output;
333
    // BIP324 uses the initiator as party A, and the responder as party B. Remap the inputs
334
    // accordingly:
335
412
    bool success = secp256k1_ellswift_xdh(secp256k1_context_static,
336
412
                                          UCharCast(output.data()),
337
412
                                          UCharCast(initiating ? our_ellswift.data() : their_ellswift.data()),
338
412
                                          UCharCast(initiating ? their_ellswift.data() : our_ellswift.data()),
339
412
                                          keydata->data(),
340
412
                                          initiating ? 0 : 1,
341
412
                                          secp256k1_ellswift_xdh_hash_function_bip324,
342
412
                                          nullptr);
343
    // Should always succeed for valid keys (assert above).
344
412
    assert(success);
345
412
    return output;
346
412
}
347
348
KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const
349
1.38k
{
350
1.38k
    return KeyPair(*this, merkle_root);
351
1.38k
}
352
353
std::vector<uint8_t> CKey::CreateMuSig2Nonce(MuSig2SecNonce& secnonce, const uint256& sighash, const CPubKey& aggregate_pubkey, const std::vector<CPubKey>& pubkeys)
354
79
{
355
    // Get the keyagg cache and aggregate pubkey
356
79
    secp256k1_musig_keyagg_cache keyagg_cache;
357
79
    if (!MuSig2AggregatePubkeys(pubkeys, keyagg_cache, aggregate_pubkey)) return {};
358
359
    // Parse participant pubkey
360
79
    CPubKey our_pubkey = GetPubKey();
361
79
    secp256k1_pubkey pubkey;
362
79
    if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, our_pubkey.data(), our_pubkey.size())) {
363
0
        return {};
364
0
    }
365
366
    // Generate randomness for nonce
367
79
    uint256 rand;
368
79
    GetStrongRandBytes(rand);
369
370
    // Generate nonce
371
79
    secp256k1_musig_pubnonce pubnonce;
372
79
    if (!secp256k1_musig_nonce_gen(secp256k1_context_sign, secnonce.Get(), &pubnonce, rand.data(), UCharCast(begin()), &pubkey, sighash.data(), &keyagg_cache, nullptr)) {
373
0
        return {};
374
0
    }
375
376
    // Serialize pubnonce
377
79
    std::vector<uint8_t> out;
378
79
    out.resize(MUSIG2_PUBNONCE_SIZE);
379
79
    if (!secp256k1_musig_pubnonce_serialize(secp256k1_context_static, out.data(), &pubnonce)) {
380
0
        return {};
381
0
    }
382
383
79
    return out;
384
79
}
385
386
std::optional<uint256> CKey::CreateMuSig2PartialSig(const uint256& sighash, const CPubKey& aggregate_pubkey, const std::vector<CPubKey>& pubkeys, const std::map<CPubKey, std::vector<uint8_t>>& pubnonces, MuSig2SecNonce& secnonce, const std::vector<std::pair<uint256, bool>>& tweaks)
387
71
{
388
71
    secp256k1_keypair keypair;
389
71
    if (!secp256k1_keypair_create(secp256k1_context_sign, &keypair, UCharCast(begin()))) return std::nullopt;
390
391
    // Get the keyagg cache and aggregate pubkey
392
71
    secp256k1_musig_keyagg_cache keyagg_cache;
393
71
    if (!MuSig2AggregatePubkeys(pubkeys, keyagg_cache, aggregate_pubkey)) return std::nullopt;
394
395
    // Check that there are enough pubnonces
396
71
    if (pubnonces.size() != pubkeys.size()) return std::nullopt;
397
398
    // Parse the pubnonces
399
71
    std::vector<std::pair<secp256k1_pubkey, secp256k1_musig_pubnonce>> signers_data;
400
71
    std::vector<const secp256k1_musig_pubnonce*> pubnonce_ptrs;
401
71
    std::optional<size_t> our_pubkey_idx;
402
71
    CPubKey our_pubkey = GetPubKey();
403
201
    for (const CPubKey& part_pk : pubkeys) {
404
201
        const auto& pn_it = pubnonces.find(part_pk);
405
201
        if (pn_it == pubnonces.end()) return std::nullopt;
406
201
        const std::vector<uint8_t> pubnonce = pn_it->second;
407
201
        if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) return std::nullopt;
408
201
        if (part_pk == our_pubkey) {
409
71
            our_pubkey_idx = signers_data.size();
410
71
        }
411
412
201
        auto& [secp_pk, secp_pn] = signers_data.emplace_back();
413
414
201
        if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &secp_pk, part_pk.data(), part_pk.size())) {
415
0
            return std::nullopt;
416
0
        }
417
418
201
        if (!secp256k1_musig_pubnonce_parse(secp256k1_context_static, &secp_pn, pubnonce.data())) {
419
0
            return std::nullopt;
420
0
        }
421
201
    }
422
71
    if (our_pubkey_idx == std::nullopt) {
423
0
        return std::nullopt;
424
0
    }
425
71
    pubnonce_ptrs.reserve(signers_data.size());
426
201
    for (auto& [_, pn] : signers_data) {
427
201
        pubnonce_ptrs.push_back(&pn);
428
201
    }
429
430
    // Aggregate nonces
431
71
    secp256k1_musig_aggnonce aggnonce;
432
71
    if (!secp256k1_musig_nonce_agg(secp256k1_context_static, &aggnonce, pubnonce_ptrs.data(), pubnonce_ptrs.size())) {
433
0
        return std::nullopt;
434
0
    }
435
436
    // Apply tweaks
437
108
    for (const auto& [tweak, xonly] : tweaks) {
438
108
        if (xonly) {
439
18
            if (!secp256k1_musig_pubkey_xonly_tweak_add(secp256k1_context_static, nullptr, &keyagg_cache, tweak.data())) {
440
0
                return std::nullopt;
441
0
            }
442
90
        } else if (!secp256k1_musig_pubkey_ec_tweak_add(secp256k1_context_static, nullptr, &keyagg_cache, tweak.data())) {
443
0
            return std::nullopt;
444
0
        }
445
108
    }
446
447
    // Create musig_session
448
71
    secp256k1_musig_session session;
449
71
    if (!secp256k1_musig_nonce_process(secp256k1_context_static, &session, &aggnonce, sighash.data(), &keyagg_cache)) {
450
0
        return std::nullopt;
451
0
    }
452
453
    // Create partial signature
454
71
    secp256k1_musig_partial_sig psig;
455
71
    if (!secp256k1_musig_partial_sign(secp256k1_context_static, &psig, secnonce.Get(), &keypair, &keyagg_cache, &session)) {
456
0
        return std::nullopt;
457
0
    }
458
    // The secnonce must be deleted after signing to prevent nonce reuse.
459
71
    secnonce.Invalidate();
460
461
    // Verify partial signature
462
71
    if (!secp256k1_musig_partial_sig_verify(secp256k1_context_static, &psig, &(signers_data.at(*our_pubkey_idx).second), &(signers_data.at(*our_pubkey_idx).first), &keyagg_cache, &session)) {
463
0
        return std::nullopt;
464
0
    }
465
466
    // Serialize
467
71
    uint256 sig;
468
71
    if (!secp256k1_musig_partial_sig_serialize(secp256k1_context_static, sig.data(), &psig)) {
469
0
        return std::nullopt;
470
0
    }
471
472
71
    return sig;
473
71
}
474
475
CKey GenerateRandomKey(bool compressed) noexcept
476
1.85k
{
477
1.85k
    CKey key;
478
1.85k
    key.MakeNewKey(/*fCompressed=*/compressed);
479
1.85k
    return key;
480
1.85k
}
481
482
107k
bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
483
107k
    if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
484
107k
    out.nDepth = nDepth + 1;
485
107k
    CKeyID id = key.GetPubKey().GetID();
486
107k
    memcpy(out.vchFingerprint, &id, 4);
487
107k
    out.nChild = _nChild;
488
107k
    return key.Derive(out.key, out.chaincode, _nChild, chaincode);
489
107k
}
490
491
void CExtKey::SetSeed(std::span<const std::byte> seed)
492
526
{
493
526
    static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
494
526
    std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
495
526
    CHMAC_SHA512{hashkey, sizeof(hashkey)}.Write(UCharCast(seed.data()), seed.size()).Finalize(vout.data());
496
526
    key.Set(vout.data(), vout.data() + 32, true);
497
526
    memcpy(chaincode.begin(), vout.data() + 32, 32);
498
526
    nDepth = 0;
499
526
    nChild = 0;
500
526
    memset(vchFingerprint, 0, sizeof(vchFingerprint));
501
526
}
502
503
76.1k
CExtPubKey CExtKey::Neuter() const {
504
76.1k
    CExtPubKey ret;
505
76.1k
    ret.nDepth = nDepth;
506
76.1k
    memcpy(ret.vchFingerprint, vchFingerprint, 4);
507
76.1k
    ret.nChild = nChild;
508
76.1k
    ret.pubkey = key.GetPubKey();
509
76.1k
    ret.chaincode = chaincode;
510
76.1k
    return ret;
511
76.1k
}
512
513
1.01k
void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
514
1.01k
    code[0] = nDepth;
515
1.01k
    memcpy(code+1, vchFingerprint, 4);
516
1.01k
    WriteBE32(code+5, nChild);
517
1.01k
    memcpy(code+9, chaincode.begin(), 32);
518
1.01k
    code[41] = 0;
519
1.01k
    assert(key.size() == 32);
520
1.01k
    memcpy(code+42, key.begin(), 32);
521
1.01k
}
522
523
859
void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
524
859
    nDepth = code[0];
525
859
    memcpy(vchFingerprint, code+1, 4);
526
859
    nChild = ReadBE32(code+5);
527
859
    memcpy(chaincode.begin(), code+9, 32);
528
859
    key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
529
859
    if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || code[41] != 0) key = CKey();
530
859
}
531
532
KeyPair::KeyPair(const CKey& key, const uint256* merkle_root)
533
1.38k
{
534
1.38k
    static_assert(std::tuple_size<KeyType>() == sizeof(secp256k1_keypair));
535
1.38k
    MakeKeyPairData();
536
1.38k
    auto keypair = reinterpret_cast<secp256k1_keypair*>(m_keypair->data());
537
1.38k
    bool success = secp256k1_keypair_create(secp256k1_context_sign, keypair, UCharCast(key.data()));
538
1.38k
    if (success && merkle_root) {
539
626
        secp256k1_xonly_pubkey pubkey;
540
626
        unsigned char pubkey_bytes[32];
541
626
        assert(secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey, nullptr, keypair));
542
626
        assert(secp256k1_xonly_pubkey_serialize(secp256k1_context_static, pubkey_bytes, &pubkey));
543
626
        uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
544
626
        success = secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, keypair, tweak.data());
545
626
    }
546
1.38k
    if (!success) ClearKeyPairData();
547
1.38k
}
548
549
bool KeyPair::SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256& aux) const
550
1.38k
{
551
1.38k
    assert(sig.size() == 64);
552
1.38k
    if (!IsValid()) return false;
553
1.38k
    auto keypair = reinterpret_cast<const secp256k1_keypair*>(m_keypair->data());
554
1.38k
    bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), keypair, aux.data());
555
1.38k
    if (ret) {
556
        // Additional verification step to prevent using a potentially corrupted signature
557
1.38k
        secp256k1_xonly_pubkey pubkey_verify;
558
1.38k
        ret = secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey_verify, nullptr, keypair);
559
1.38k
        ret &= secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), hash.begin(), 32, &pubkey_verify);
560
1.38k
    }
561
1.38k
    if (!ret) memory_cleanse(sig.data(), sig.size());
562
1.38k
    return ret;
563
1.38k
}
564
565
1.11k
bool ECC_InitSanityCheck() {
566
1.11k
    CKey key = GenerateRandomKey();
567
1.11k
    CPubKey pubkey = key.GetPubKey();
568
1.11k
    return key.VerifyPubKey(pubkey);
569
1.11k
}
570
571
/** Initialize the elliptic curve support. May not be called twice without calling ECC_Stop first. */
572
1.84k
static void ECC_Start() {
573
1.84k
    assert(secp256k1_context_sign == nullptr);
574
575
1.84k
    secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
576
1.84k
    assert(ctx != nullptr);
577
578
1.84k
    {
579
        // Pass in a random blinding seed to the secp256k1 context.
580
1.84k
        std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
581
1.84k
        GetRandBytes(vseed);
582
1.84k
        bool ret = secp256k1_context_randomize(ctx, vseed.data());
583
1.84k
        assert(ret);
584
1.84k
    }
585
586
1.84k
    secp256k1_context_sign = ctx;
587
1.84k
}
588
589
/** Deinitialize the elliptic curve support. No-op if ECC_Start wasn't called first. */
590
1.84k
static void ECC_Stop() {
591
1.84k
    secp256k1_context *ctx = secp256k1_context_sign;
592
1.84k
    secp256k1_context_sign = nullptr;
593
594
1.84k
    if (ctx) {
595
1.84k
        secp256k1_context_destroy(ctx);
596
1.84k
    }
597
1.84k
}
598
599
ECC_Context::ECC_Context()
600
1.84k
{
601
1.84k
    ECC_Start();
602
1.84k
}
603
604
ECC_Context::~ECC_Context()
605
1.84k
{
606
1.84k
    ECC_Stop();
607
1.84k
}