Coverage Report

Created: 2026-10-07 20:27

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/root/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
0
int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *seckey, size_t seckeylen) {
41
0
    const unsigned char *end = seckey + seckeylen;
42
0
    memset(out32, 0, 32);
43
    /* sequence header */
44
0
    if (end - seckey < 1 || *seckey != 0x30u) {
  Branch (44:9): [True: 0, False: 0]
  Branch (44:29): [True: 0, False: 0]
45
0
        return 0;
46
0
    }
47
0
    seckey++;
48
    /* sequence length constructor */
49
0
    if (end - seckey < 1 || !(*seckey & 0x80u)) {
  Branch (49:9): [True: 0, False: 0]
  Branch (49:29): [True: 0, False: 0]
50
0
        return 0;
51
0
    }
52
0
    ptrdiff_t lenb = *seckey & ~0x80u; seckey++;
53
0
    if (lenb < 1 || lenb > 2) {
  Branch (53:9): [True: 0, False: 0]
  Branch (53:21): [True: 0, False: 0]
54
0
        return 0;
55
0
    }
56
0
    if (end - seckey < lenb) {
  Branch (56:9): [True: 0, False: 0]
57
0
        return 0;
58
0
    }
59
    /* sequence length */
60
0
    ptrdiff_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u);
  Branch (60:39): [True: 0, False: 0]
61
0
    seckey += lenb;
62
0
    if (end - seckey < len) {
  Branch (62:9): [True: 0, False: 0]
63
0
        return 0;
64
0
    }
65
    /* sequence element 0: version number (=1) */
66
0
    if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) {
  Branch (66:9): [True: 0, False: 0]
  Branch (66:29): [True: 0, False: 0]
  Branch (66:51): [True: 0, False: 0]
  Branch (66:73): [True: 0, False: 0]
67
0
        return 0;
68
0
    }
69
0
    seckey += 3;
70
    /* sequence element 1: octet string, up to 32 bytes */
71
0
    if (end - seckey < 2 || seckey[0] != 0x04u) {
  Branch (71:9): [True: 0, False: 0]
  Branch (71:29): [True: 0, False: 0]
72
0
        return 0;
73
0
    }
74
0
    ptrdiff_t oslen = seckey[1];
75
0
    seckey += 2;
76
0
    if (oslen > 32 || end - seckey < oslen) {
  Branch (76:9): [True: 0, False: 0]
  Branch (76:23): [True: 0, False: 0]
77
0
        return 0;
78
0
    }
79
0
    memcpy(out32 + (32 - oslen), seckey, oslen);
80
0
    if (!secp256k1_ec_seckey_verify(ctx, out32)) {
  Branch (80:9): [True: 0, False: 0]
81
0
        memset(out32, 0, 32);
82
0
        return 0;
83
0
    }
84
0
    return 1;
85
0
}
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
0
int ec_seckey_export_der(const secp256k1_context *ctx, unsigned char *seckey, size_t *seckeylen, const unsigned char *key32, bool compressed) {
98
0
    assert(*seckeylen >= CKey::SIZE);
  Branch (98:5): [True: 0, False: 0]
99
0
    secp256k1_pubkey pubkey;
100
0
    size_t pubkeylen = 0;
101
0
    if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
  Branch (101:9): [True: 0, False: 0]
102
0
        *seckeylen = 0;
103
0
        return 0;
104
0
    }
105
0
    if (compressed) {
  Branch (105:9): [True: 0, False: 0]
106
0
        static const unsigned char begin[] = {
107
0
            0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
108
0
        };
109
0
        static const unsigned char middle[] = {
110
0
            0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
111
0
            0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
112
0
            0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
113
0
            0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
114
0
            0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
115
0
            0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
116
0
            0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
117
0
            0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
118
0
            0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
119
0
        };
120
0
        unsigned char *ptr = seckey;
121
0
        memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
122
0
        memcpy(ptr, key32, 32); ptr += 32;
123
0
        memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
124
0
        pubkeylen = CPubKey::COMPRESSED_SIZE;
125
0
        secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
126
0
        ptr += pubkeylen;
127
0
        *seckeylen = ptr - seckey;
128
0
        assert(*seckeylen == CKey::COMPRESSED_SIZE);
  Branch (128:9): [True: 0, False: 0]
129
0
    } else {
130
0
        static const unsigned char begin[] = {
131
0
            0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
132
0
        };
133
0
        static const unsigned char middle[] = {
134
0
            0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
135
0
            0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
136
0
            0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
137
0
            0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
138
0
            0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
139
0
            0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
140
0
            0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
141
0
            0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
142
0
            0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
143
0
            0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
144
0
            0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
145
0
        };
146
0
        unsigned char *ptr = seckey;
147
0
        memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
148
0
        memcpy(ptr, key32, 32); ptr += 32;
149
0
        memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
150
0
        pubkeylen = CPubKey::SIZE;
151
0
        secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
152
0
        ptr += pubkeylen;
153
0
        *seckeylen = ptr - seckey;
154
0
        assert(*seckeylen == CKey::SIZE);
  Branch (154:9): [True: 0, False: 0]
155
0
    }
