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