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