156
0
    return 1;
157
0
}
158
159
0
bool CKey::Check(const unsigned char *vch) {
160
0
    return secp256k1_ec_seckey_verify(secp256k1_context_static, vch);
161
0
}
162
163
0
void CKey::MakeNewKey(bool fCompressedIn) {
164
0
    MakeKeyData();
165
0
    do {
166
0
        GetStrongRandBytes(*keydata);
167
0
    } while (!Check(keydata->data()));
  Branch (167:14): [True: 0, False: 0]
168
0
    fCompressed = fCompressedIn;
169
0
}
170
171
0
CPrivKey CKey::GetPrivKey() const {
172
0
    assert(keydata);
  Branch (172:5): [True: 0, False: 0]
173
0
    CPrivKey seckey;
174
0
    int ret;
175
0
    size_t seckeylen;
176
0
    seckey.resize(SIZE);
177
0
    seckeylen = SIZE;
178
0
    ret = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, UCharCast(begin()), fCompressed);
179
0
    assert(ret);
  Branch (179:5): [True: 0, False: 0]
180
0
    seckey.resize(seckeylen);
181
0
    return seckey;
182
0
}
183
184
0
CPubKey CKey::GetPubKey() const {
185
0
    assert(keydata);
  Branch (185:5): [True: 0, False: 0]
186
0
    secp256k1_pubkey pubkey;
187
0
    size_t clen = CPubKey::SIZE;
188
0
    CPubKey result;
189
0
    int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, UCharCast(begin()));
190
0
    assert(ret);
  Branch (190:5): [True: 0, False: 0]
191
0
    secp256k1_ec_pubkey_serialize(secp256k1_context_static, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
  Branch (191:109): [True: 0, False: 0]
192
0
    assert(result.size() == clen);
  Branch (192:5): [True: 0, False: 0]
193
0
    assert(result.IsValid());
  Branch (193:5): [True: 0, False: 0]
194
0
    return result;
195
0
}
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
0
{
200
0
    unsigned char compact_sig[64];
201
0
    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
0
    return compact_sig[0] < 0x80;
208
0
}
209
210
0
bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const {
211
0
    if (!keydata)
  Branch (211:9): [True: 0, False: 0]
212
0
        return false;
213
0
    vchSig.resize(CPubKey::SIGNATURE_SIZE);
214
0
    size_t nSigLen = CPubKey::SIGNATURE_SIZE;
215
0
    unsigned char extra_entropy[32] = {0};
216
0
    WriteLE32(extra_entropy, test_case);
217
0
    secp256k1_ecdsa_signature sig;
218
0
    uint32_t counter = 0;
219
0
    int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr);
  Branch (219:135): [True: 0, False: 0]
  Branch (219:145): [True: 0, False: 0]
220
221
    // Grind for low R
222
0
    while (ret && !SigHasLowR(&sig) && grind) {
  Branch (222:12): [True: 0, False: 0]
  Branch (222:19): [True: 0, False: 0]
  Branch (222:40): [True: 0, False: 0]
223
0
        WriteLE32(extra_entropy, ++counter);
224
0
        ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, extra_entropy);
225
0
    }
226
0
    assert(ret);
  Branch (226:5): [True: 0, False: 0]
227
0
    secp256k1_ecdsa_signature_serialize_der(secp256k1_context_static, vchSig.data(), &nSigLen, &sig);
228
0
    vchSig.resize(nSigLen);
229
    // Additional verification step to prevent using a potentially corrupted signature
