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 <pubkey.h>
7 : :
8 : : #include <hash.h>
9 : : #include <secp256k1.h>
10 : : #include <secp256k1_ellswift.h>
11 : : #include <secp256k1_extrakeys.h>
12 : : #include <secp256k1_recovery.h>
13 : : #include <secp256k1_schnorrsig.h>
14 : : #include <span.h>
15 : : #include <uint256.h>
16 : : #include <util/strencodings.h>
17 : :
18 : : #include <algorithm>
19 : : #include <cassert>
20 : :
21 : : using namespace util::hex_literals;
22 : :
23 : : namespace {
24 : :
25 : : struct Secp256k1SelfTester
26 : : {
27 : : Secp256k1SelfTester() {
28 : : /* Run libsecp256k1 self-test before using the secp256k1_context_static. */
29 : : secp256k1_selftest();
30 : : }
31 : : } SECP256K1_SELFTESTER;
32 : :
33 : : } // namespace
34 : :
35 : : /** This function is taken from the libsecp256k1 distribution and implements
36 : : * DER parsing for ECDSA signatures, while supporting an arbitrary subset of
37 : : * format violations.
38 : : *
39 : : * Supported violations include negative integers, excessive padding, garbage
40 : : * at the end, and overly long length descriptors. This is safe to use in
41 : : * Bitcoin because since the activation of BIP66, signatures are verified to be
42 : : * strict DER before being passed to this module, and we know it supports all
43 : : * violations present in the blockchain before that point.
44 : : */
45 : 150559 : int ecdsa_signature_parse_der_lax(secp256k1_ecdsa_signature* sig, const unsigned char *input, size_t inputlen) {
46 : 150559 : size_t rpos, rlen, spos, slen;
47 : 150559 : size_t pos = 0;
48 : 150559 : size_t lenbyte;
49 : 150559 : unsigned char tmpsig[64] = {0};
50 : 150559 : int overflow = 0;
51 : :
52 : : /* Hack to initialize sig with a correctly-parsed but invalid signature. */
53 : 150559 : secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
54 : :
55 : : /* Sequence tag byte */
56 [ + + + - ]: 150559 : if (pos == inputlen || input[pos] != 0x30) {
57 : : return 0;
58 : : }
59 : 150523 : pos++;
60 : :
61 : : /* Sequence length bytes */
62 [ + - ]: 150523 : if (pos == inputlen) {
63 : : return 0;
64 : : }
65 : 150523 : lenbyte = input[pos++];
66 [ - + ]: 150523 : if (lenbyte & 0x80) {
67 : 0 : lenbyte -= 0x80;
68 [ # # ]: 0 : if (lenbyte > inputlen - pos) {
69 : : return 0;
70 : : }
71 : 0 : pos += lenbyte;
72 : : }
73 : :
74 : : /* Integer tag byte for R */
75 [ + - + - ]: 150523 : if (pos == inputlen || input[pos] != 0x02) {
76 : : return 0;
77 : : }
78 : 150523 : pos++;
79 : :
80 : : /* Integer length for R */
81 [ + - ]: 150523 : if (pos == inputlen) {
82 : : return 0;
83 : : }
84 : 150523 : lenbyte = input[pos++];
85 [ - + ]: 150523 : if (lenbyte & 0x80) {
86 : 0 : lenbyte -= 0x80;
87 [ # # ]: 0 : if (lenbyte > inputlen - pos) {
88 : : return 0;
89 : : }
90 [ # # # # ]: 0 : while (lenbyte > 0 && input[pos] == 0) {
91 : 0 : pos++;
92 : 0 : lenbyte--;
93 : : }
94 : 0 : static_assert(sizeof(size_t) >= 4, "size_t too small");
95 [ # # ]: 0 : if (lenbyte >= 4) {
96 : : return 0;
97 : : }
98 : : rlen = 0;
99 [ # # ]: 0 : while (lenbyte > 0) {
100 : 0 : rlen = (rlen << 8) + input[pos];
101 : 0 : pos++;
102 : 0 : lenbyte--;
103 : : }
104 : : } else {
105 : : rlen = lenbyte;
106 : : }
107 [ + - ]: 150523 : if (rlen > inputlen - pos) {
108 : : return 0;
109 : : }
110 : 150523 : rpos = pos;
111 : 150523 : pos += rlen;
112 : :
113 : : /* Integer tag byte for S */
114 [ + - + - ]: 150523 : if (pos == inputlen || input[pos] != 0x02) {
115 : : return 0;
116 : : }
117 : 150523 : pos++;
118 : :
119 : : /* Integer length for S */
120 [ + - ]: 150523 : if (pos == inputlen) {
121 : : return 0;
122 : : }
123 : 150523 : lenbyte = input[pos++];
124 [ - + ]: 150523 : if (lenbyte & 0x80) {
125 : 0 : lenbyte -= 0x80;
126 [ # # ]: 0 : if (lenbyte > inputlen - pos) {
127 : : return 0;
128 : : }
129 [ # # # # ]: 0 : while (lenbyte > 0 && input[pos] == 0) {
130 : 0 : pos++;
131 : 0 : lenbyte--;
132 : : }
133 : 0 : static_assert(sizeof(size_t) >= 4, "size_t too small");
134 [ # # ]: 0 : if (lenbyte >= 4) {
135 : : return 0;
136 : : }
137 : : slen = 0;
138 [ # # ]: 0 : while (lenbyte > 0) {
139 : 0 : slen = (slen << 8) + input[pos];
140 : 0 : pos++;
141 : 0 : lenbyte--;
142 : : }
143 : : } else {
144 : : slen = lenbyte;
145 : : }
146 [ + - ]: 150523 : if (slen > inputlen - pos) {
147 : : return 0;
148 : : }
149 : 179468 : spos = pos;
150 : :
151 : : /* Ignore leading zeroes in R */
152 [ + - + + ]: 179468 : while (rlen > 0 && input[rpos] == 0) {
153 : 28945 : rlen--;
154 : 28945 : rpos++;
155 : : }
156 : : /* Copy R value */
157 [ + + ]: 150523 : if (rlen > 32) {
158 : 150523 : overflow = 1;
159 : : } else {
160 : 150522 : memcpy(tmpsig + 32 - rlen, input + rpos, rlen);
161 : : }
162 : :
163 : : /* Ignore leading zeroes in S */
164 [ + - + + ]: 152396 : while (slen > 0 && input[spos] == 0) {
165 : 1873 : slen--;
166 : 1873 : spos++;
167 : : }
168 : : /* Copy S value */
169 [ + - ]: 150523 : if (slen > 32) {
170 : : overflow = 1;
171 : : } else {
172 [ + + ]: 150523 : memcpy(tmpsig + 64 - slen, input + spos, slen);
173 : : }
174 : :
175 [ + + ]: 150523 : if (!overflow) {
176 : 150522 : overflow = !secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
177 : : }
178 [ - + ]: 150522 : if (overflow) {
179 : : /* Overwrite the result again with a correctly-parsed but invalid
180 : : signature if parsing failed. */
181 : 1 : memset(tmpsig, 0, 64);
182 : 1 : secp256k1_ecdsa_signature_parse_compact(secp256k1_context_static, sig, tmpsig);
183 : : }
184 : : return 1;
185 : : }
186 : :
187 : : /** Nothing Up My Sleeve (NUMS) point
188 : : *
189 : : * NUMS_H is a point with an unknown discrete logarithm, constructed by taking the sha256 of 'g'
190 : : * (uncompressed encoding), which happens to be a point on the curve.
191 : : *
192 : : * For an example script for calculating H, refer to the unit tests in
193 : : * ./test/functional/test_framework/crypto/secp256k1.py
194 : : */
195 : : constexpr XOnlyPubKey XOnlyPubKey::NUMS_H{
196 : : // Use immediate lambda to work around GCC-14 bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=117966
197 : : []() consteval { return XOnlyPubKey{"50929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"_hex_u8}; }(),
198 : : };
199 : :
200 : 395255 : std::vector<CPubKey> XOnlyPubKey::GetCPubKeys() const
201 : : {
202 : 395255 : std::vector<CPubKey> out;
203 : 395255 : unsigned char b[33] = {0x02};
204 : 395255 : std::copy(m_keydata.begin(), m_keydata.end(), b + 1);
205 : 395255 : CPubKey fullpubkey;
206 : 395255 : fullpubkey.Set(b, b + 33);
207 [ + - ]: 395255 : out.push_back(fullpubkey);
208 : 395255 : b[0] = 0x03;
209 : 395255 : fullpubkey.Set(b, b + 33);
210 [ + - ]: 395255 : out.push_back(fullpubkey);
211 : 395255 : return out;
212 : 0 : }
213 : :
214 : 395255 : std::vector<CKeyID> XOnlyPubKey::GetKeyIDs() const
215 : : {
216 : 395255 : std::vector<CKeyID> out;
217 [ + - + + ]: 1185765 : for (const CPubKey& pk : GetCPubKeys()) {
218 [ + - ]: 1581020 : out.push_back(pk.GetID());
219 : 0 : }
220 : 395255 : return out;
221 : 0 : }
222 : :
223 : 133228 : CPubKey XOnlyPubKey::GetEvenCorrespondingCPubKey() const
224 : : {
225 : 133228 : unsigned char full_key[CPubKey::COMPRESSED_SIZE] = {0x02};
226 : 133228 : std::copy(begin(), end(), full_key + 1);
227 : 133228 : return CPubKey{full_key};
228 : : }
229 : :
230 : 153330 : bool XOnlyPubKey::IsFullyValid() const
231 : : {
232 : 153330 : secp256k1_xonly_pubkey pubkey;
233 : 153330 : return secp256k1_xonly_pubkey_parse(secp256k1_context_static, &pubkey, m_keydata.data());
234 : : }
235 : :
236 : 9259 : bool XOnlyPubKey::VerifySchnorr(const uint256& msg, std::span<const unsigned char> sigbytes) const
237 : : {
238 [ - + ]: 9259 : assert(sigbytes.size() == 64);
239 : 9259 : secp256k1_xonly_pubkey pubkey;
240 [ + + ]: 9259 : if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &pubkey, m_keydata.data())) return false;
241 : 9257 : return secp256k1_schnorrsig_verify(secp256k1_context_static, sigbytes.data(), msg.begin(), 32, &pubkey);
242 : : }
243 : :
244 : : static const HashWriter HASHER_TAPTWEAK{TaggedHash("TapTweak")};
245 : :
246 : 211165 : uint256 XOnlyPubKey::ComputeTapTweakHash(const uint256* merkle_root) const
247 : : {
248 [ + + ]: 211165 : if (merkle_root == nullptr) {
249 : : // We have no scripts. The actual tweak does not matter, but follow BIP341 here to
250 : : // allow for reproducible tweaking.
251 : 115655 : return (HashWriter{HASHER_TAPTWEAK} << m_keydata).GetSHA256();
252 : : } else {
253 : 95510 : return (HashWriter{HASHER_TAPTWEAK} << m_keydata << *merkle_root).GetSHA256();
254 : : }
255 : : }
256 : :
257 : 78049 : bool XOnlyPubKey::CheckTapTweak(const XOnlyPubKey& internal, const uint256& merkle_root, bool parity) const
258 : : {
259 : 78049 : secp256k1_xonly_pubkey internal_key;
260 [ + + ]: 78049 : if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &internal_key, internal.data())) return false;
261 : 78045 : uint256 tweak = internal.ComputeTapTweakHash(&merkle_root);
262 : 78045 : return secp256k1_xonly_pubkey_tweak_add_check(secp256k1_context_static, m_keydata.begin(), parity, &internal_key, tweak.begin());
263 : : }
264 : :
265 : 132509 : std::optional<std::pair<XOnlyPubKey, bool>> XOnlyPubKey::CreateTapTweak(const uint256* merkle_root) const
266 : : {
267 : 132509 : secp256k1_xonly_pubkey base_point;
268 [ - + ]: 132509 : if (!secp256k1_xonly_pubkey_parse(secp256k1_context_static, &base_point, data())) return std::nullopt;
269 : 132509 : secp256k1_pubkey out;
270 : 132509 : uint256 tweak = ComputeTapTweakHash(merkle_root);
271 [ - + ]: 132509 : if (!secp256k1_xonly_pubkey_tweak_add(secp256k1_context_static, &out, &base_point, tweak.data())) return std::nullopt;
272 : 132509 : int parity = -1;
273 : 132509 : std::pair<XOnlyPubKey, bool> ret;
274 : 132509 : secp256k1_xonly_pubkey out_xonly;
275 [ - + ]: 132509 : if (!secp256k1_xonly_pubkey_from_pubkey(secp256k1_context_static, &out_xonly, &parity, &out)) return std::nullopt;
276 : 132509 : secp256k1_xonly_pubkey_serialize(secp256k1_context_static, ret.first.begin(), &out_xonly);
277 [ - + ]: 132509 : assert(parity == 0 || parity == 1);
278 : 132509 : ret.second = parity;
279 : 132509 : return ret;
280 : : }
281 : :
282 : :
283 : 97652 : bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const {
284 [ + - ]: 97652 : if (!IsValid())
285 : : return false;
286 : 97652 : secp256k1_pubkey pubkey;
287 : 97652 : secp256k1_ecdsa_signature sig;
288 [ + - ]: 97652 : if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
289 : : return false;
290 : : }
291 [ + + ]: 97652 : if (!ecdsa_signature_parse_der_lax(&sig, vchSig.data(), vchSig.size())) {
292 : : return false;
293 : : }
294 : : /* libsecp256k1's ECDSA verification requires lower-S signatures, which have
295 : : * not historically been enforced in Bitcoin, so normalize them first. */
296 : 97616 : secp256k1_ecdsa_signature_normalize(secp256k1_context_static, &sig, &sig);
297 : 97616 : return secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pubkey);
298 : : }
299 : :
300 : 77 : bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector<unsigned char>& vchSig) {
301 [ + - ]: 77 : if (vchSig.size() != COMPACT_SIGNATURE_SIZE)
302 : : return false;
303 : 77 : int recid = (vchSig[0] - 27) & 3;
304 : 77 : bool fComp = ((vchSig[0] - 27) & 4) != 0;
305 : 77 : secp256k1_pubkey pubkey;
306 : 77 : secp256k1_ecdsa_recoverable_signature sig;
307 [ + - ]: 77 : if (!secp256k1_ecdsa_recoverable_signature_parse_compact(secp256k1_context_static, &sig, &vchSig[1], recid)) {
308 : : return false;
309 : : }
310 [ + + ]: 77 : if (!secp256k1_ecdsa_recover(secp256k1_context_static, &pubkey, &sig, hash.begin())) {
311 : : return false;
312 : : }
313 : 76 : unsigned char pub[SIZE];
314 : 76 : size_t publen = SIZE;
315 [ + + ]: 108 : secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, fComp ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
316 : 76 : Set(pub, pub + publen);
317 : 76 : return true;
318 : : }
319 : :
320 : 50374 : bool CPubKey::IsFullyValid() const {
321 [ + + ]: 50374 : if (!IsValid())
322 : : return false;
323 : 31830 : secp256k1_pubkey pubkey;
324 : 31830 : return secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size());
325 : : }
326 : :
327 : 122 : bool CPubKey::Decompress() {
328 [ + - ]: 122 : if (!IsValid())
329 : : return false;
330 : 122 : secp256k1_pubkey pubkey;
331 [ + + ]: 122 : if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
332 : : return false;
333 : : }
334 : 120 : unsigned char pub[SIZE];
335 : 120 : size_t publen = SIZE;
336 : 120 : secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
337 : 120 : Set(pub, pub + publen);
338 : 120 : return true;
339 : : }
340 : :
341 : 668829 : bool CPubKey::Derive(CPubKey& pubkeyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
342 [ - + ]: 668829 : assert(IsValid());
343 [ - + ]: 668829 : assert((nChild >> 31) == 0);
344 [ - + ]: 668829 : assert(size() == COMPRESSED_SIZE);
345 : 668829 : unsigned char out[64];
346 : 668829 : BIP32Hash(cc, nChild, *begin(), begin()+1, out);
347 : 668829 : memcpy(ccChild.begin(), out+32, 32);
348 : 668829 : secp256k1_pubkey pubkey;
349 [ + - ]: 668829 : if (!secp256k1_ec_pubkey_parse(secp256k1_context_static, &pubkey, vch, size())) {
350 : : return false;
351 : : }
352 [ + - ]: 668829 : if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_static, &pubkey, out)) {
353 : : return false;
354 : : }
355 : 668829 : unsigned char pub[COMPRESSED_SIZE];
356 : 668829 : size_t publen = COMPRESSED_SIZE;
357 : 668829 : secp256k1_ec_pubkey_serialize(secp256k1_context_static, pub, &publen, &pubkey, SECP256K1_EC_COMPRESSED);
358 : 668829 : pubkeyChild.Set(pub, pub + publen);
359 : 668829 : return true;
360 : : }
361 : :
362 : 705 : EllSwiftPubKey::EllSwiftPubKey(std::span<const std::byte> ellswift) noexcept
363 : : {
364 [ - + ]: 705 : assert(ellswift.size() == SIZE);
365 : 705 : std::copy(ellswift.begin(), ellswift.end(), m_pubkey.begin());
366 : 705 : }
367 : :
368 : 4 : CPubKey EllSwiftPubKey::Decode() const
369 : : {
370 : 4 : secp256k1_pubkey pubkey;
371 : 4 : secp256k1_ellswift_decode(secp256k1_context_static, &pubkey, UCharCast(m_pubkey.data()));
372 : :
373 : 4 : size_t sz = CPubKey::COMPRESSED_SIZE;
374 : 4 : std::array<uint8_t, CPubKey::COMPRESSED_SIZE> vch_bytes;
375 : :
376 : 4 : secp256k1_ec_pubkey_serialize(secp256k1_context_static, vch_bytes.data(), &sz, &pubkey, SECP256K1_EC_COMPRESSED);
377 [ - + ]: 4 : assert(sz == vch_bytes.size());
378 : :
379 : 4 : return CPubKey{vch_bytes.begin(), vch_bytes.end()};
380 : : }
381 : :
382 : 145231 : void CExtPubKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
383 : 145231 : code[0] = nDepth;
384 : 145231 : memcpy(code+1, vchFingerprint, 4);
385 : 145231 : WriteBE32(code+5, nChild);
386 [ - + ]: 145231 : memcpy(code+9, chaincode.begin(), 32);
387 [ - + ]: 145231 : assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
388 : 145231 : memcpy(code+41, pubkey.begin(), CPubKey::COMPRESSED_SIZE);
389 : 145231 : }
390 : :
391 : 10765 : void CExtPubKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
392 : 10765 : nDepth = code[0];
393 : 10765 : memcpy(vchFingerprint, code+1, 4);
394 : 10765 : nChild = ReadBE32(code+5);
395 : 10765 : memcpy(chaincode.begin(), code+9, 32);
396 : 10765 : pubkey.Set(code+41, code+BIP32_EXTKEY_SIZE);
397 [ + + + + : 10765 : if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || !pubkey.IsFullyValid()) pubkey = CPubKey();
+ + + + ]
398 : 10765 : }
399 : :
400 : 3 : void CExtPubKey::EncodeWithVersion(unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE]) const
401 : : {
402 : 3 : memcpy(code, version, 4);
403 : 3 : Encode(&code[4]);
404 : 3 : }
405 : :
406 : 3 : void CExtPubKey::DecodeWithVersion(const unsigned char code[BIP32_EXTKEY_WITH_VERSION_SIZE])
407 : : {
408 : 3 : memcpy(version, code, 4);
409 : 3 : Decode(&code[4]);
410 : 3 : }
411 : :
412 : 668830 : bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const {
413 [ + + ]: 668830 : if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
414 : 668829 : out.nDepth = nDepth + 1;
415 : 668829 : CKeyID id = pubkey.GetID();
416 : 668829 : memcpy(out.vchFingerprint, &id, 4);
417 : 668829 : out.nChild = _nChild;
418 : 668829 : return pubkey.Derive(out.pubkey, out.chaincode, _nChild, chaincode);
419 : : }
420 : :
421 : 52907 : /* static */ bool CPubKey::CheckLowS(const std::vector<unsigned char>& vchSig) {
422 : 52907 : secp256k1_ecdsa_signature sig;
423 [ + - ]: 52907 : if (!ecdsa_signature_parse_der_lax(&sig, vchSig.data(), vchSig.size())) {
424 : : return false;
425 : : }
426 : 52907 : return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_static, nullptr, &sig));
427 : : }
|