Coverage Report

Created: 2026-09-14 20:36

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_recovery.h>
17
#include <secp256k1_schnorrsig.h>
18
19
#include <algorithm>
20
21
static secp256k1_context* secp256k1_context_sign = nullptr;
22
23
/** These functions are taken from the libsecp256k1 distribution and are very ugly. */
24
25
/**
26
 * This parses a format loosely based on a DER encoding of the ECPrivateKey type from
27
 * section C.4 of SEC 1 <https://www.secg.org/sec1-v2.pdf>, with the following caveats:
28
 *
29
 * * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not
30
 *   required to be encoded as one octet if it is less than 256, as DER would require.
31
 * * The octet-length of the SEQUENCE must not be greater than the remaining
32
 *   length of the key encoding, but need not match it (i.e. the encoding may contain
33
 *   junk after the encoded SEQUENCE).
34
 * * The privateKey OCTET STRING is zero-filled on the left to 32 octets.
35
 * * Anything after the encoding of the privateKey OCTET STRING is ignored, whether
36
 *   or not it is validly encoded DER.
37
 *
38
 * out32 must point to an output buffer of length at least 32 bytes.
39
 */
40
2.76k
int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *seckey, size_t seckeylen) {
41
2.76k
    const unsigned char *end = seckey + seckeylen;
42
2.76k
    memset(out32, 0, 32);
43
    /* sequence header */
44
2.76k
    if (end - seckey < 1 || *seckey != 0x30u) {
45
0
        return 0;
46
0
    }
47
2.76k
    seckey++;
48
    /* sequence length constructor */
49
2.76k
    if (end - seckey < 1 || !(*seckey & 0x80u)) {
50
0
        return 0;
51
0
    }
52
2.76k
    ptrdiff_t lenb = *seckey & ~0x80u; seckey++;
53
2.76k
    if (lenb < 1 || lenb > 2) {
54
0
        return 0;
55
0
    }
56
2.76k
    if (end - seckey < lenb) {
57
0
        return 0;
58
0
    }
59
    /* sequence length */
60
2.76k
    ptrdiff_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u);
61
2.76k
    seckey += lenb;
62
2.76k
    if (end - seckey < len) {
63
0
        return 0;
64
0
    }
65
    /* sequence element 0: version number (=1) */
66
2.76k
    if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) {
67
0
        return 0;
68
0
    }
69
2.76k
    seckey += 3;
70
    /* sequence element 1: octet string, up to 32 bytes */
71
2.76k
    if (end - seckey < 2 || seckey[0] != 0x04u) {
72
0
        return 0;
73
0
    }
74
2.76k
    ptrdiff_t oslen = seckey[1];
75
2.76k
    seckey += 2;
76
2.76k
    if (oslen > 32 || end - seckey < oslen) {
77
0
        return 0;
78
0
    }
79
2.76k
    memcpy(out32 + (32 - oslen), seckey, oslen);
80
2.76k
    if (!secp256k1_ec_seckey_verify(ctx, out32)) {
81
0
        memset(out32, 0, 32);
82
0
        return 0;
83
0
    }
84
2.76k
    return 1;
85
2.76k
}
86
87
/**
88
 * This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1
89
 * <https://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are
90
 * included.
91
 *
92
 * seckey must point to an output buffer of length at least CKey::SIZE bytes.
93
 * seckeylen must initially be set to the size of the seckey buffer. Upon return it
94
 * will be set to the number of bytes used in the buffer.
95
 * key32 must point to a 32-byte raw private key.
96
 */
97
4.66k
int ec_seckey_export_der(const secp256k1_context *ctx, unsigned char *seckey, size_t *seckeylen, const unsigned char *key32, bool compressed) {
98
4.66k
    assert(*seckeylen >= CKey::SIZE);
99
4.66k
    secp256k1_pubkey pubkey;
100
4.66k
    size_t pubkeylen = 0;
101
4.66k
    if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
102
0
        *seckeylen = 0;
103
0
        return 0;
104
0
    }