230
0
    secp256k1_pubkey pk;
231
0
    ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pk, UCharCast(begin()));
232
0
    assert(ret);
  Branch (232:5): [True: 0, False: 0]
233
0
    ret = secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pk);
234
0
    assert(ret);
  Branch (234:5): [True: 0, False: 0]
235
0
    return true;
236
0
}
237
238
0
bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
239
0
    if (pubkey.IsCompressed() != fCompressed) {
  Branch (239:9): [True: 0, False: 0]
240
0
        return false;
241
0
    }
242
0
    unsigned char rnd[8];
243
0
    std::string str = "Bitcoin key verification\n";
244
0
    GetRandBytes(rnd);
245
0
    uint256 hash{Hash(str, rnd)};
246
0
    std::vector<unsigned char> vchSig;
247
0
    Sign(hash, vchSig);
248
0
    return pubkey.Verify(hash, vchSig);
249
0
}
250
251
0
bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
252
0
    if (!keydata)
  Branch (252:9): [True: 0, False: 0]
253
0
        return false;
254
0
    vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
255
0
    int rec = -1;
256
0
    secp256k1_ecdsa_recoverable_signature rsig;
257
0
    int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &rsig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, nullptr);
258
0
    assert(ret);
  Branch (258:5): [True: 0, False: 0]
259
0
    ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_static, &vchSig[1], &rec, &rsig);
260
0
    assert(ret);
  Branch (260:5): [True: 0, False: 0]
261
0
    assert(rec != -1);
  Branch (261:5): [True: 0, False: 0]
262
0
    vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
  Branch (262:29): [True: 0, False: 0]
263
    // Additional verification step to prevent using a potentially corrupted signature
264
0
    secp256k1_pubkey epk, rpk;
265
0
    ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &epk, UCharCast(begin()));
266
0
    assert(ret);
  Branch (266:5): [True: 0, False: 0]
267
0
    ret = secp256k1_ecdsa_recover(secp256k1_context_static, &rpk, &rsig, hash.begin());
268
0
    assert(ret);
  Branch (268:5): [True: 0, False: 0]
269
0
    ret = secp256k1_ec_pubkey_cmp(secp256k1_context_static, &epk, &rpk);
270
0
    assert(ret == 0);
  Branch (270:5): [True: 0, False: 0]
271
0
    return true;
272
0
}
273
274
bool CKey::SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const
275
0
{
276
0
    KeyPair kp = ComputeKeyPair(merkle_root);
277
0
    return kp.SignSchnorr(hash, sig, aux);
278
0
}
279
280
0
bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
281
0
    MakeKeyData();
282
0
    if (!ec_seckey_import_der(secp256k1_context_static, (unsigned char*)begin(), seckey.data(), seckey.size())) {
  Branch (282:9): [True: 0, False: 0]
283
0
        ClearKeyData();
284
0
        return false;
285
0
    }
286
0
    fCompressed = vchPubKey.IsCompressed();
287
288
0
    if (fSkipCheck)
  Branch (288:9): [True: 0, False: 0]
289
0
        return true;
290
291
0
    return VerifyPubKey(vchPubKey);
292
0
}
293
294
0
bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
295
0
    assert(IsValid());
  Branch (295:5): [True: 0, False: 0]
296
0
    assert(IsCompressed());
  Branch (296:5): [True: 0, False: 0]
297
0
    std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
298
0
    if ((nChild >> 31) == 0) {
  Branch (298:9): [True: 0, False: 0]
299
0
        CPubKey pubkey = GetPubKey();
300
0
        assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
  Branch (300:9): [True: 0, False: 0]
301
0
        BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
302
0
    } else {
303
0
        assert(size() == 32);
  Branch (303:9): [True: 0, False: 0]
304
0
        BIP32Hash(cc, nChild, 0, UCharCast(begin()), vout.data());
305
0
    }
306
0
    memcpy(ccChild.begin(), vout.data()+32, 32);
307
0
    keyChild.Set(begin(), begin() + 32, true);
308
0
    bool ret = secp256k1_ec_seckey_tweak_add(secp256k1_context_static, (unsigned char*)keyChild.begin(), vout.data());
309
0
    if (!ret) keyChild.ClearKeyData();
  Branch (309:9): [True: 0, False: 0]
310
0
    return ret;
