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