105
4.66k
    if (compressed) {
106
4.66k
        static const unsigned char begin[] = {
107
4.66k
            0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
108
4.66k
        };
109
4.66k
        static const unsigned char middle[] = {
110
4.66k
            0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
111
4.66k
            0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
112
4.66k
            0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
113
4.66k
            0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
114
4.66k
            0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
115
4.66k
            0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
116
4.66k
            0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
117
4.66k
            0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
118
4.66k
            0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
119
4.66k
        };
120
4.66k
        unsigned char *ptr = seckey;
121
4.66k
        memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
122
4.66k
        memcpy(ptr, key32, 32); ptr += 32;
123
4.66k
        memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
124
4.66k
        pubkeylen = CPubKey::COMPRESSED_SIZE;
125
4.66k
        secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
126
4.66k
        ptr += pubkeylen;
127
4.66k
        *seckeylen = ptr - seckey;
128
4.66k
        assert(*seckeylen == CKey::COMPRESSED_SIZE);
129
4.66k
    } else {
130
6
        static const unsigned char begin[] = {
131
6
            0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
132
6
        };
133
6
        static const unsigned char middle[] = {
134
6
            0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
135
6
            0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
136
6
            0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
137
6
            0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
138
6
            0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
139
6
            0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
140
6
            0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
141
6
            0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
142
6
            0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
143
6
            0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
144
6
            0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
145
6
        };
146
6
        unsigned char *ptr = seckey;
147
6
        memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
148
6
        memcpy(ptr, key32, 32); ptr += 32;
149
6
        memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
150
6
        pubkeylen = CPubKey::SIZE;
151
6
        secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
152
6
        ptr += pubkeylen;
153
6
        *seckeylen = ptr - seckey;
154
6
        assert(*seckeylen == CKey::SIZE);
155
6
    }
156
4.66k
    return 1;
157
4.66k
}
158
159
150k
bool CKey::Check(const unsigned char *vch) {
160
150k
    return secp256k1_ec_seckey_verify(secp256k1_context_static, vch);
161
150k
}
162
163
2.07k
void CKey::MakeNewKey(bool fCompressedIn) {
164
2.07k
    MakeKeyData();
165
2.07k
    do {
166
2.07k
        GetStrongRandBytes(*keydata);
167
2.07k
    } while (!Check(keydata->data()));
168
2.07k
    fCompressed = fCompressedIn;
169
2.07k
}
170
171
4.66k
CPrivKey CKey::GetPrivKey() const {
172
4.66k
    assert(keydata);
173
4.66k
    CPrivKey seckey;
174
4.66k
    int ret;
175
4.66k
    size_t seckeylen;
176
4.66k
    seckey.resize(SIZE);
177
4.66k
    seckeylen = SIZE;
178
4.66k
    ret = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, UCharCast(begin()), fCompressed);
179
4.66k
    assert(ret);
180
4.66k
    seckey.resize(seckeylen);
181
4.66k
    return seckey;
182
4.66k
}
183
184
332k
CPubKey CKey::GetPubKey() const {
185
332k
    assert(keydata);
186
332k
    secp256k1_pubkey pubkey;
187
332k
    size_t clen = CPubKey::SIZE;
188
332k
    CPubKey result;
189
332k
    int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, UCharCast(begin()));
190
332k
    assert(ret);
191
332k
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
192
332k
    assert(result.size() == clen);
193
332k
    assert(result.IsValid());
194
332k
    return result;
195
332k
}
196
197
// Check that the sig has a low R value and will be less than 71 bytes
198
bool SigHasLowR(const secp256k1_ecdsa_signature* sig)
199
49.0k
{
200
49.0k
    unsigned char compact_sig[64];
201
49.0k
    secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_static, compact_sig, sig);
202
203
    // In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates
204
    // its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted
205
    // to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that
206
    // our highest bit is always 0, and thus we must check that the first byte is less than 0x80.
207
49.0k
    return compact_sig[0] < 0x80;
208
49.0k
}
209
210
25.1k
bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const {
211
25.1k
    if (!keydata)
212
0
        return false;
213
25.1k
    vchSig.resize(CPubKey::SIGNATURE_SIZE);
214
25.1k
    size_t nSigLen = CPubKey::SIGNATURE_SIZE;
215
25.1k
    unsigned char extra_entropy[32] = {0};
216
25.1k
    WriteLE32(extra_entropy, test_case);
217
25.1k
    secp256k1_ecdsa_signature sig;
218
25.1k
    uint32_t counter = 0;
219
25.1k
    int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr);