311
0
}
312
313
EllSwiftPubKey CKey::EllSwiftCreate(std::span<const std::byte> ent32) const
314
0
{
315
0
    assert(keydata);
  Branch (315:5): [True: 0, False: 0]
316
0
    assert(ent32.size() == 32);
  Branch (316:5): [True: 0, False: 0]
317
0
    std::array<std::byte, EllSwiftPubKey::size()> encoded_pubkey;
318
319
0
    auto success = secp256k1_ellswift_create(secp256k1_context_sign,
320
0
                                             UCharCast(encoded_pubkey.data()),
321
0
                                             keydata->data(),
322
0
                                             UCharCast(ent32.data()));
323
324
    // Should always succeed for valid keys (asserted above).
325
0
    assert(success);
  Branch (325:5): [True: 0, False: 0]
326
0
    return {encoded_pubkey};
327
0
}
328
329
ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, const EllSwiftPubKey& our_ellswift, bool initiating) const
330
0
{
331
0
    assert(keydata);
  Branch (331:5): [True: 0, False: 0]
332
333
0
    ECDHSecret output;
334
    // BIP324 uses the initiator as party A, and the responder as party B. Remap the inputs
335
    // accordingly:
336
0
    bool success = secp256k1_ellswift_xdh(secp256k1_context_static,
337
0
                                          UCharCast(output.data()),
338
0
                                          UCharCast(initiating ? our_ellswift.data() : their_ellswift.data()),
  Branch (338:53): [True: 0, False: 0]
339
0
                                          UCharCast(initiating ? their_ellswift.data() : our_ellswift.data()),
  Branch (339:53): [True: 0, False: 0]
340
0
                                          keydata->data(),
341
0
                                          initiating ? 0 : 1,
  Branch (341:43): [True: 0, False: 0]
342
0
                                          secp256k1_ellswift_xdh_hash_function_bip324,
343
0
                                          nullptr);
344
    // Should always succeed for valid keys (assert above).
345
0
    assert(success);
  Branch (345:5): [True: 0, False: 0]
346
0
    return output;
347
0
}
348
349
KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const
350
0
{
351
0
    return KeyPair(*this, merkle_root);
352
0
}
353
354
CKey GenerateRandomKey(bool compressed) noexcept
355
0
{
356
0
    CKey key;
357
0
    key.MakeNewKey(/*fCompressed=*/compressed);
358
0
    return key;
359
0
}
360
361
0
bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
362
0
    if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
  Branch (362:9): [True: 0, False: 0]
363
0
    out.nDepth = nDepth + 1;
364
0
    out.fingerprint = id_key_fingerprint();
365
0
    out.nChild = _nChild;
366
0
    return key.Derive(out.key, out.chaincode, _nChild, chaincode);
367
0
}
368
369
std::optional<std::pair<CExtKey, KeyOriginInfo>> DeriveExtKey(const CExtKey& ext_key, const std::vector<uint32_t>& path)
370
0
{
371
0
    CExtKey descendant = ext_key;
372
0
    KeyOriginInfo origin;
373
0
    origin.fingerprint = ext_key.id_key_fingerprint();
374
0
    origin.path = path;
375
0
    for (uint32_t i : path) {
  Branch (375:21): [True: 0, False: 0]
376
0
        if (!descendant.Derive(descendant, i)) return std::nullopt;
  Branch (376:13): [True: 0, False: 0]
377
0
    }
378
0
    return std::make_pair(descendant, origin);
379
0
}
380
381
void CExtKey::SetSeed(std::span<const std::byte> seed)
382
0
{
383
0
    Assert(16 <= seed.size() && seed.size() <= 64);
384
0
    static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
385
0
    std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
386
0
    CHMAC_SHA512{hashkey, sizeof(hashkey)}.Write(UCharCast(seed.data()), seed.size()).Finalize(vout.data());
387
0
    key.Set(vout.data(), vout.data() + 32, true);
388
0
    memcpy(chaincode.begin(), vout.data() + 32, 32);
389
0
    nDepth = 0;
390
0
    nChild = 0;
391
0
    fingerprint.fill(0);
392
0
}
393
394
0
CExtPubKey CExtKey::Neuter() const {
395
0
    CExtPubKey ret;
396
0
    ret.nDepth = nDepth;
397
0
    ret.fingerprint = fingerprint;
398
0
    ret.nChild = nChild;
399
0
    ret.pubkey = key.GetPubKey();
400
0
    ret.chaincode = chaincode;
401
0
    return ret;
402
0
}
403
404
KeyPair::KeyPair(const CKey& key, const uint256* merkle_root)
405
0
{
406
0
    static_assert(std::tuple_size<KeyType>() == sizeof(secp256k1_keypair));
407
0
    MakeKeyPairData();
408
0
    auto keypair = reinterpret_cast<secp256k1_keypair*>(m_keypair->data());
409
0
    bool success = secp256k1_keypair_create(secp256k1_context_sign, keypair, UCharCast(key.data()));
410
0
    if (success && merkle_root) {
  Branch (410:9): [True: 0, False: 0]
  Branch (410:20): [True: 0, False: 0]
411
0
        secp256k1_xonly_pubkey pubkey;
412
0
        unsigned char pubkey_bytes[32];
413
0
        assert(secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey, nullptr, keypair));
  Branch (413:9): [True: 0, False: 0]
414
0
        assert(secp256k1_xonly_pubkey_serialize(secp256k1_context_static, pubkey_bytes, &pubkey));
  Branch (414:9): [True: 0, False: 0]
415
0
        uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
  Branch (415:71): [True: 0, False: 0]
416
0
        success = secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, keypair, tweak.data());