220
221
    // Grind for low R
222
49.0k
    while (ret && !SigHasLowR(&sig) && grind) {
223
23.9k
        WriteLE32(extra_entropy, ++counter);
224
23.9k
        ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, extra_entropy);
225
23.9k
    }
226
25.1k
    assert(ret);
227
25.1k
    secp256k1_ecdsa_signature_serialize_der(secp256k1_context_static, vchSig.data(), &nSigLen, &sig);
228
25.1k
    vchSig.resize(nSigLen);
229
    // Additional verification step to prevent using a potentially corrupted signature
230
25.1k
    secp256k1_pubkey pk;
231
25.1k
    ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pk, UCharCast(begin()));
232
25.1k
    assert(ret);
233
25.1k
    ret = secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pk);
234
25.1k
    assert(ret);
235
25.1k
    return true;
236
25.1k
}
237
238
5.12k
bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
239
5.12k
    if (pubkey.IsCompressed() != fCompressed) {
240
8
        return false;
241
8
    }
242
5.11k
    unsigned char rnd[8];
243
5.11k
    std::string str = "Bitcoin key verification\n";
244
5.11k
    GetRandBytes(rnd);
245
5.11k
    uint256 hash{Hash(str, rnd)};
246
5.11k
    std::vector<unsigned char> vchSig;
247
5.11k
    Sign(hash, vchSig);
248
5.11k
    return pubkey.Verify(hash, vchSig);
249
5.12k
}
250
251
80
bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
252
80
    if (!keydata)
253
1
        return false;
254
79
    vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
255
79
    int rec = -1;
256
79
    secp256k1_ecdsa_recoverable_signature rsig;
257
79
    int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &rsig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, nullptr);
258
79
    assert(ret);
259
79
    ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_static, &vchSig[1], &rec, &rsig);
260
79
    assert(ret);
261
79
    assert(rec != -1);
262
79
    vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
263
    // Additional verification step to prevent using a potentially corrupted signature
264
79
    secp256k1_pubkey epk, rpk;
265
79
    ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &epk, UCharCast(begin()));
266
79
    assert(ret);
267
79
    ret = secp256k1_ecdsa_recover(secp256k1_context_static, &rpk, &rsig, hash.begin());
268
79
    assert(ret);
269
79
    ret = secp256k1_ec_pubkey_cmp(secp256k1_context_static, &epk, &rpk);
270
79
    assert(ret == 0);
271
79
    return true;
272
79
}
273
274
bool CKey::SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const
275
1.37k
{
276
1.37k
    KeyPair kp = ComputeKeyPair(merkle_root);
277
1.37k
    return kp.SignSchnorr(hash, sig, aux);
278
1.37k
}
279
280
2.76k
bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
281
2.76k
    MakeKeyData();
282
2.76k
    if (!ec_seckey_import_der(secp256k1_context_static, (unsigned char*)begin(), seckey.data(), seckey.size())) {
283
0
        ClearKeyData();
284
0
        return false;
285
0
    }
286
2.76k
    fCompressed = vchPubKey.IsCompressed();
287
288
2.76k
    if (fSkipCheck)
289
2.76k
        return true;
290
291
0
    return VerifyPubKey(vchPubKey);
292
2.76k
}
293
294
141k
bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
295
141k
    assert(IsValid());
296
141k
    assert(IsCompressed());
297
141k
    std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
298
141k
    if ((nChild >> 31) == 0) {
299
35.7k
        CPubKey pubkey = GetPubKey();
300
35.7k
        assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
301
35.7k
        BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
302
106k
    } else {
303
106k
        assert(size() == 32);
304
106k
        BIP32Hash(cc, nChild, 0, UCharCast(begin()), vout.data());
305
106k
    }
306
141k
    memcpy(ccChild.begin(), vout.data()+32, 32);
307
141k
    keyChild.Set(begin(), begin() + 32, true);
308
141k
    bool ret = secp256k1_ec_seckey_tweak_add(secp256k1_context_static, (unsigned char*)keyChild.begin(), vout.data());
309
141k
    if (!ret) keyChild.ClearKeyData();
310
141k
    return ret;