417
0
    }
418
0
    if (!success) ClearKeyPairData();
  Branch (418:9): [True: 0, False: 0]
419
0
}
420
421
bool KeyPair::SignSchnorr(const uint256& hash, std::span<unsigned char> sig, const uint256& aux) const
422
0
{
423
0
    assert(sig.size() == 64);
  Branch (423:5): [True: 0, False: 0]
424
0
    if (!IsValid()) return false;
  Branch (424:9): [True: 0, False: 0]
425
0
    auto keypair = reinterpret_cast<const secp256k1_keypair*>(m_keypair->data());
426
0
    bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), keypair, aux.data());
427
0
    if (ret) {
  Branch (427:9): [True: 0, False: 0]
428
        // Additional verification step to prevent using a potentially corrupted signature
429
0
        secp256k1_xonly_pubkey pubkey_verify;
430
0
        ret = secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey_verify, nullptr, keypair);
431
0
        ret &= secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), hash.begin(), 32, &pubkey_verify);
432
0
    }
433
0
    if (!ret) memory_cleanse(sig.data(), sig.size());
  Branch (433:9): [True: 0, False: 0]
434
0
    return ret;
435
0
}
436
437
0
bool ECC_InitSanityCheck() {
438
0
    CKey key = GenerateRandomKey();
439
0
    CPubKey pubkey = key.GetPubKey();
440
0
    return key.VerifyPubKey(pubkey);
441
0
}
442
443
secp256k1_context* GetSecp256k1SignContext()
444
0
{
445
0
    return secp256k1_context_sign;
446
0
}
447
448
/** Initialize the elliptic curve support. May not be called twice without calling ECC_Stop first. */
449
0
static void ECC_Start() {
450
0
    assert(secp256k1_context_sign == nullptr);
  Branch (450:5): [True: 0, False: 0]
451
452
0
    secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
453
0
    assert(ctx != nullptr);
  Branch (453:5): [True: 0, False: 0]
454
455
0
    {
456
        // Pass in a random blinding seed to the secp256k1 context.
457
0
        std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
458
0
        GetRandBytes(vseed);
459
0
        bool ret = secp256k1_context_randomize(ctx, vseed.data());
460
0
        assert(ret);
  Branch (460:9): [True: 0, False: 0]
461
0
    }
462
463
0
    secp256k1_context_sign = ctx;
464
0
}
465
466
/** Deinitialize the elliptic curve support. No-op if ECC_Start wasn't called first. */
467
1
static void ECC_Stop() {
468
1
    secp256k1_context *ctx = secp256k1_context_sign;
469
1
    secp256k1_context_sign = nullptr;
470
471
1
    if (ctx) {
  Branch (471:9): [True: 1, False: 0]
472
1
        secp256k1_context_destroy(ctx);
473
1
    }
474
1
}
475
476
ECC_Context::ECC_Context()
477
0
{
478
0
    ECC_Start();
479
0
}
480
481
ECC_Context::~ECC_Context()
482
1
{
483
1
    ECC_Stop();
484
1
}