311
141k
}
312
313
EllSwiftPubKey CKey::EllSwiftCreate(std::span<const std::byte> ent32) const
314
363
{
315
363
    assert(keydata);
316
363
    assert(ent32.size() == 32);
317
363
    std::array<std::byte, EllSwiftPubKey::size()> encoded_pubkey;
318
319
363
    auto success = secp256k1_ellswift_create(secp256k1_context_sign,
320
363
                                             UCharCast(encoded_pubkey.data()),
321
363
                                             keydata->data(),
322
363
                                             UCharCast(ent32.data()));
323
324
    // Should always succeed for valid keys (asserted above).
325
363
    assert(success);
326
363
    return {encoded_pubkey};
327
363
}
328
329
ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, const EllSwiftPubKey& our_ellswift, bool initiating) const
330
439
{
331
439
    assert(keydata);
332
333
439
    ECDHSecret output;
334
    // BIP324 uses the initiator as party A, and the responder as party B. Remap the inputs
335
    // accordingly:
336
439
    bool success = secp256k1_ellswift_xdh(secp256k1_context_static,
337
439
                                          UCharCast(output.data()),
338
439
                                          UCharCast(initiating ? our_ellswift.data() : their_ellswift.data()),
339
439
                                          UCharCast(initiating ? their_ellswift.data() : our_ellswift.data()),
340
439
                                          keydata->data(),
341
439
                                          initiating ? 0 : 1,
342
439
                                          secp256k1_ellswift_xdh_hash_function_bip324,
343
439
                                          nullptr);
344
    // Should always succeed for valid keys (assert above).
345
439
    assert(success);
346
439
    return output;
347
439
}
348
349
KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const
350
1.41k
{
351
1.41k
    return KeyPair(*this, merkle_root);
352
1.41k
}
353
354
CKey GenerateRandomKey(bool compressed) noexcept
355
2.02k
{
356
2.02k
    CKey key;
357
2.02k
    key.MakeNewKey(/*fCompressed=*/compressed);
358
2.02k
    return key;
359
2.02k
}
360
361
141k
bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
362
141k
    if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
363
141k
    out.nDepth = nDepth + 1;
364
141k
    out.fingerprint = id_key_fingerprint();
365
141k
    out.nChild = _nChild;
366
141k
    return key.Derive(out.key, out.chaincode, _nChild, chaincode);
367
141k
}
368
369
std::optional<std::pair<CExtKey, KeyOriginInfo>> DeriveExtKey(const CExtKey& ext_key, const std::vector<uint32_t>& path)
370
21
{
371
21
    CExtKey descendant = ext_key;
372
21
    KeyOriginInfo origin;
373
21
    origin.fingerprint = ext_key.id_key_fingerprint();
374
21
    origin.path = path;
375
298
    for (uint32_t i : path) {
376
298
        if (!descendant.Derive(descendant, i)) return std::nullopt;
377
298
    }
378
19
    return std::make_pair(descendant, origin);
379
21
}
380
381
void CExtKey::SetSeed(std::span<const std::byte> seed)
382
557
{
383
557
    Assert(16 <= seed.size() && seed.size() <= 64);
384
557
    static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
385
557
    std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
386
557
    CHMAC_SHA512{hashkey, sizeof(hashkey)}.Write(UCharCast(seed.data()), seed.size()).Finalize(vout.data());
387
557
    key.Set(vout.data(), vout.data() + 32, true);
388
557
    memcpy(chaincode.begin(), vout.data() + 32, 32);
389
557
    nDepth = 0;
390
557
    nChild = 0;
391
557
    fingerprint.fill(0);
392
557
}
393
394
120k
CExtPubKey CExtKey::Neuter() const {
395
120k
    CExtPubKey ret;
396
120k
    ret.nDepth = nDepth;
397
120k
    ret.fingerprint = fingerprint;
398
120k
    ret.nChild = nChild;
399
120k
    ret.pubkey = key.GetPubKey();
400
120k
    ret.chaincode = chaincode;
401
120k
    return ret;
402
120k
}
403
404
1.10k
void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
405
1.10k
    code[0] = nDepth;
406
1.10k
    std::ranges::copy(fingerprint, code+1);
407
1.10k
    WriteBE32(code+5, nChild);
408
1.10k
    memcpy(code+9, chaincode.begin(), 32);
409
1.10k
    code[41] = 0;
410
1.10k
    assert(key.size() == 32);
411
1.10k
    memcpy(code+42, key.begin(), 32);
412
1.10k
}
413
414
936
void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
415
936
    nDepth = code[0];
416
936
    std::copy_n(code + 1, fingerprint.size(), fingerprint.begin());
417
936
    nChild = ReadBE32(code+5);
418
936
    memcpy(chaincode.begin(), code+9, 32);
419
936
    key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
420
936
    if ((nDepth == 0 && (nChild != 0 || ReadLE32(fingerprint.data()) != 0)) || code[41] != 0) key = CKey();
421
936
}
422
423
KeyPair::KeyPair(const CKey& key, const uint256* merkle_root)
424
1.41k
{
425
1.41k
    static_assert(std::tuple_size<KeyType>() == sizeof(secp256k1_keypair));
426
1.41k
    MakeKeyPairData();
427
1.41k
    auto keypair = reinterpret_cast<secp256k1_keypair*>(m_keypair->data());
428
1.41k
    bool success = secp256k1_keypair_create(secp256k1_context_sign, keypair, UCharCast(key.data()));
429
1.41k
    if (success && merkle_root) {
430
640
        secp256k1_xonly_pubkey pubkey;
431
640
        unsigned char pubkey_bytes[32];
432
640
        assert(secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey, nullptr, keypair));
433
640
        assert(secp256k1_xonly_pubkey_serialize(secp256k1_context_static, pubkey_bytes, &pubkey));
434
640
        uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
435
640
        success = secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, keypair, tweak.data());
436
640
    }
437
1.41k
    if (!success) ClearKeyPairData();
438
1.41k
}
439
440
bool KeyPair::SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256& aux) const
441
1.41k
{
442
1.41k
    assert(sig.size() == 64);
443
1.41k
    if (!IsValid()) return false;
444
1.41k
    auto keypair = reinterpret_cast<const secp256k1_keypair*>(m_keypair->data());
445
1.41k
    bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), keypair, aux.data());
446
1.41k
    if (ret) {
447
        // Additional verification step to prevent using a potentially corrupted signature
448
1.41k
        secp256k1_xonly_pubkey pubkey_verify;
449
1.41k
        ret = secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey_verify, nullptr, keypair);
450
1.41k
        ret &= secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), hash.begin(), 32, &pubkey_verify);
451
1.41k
    }
452
1.41k
    if (!ret) memory_cleanse(sig.data(), sig.size());
453
1.41k
    return ret;
454
1.41k
}
455
456
1.19k
bool ECC_InitSanityCheck() {
457
1.19k
    CKey key = GenerateRandomKey();
458
1.19k
    CPubKey pubkey = key.GetPubKey();
459
1.19k
    return key.VerifyPubKey(pubkey);
460
1.19k
}
461
462
secp256k1_context* GetSecp256k1SignContext()
463
315
{
464
315
    return secp256k1_context_sign;
465
315
}
466
467
/** Initialize the elliptic curve support. May not be called twice without calling ECC_Stop first. */
468
1.99k
static void ECC_Start() {
469
1.99k
    assert(secp256k1_context_sign == nullptr);
470
471
1.99k
    secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
472
1.99k
    assert(ctx != nullptr);
473
474
1.99k
    {
475
        // Pass in a random blinding seed to the secp256k1 context.
476
1.99k
        std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
477
1.99k
        GetRandBytes(vseed);
478
1.99k
        bool ret = secp256k1_context_randomize(ctx, vseed.data());
479
1.99k
        assert(ret);
480
1.99k
    }
481
482
1.99k
    secp256k1_context_sign = ctx;
483
1.99k
}
484
485
/** Deinitialize the elliptic curve support. No-op if ECC_Start wasn't called first. */
486
1.99k
static void ECC_Stop() {
487
1.99k
    secp256k1_context *ctx = secp256k1_context_sign;
488
1.99k
    secp256k1_context_sign = nullptr;
489
490
1.99k
    if (ctx) {
491
1.99k
        secp256k1_context_destroy(ctx);
492
1.99k
    }
493
1.99k
}
494
495
ECC_Context::ECC_Context()
496
1.99k
{
497
1.99k
    ECC_Start();
498
1.99k
}
499
500
ECC_Context::~ECC_Context()
501
1.99k
{
502
1.99k
    ECC_Stop();
503
1.99k
}