Line data Source code
1 : // Copyright (c) 2009-2017 The Bitcoin developers
2 : // Copyright (c) 2017-2021 The PIVX Core 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_recovery.h>
14 :
15 : static secp256k1_context* secp256k1_context_sign = nullptr;
16 :
17 : /** These functions are taken from the libsecp256k1 distribution and are very ugly. */
18 :
19 : /**
20 : * This parses a format loosely based on a DER encoding of the ECPrivateKey type from
21 : * section C.4 of SEC 1 <http://www.secg.org/sec1-v2.pdf>, with the following caveats:
22 : *
23 : * * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not
24 : * required to be encoded as one octet if it is less than 256, as DER would require.
25 : * * The octet-length of the SEQUENCE must not be greater than the remaining
26 : * length of the key encoding, but need not match it (i.e. the encoding may contain
27 : * junk after the encoded SEQUENCE).
28 : * * The privateKey OCTET STRING is zero-filled on the left to 32 octets.
29 : * * Anything after the encoding of the privateKey OCTET STRING is ignored, whether
30 : * or not it is validly encoded DER.
31 : *
32 : * out32 must point to an output buffer of length at least 32 bytes.
33 : */
34 7787 : static int ec_privkey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *privkey, size_t privkeylen) {
35 7787 : const unsigned char *end = privkey + privkeylen;
36 7787 : memset(out32, 0, 32);
37 : /* sequence header */
38 7787 : if (end - privkey < 1 || *privkey != 0x30u) {
39 : return 0;
40 : }
41 7787 : privkey++;
42 : /* sequence length constructor */
43 7787 : if (end - privkey < 1 || !(*privkey & 0x80u)) {
44 : return 0;
45 : }
46 7787 : ptrdiff_t lenb = *privkey & ~0x80u; privkey++;
47 7787 : if (lenb < 1 || lenb > 2) {
48 : return 0;
49 : }
50 7787 : if (end - privkey < lenb) {
51 : return 0;
52 : }
53 : /* sequence length */
54 7787 : ptrdiff_t len = privkey[lenb-1] | (lenb > 1 ? privkey[lenb-2] << 8 : 0u);
55 7787 : privkey += lenb;
56 7787 : if (end - privkey < len) {
57 : return 0;
58 : }
59 : /* sequence element 0: version number (=1) */
60 7787 : if (end - privkey < 3 || privkey[0] != 0x02u || privkey[1] != 0x01u || privkey[2] != 0x01u) {
61 : return 0;
62 : }
63 7787 : privkey += 3;
64 : /* sequence element 1: octet string, up to 32 bytes */
65 7787 : if (end - privkey < 2 || privkey[0] != 0x04u) {
66 : return 0;
67 : }
68 7787 : ptrdiff_t oslen = privkey[1];
69 7787 : privkey += 2;
70 7787 : if (oslen > 32 || end - privkey < oslen) {
71 : return 0;
72 : }
73 7787 : memcpy(out32 + (32 - oslen), privkey, oslen);
74 7787 : if (!secp256k1_ec_seckey_verify(ctx, out32)) {
75 0 : memset(out32, 0, 32);
76 0 : return 0;
77 : }
78 : return 1;
79 : }
80 :
81 : /**
82 : * This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1
83 : * <http://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are
84 : * included.
85 : *
86 : * privkey must point to an output buffer of length at least CKey::PRIVATE_KEY_SIZE bytes.
87 : * privkeylen must initially be set to the size of the privkey buffer. Upon return it
88 : * will be set to the number of bytes used in the buffer.
89 : * key32 must point to a 32-byte raw private key.
90 : */
91 13350 : static int ec_privkey_export_der(const secp256k1_context *ctx, unsigned char *privkey, size_t *privkeylen, const unsigned char *key32, int compressed) {
92 13350 : assert(*privkeylen >= CKey::PRIVATE_KEY_SIZE);
93 13350 : secp256k1_pubkey pubkey;
94 13350 : size_t pubkeylen = 0;
95 13350 : if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
96 0 : *privkeylen = 0;
97 0 : return 0;
98 : }
99 13350 : if (compressed) {
100 13350 : static const unsigned char begin[] = {
101 : 0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
102 : };
103 13350 : static const unsigned char middle[] = {
104 : 0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
105 : 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
106 : 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
107 : 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
108 : 0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
109 : 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
110 : 0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
111 : 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
112 : 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
113 : };
114 13350 : unsigned char *ptr = privkey;
115 13350 : memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
116 13350 : memcpy(ptr, key32, 32); ptr += 32;
117 13350 : memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
118 13350 : pubkeylen = CPubKey::COMPRESSED_PUBLIC_KEY_SIZE;
119 13350 : secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
120 13350 : ptr += pubkeylen;
121 13350 : *privkeylen = ptr - privkey;
122 13350 : assert(*privkeylen == CKey::COMPRESSED_PRIVATE_KEY_SIZE);
123 : } else {
124 0 : static const unsigned char begin[] = {
125 : 0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
126 : };
127 0 : static const unsigned char middle[] = {
128 : 0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
129 : 0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
130 : 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
131 : 0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
132 : 0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
133 : 0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
134 : 0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
135 : 0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
136 : 0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
137 : 0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
138 : 0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
139 : };
140 0 : unsigned char *ptr = privkey;
141 0 : memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
142 0 : memcpy(ptr, key32, 32); ptr += 32;
143 0 : memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
144 0 : pubkeylen = CPubKey::PUBLIC_KEY_SIZE;
145 0 : secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
146 0 : ptr += pubkeylen;
147 0 : *privkeylen = ptr - privkey;
148 0 : assert(*privkeylen == CKey::PRIVATE_KEY_SIZE);
149 : }
150 : return 1;
151 : }
152 :
153 16790 : bool CKey::Check(const unsigned char* vch)
154 : {
155 16790 : return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch);
156 : }
157 :
158 1006 : void CKey::MakeNewKey(bool fCompressedIn)
159 : {
160 1006 : do {
161 1006 : GetStrongRandBytes(keydata.data(), keydata.size());
162 1006 : } while (!Check(keydata.data()));
163 1006 : fValid = true;
164 1006 : fCompressed = fCompressedIn;
165 1006 : }
166 :
167 1 : uint256 CKey::GetPrivKey_256()
168 : {
169 1 : void* key = keydata.data();
170 1 : return *(uint256*)key;
171 : }
172 :
173 13350 : CPrivKey CKey::GetPrivKey() const
174 : {
175 13350 : assert(fValid);
176 13350 : CPrivKey privkey;
177 13350 : size_t privkeylen;
178 13350 : privkey.resize(PRIVATE_KEY_SIZE);
179 13350 : privkeylen = PRIVATE_KEY_SIZE;
180 13350 : int ret = ec_privkey_export_der(secp256k1_context_sign, (unsigned char*)privkey.data(), &privkeylen, begin(), fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
181 13350 : assert(ret);
182 13350 : privkey.resize(privkeylen);
183 13350 : return privkey;
184 : }
185 :
186 3678597 : CPubKey CKey::GetPubKey() const
187 : {
188 3678597 : assert(fValid);
189 3678597 : secp256k1_pubkey pubkey;
190 3678597 : size_t clen = CPubKey::PUBLIC_KEY_SIZE;
191 3678597 : CPubKey result;
192 3678597 : int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, begin());
193 3678597 : assert(ret);
194 3683413 : secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
195 3683413 : assert(result.size() == clen);
196 3678597 : assert(result.IsValid());
197 3678597 : return result;
198 : }
199 :
200 230901 : bool CKey::Sign(const uint256& hash, std::vector<unsigned char>& vchSig, uint32_t test_case) const
201 : {
202 230901 : if (!fValid)
203 : return false;
204 230901 : vchSig.resize(CPubKey::SIGNATURE_SIZE);
205 230901 : size_t nSigLen = CPubKey::SIGNATURE_SIZE;
206 230901 : unsigned char extra_entropy[32] = {0};
207 230901 : WriteLE32(extra_entropy, test_case);
208 230901 : secp256k1_ecdsa_signature sig;
209 460646 : int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, test_case ? extra_entropy : nullptr);
210 230901 : assert(ret);
211 230901 : secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, (unsigned char*)vchSig.data(), &nSigLen, &sig);
212 230901 : vchSig.resize(nSigLen);
213 : return true;
214 : }
215 :
216 16138 : bool CKey::VerifyPubKey(const CPubKey& pubkey) const
217 : {
218 16146 : if (pubkey.IsCompressed() != fCompressed) {
219 : return false;
220 : }
221 16130 : unsigned char rnd[8];
222 32268 : std::string str = "Bitcoin key verification\n";
223 16130 : GetRandBytes(rnd, sizeof(rnd));
224 16130 : uint256 hash;
225 16130 : CHash256().Write((unsigned char*)str.data(), str.size()).Write(rnd, sizeof(rnd)).Finalize(hash.begin());
226 32260 : std::vector<unsigned char> vchSig;
227 16130 : Sign(hash, vchSig);
228 16130 : return pubkey.Verify(hash, vchSig);
229 : }
230 :
231 1804 : bool CKey::SignCompact(const uint256& hash, std::vector<unsigned char>& vchSig) const
232 : {
233 1804 : if (!fValid)
234 : return false;
235 1804 : vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
236 1804 : int rec = -1;
237 1804 : secp256k1_ecdsa_recoverable_signature sig;
238 1804 : int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
239 1804 : assert(ret);
240 1804 : secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, (unsigned char*)&vchSig[1], &rec, &sig);
241 1804 : assert(ret);
242 1804 : assert(rec != -1);
243 2610 : vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
244 1804 : return true;
245 : }
246 :
247 7787 : bool CKey::Load(const CPrivKey& privkey, const CPubKey& vchPubKey, bool fSkipCheck = false)
248 : {
249 7787 : if (!ec_privkey_import_der(secp256k1_context_sign, (unsigned char*)begin(), privkey.data(), privkey.size()))
250 : return false;
251 7787 : fCompressed = vchPubKey.IsCompressed();
252 7787 : fValid = true;
253 :
254 7787 : if (fSkipCheck)
255 : return true;
256 :
257 0 : return VerifyPubKey(vchPubKey);
258 : }
259 :
260 84580 : bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const
261 : {
262 84580 : assert(IsValid());
263 84580 : assert(IsCompressed());
264 84580 : std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
265 84580 : if ((nChild >> 31) == 0) {
266 9021 : CPubKey pubkey = GetPubKey();
267 9021 : assert(pubkey.size() == CPubKey::COMPRESSED_PUBLIC_KEY_SIZE);
268 9021 : BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
269 : } else {
270 75559 : assert(size() == 32);
271 75559 : BIP32Hash(cc, nChild, 0, begin(), vout.data());
272 : }
273 84580 : memcpy(ccChild.begin(), vout.data()+32, 32);
274 84580 : memcpy((unsigned char*)keyChild.begin(), begin(), 32);
275 84580 : bool ret = secp256k1_ec_privkey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data());
276 84580 : keyChild.fCompressed = true;
277 84580 : keyChild.fValid = ret;
278 169160 : return ret;
279 : }
280 :
281 84580 : bool CExtKey::Derive(CExtKey& out, unsigned int _nChild) const
282 : {
283 84580 : out.nDepth = nDepth + 1;
284 84580 : CKeyID id = key.GetPubKey().GetID();
285 84580 : memcpy(&out.vchFingerprint[0], &id, 4);
286 84580 : out.nChild = _nChild;
287 84580 : return key.Derive(out.key, out.chaincode, _nChild, chaincode);
288 : }
289 :
290 11515 : void CExtKey::SetSeed(const unsigned char* seed, unsigned int nSeedLen)
291 : {
292 11515 : static const unsigned char hashkey[] = {'B', 'i', 't', 'c', 'o', 'i', 'n', ' ', 's', 'e', 'e', 'd'};
293 11515 : std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
294 11515 : CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(vout.data());
295 11515 : key.Set(vout.data(), vout.data() + 32, true);
296 11515 : memcpy(chaincode.begin(), vout.data() + 32, 32);
297 11515 : nDepth = 0;
298 11515 : nChild = 0;
299 11515 : memset(vchFingerprint, 0, sizeof(vchFingerprint));
300 11515 : }
301 :
302 9049 : CExtPubKey CExtKey::Neuter() const
303 : {
304 9049 : CExtPubKey ret;
305 9049 : ret.nDepth = nDepth;
306 9049 : memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
307 9049 : ret.nChild = nChild;
308 9049 : ret.pubkey = key.GetPubKey();
309 9049 : ret.chaincode = chaincode;
310 9049 : return ret;
311 : }
312 :
313 34 : void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const
314 : {
315 34 : code[0] = nDepth;
316 34 : memcpy(code + 1, vchFingerprint, 4);
317 34 : code[5] = (nChild >> 24) & 0xFF;
318 34 : code[6] = (nChild >> 16) & 0xFF;
319 34 : code[7] = (nChild >> 8) & 0xFF;
320 34 : code[8] = (nChild >> 0) & 0xFF;
321 34 : memcpy(code + 9, chaincode.begin(), 32);
322 34 : code[41] = 0;
323 34 : assert(key.size() == 32);
324 34 : memcpy(code + 42, key.begin(), 32);
325 34 : }
326 :
327 34 : void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE])
328 : {
329 34 : nDepth = code[0];
330 34 : memcpy(vchFingerprint, code + 1, 4);
331 34 : nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
332 34 : memcpy(chaincode.begin(), code + 9, 32);
333 34 : key.Set(code + 42, code + BIP32_EXTKEY_SIZE, true);
334 34 : }
335 :
336 380 : bool ECC_InitSanityCheck()
337 : {
338 380 : CKey key;
339 380 : key.MakeNewKey(true);
340 380 : CPubKey pubkey = key.GetPubKey();
341 760 : return key.VerifyPubKey(pubkey);
342 : }
343 :
344 795 : void ECC_Start() {
345 795 : assert(secp256k1_context_sign == nullptr);
346 :
347 795 : secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
348 795 : assert(ctx != nullptr);
349 :
350 795 : {
351 : // Pass in a random blinding seed to the secp256k1 context.
352 795 : std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
353 795 : GetRandBytes(vseed.data(), 32);
354 795 : bool ret = secp256k1_context_randomize(ctx, vseed.data());
355 795 : assert(ret);
356 : }
357 :
358 795 : secp256k1_context_sign = ctx;
359 795 : }
360 :
361 793 : void ECC_Stop() {
362 793 : secp256k1_context *ctx = secp256k1_context_sign;
363 793 : secp256k1_context_sign = nullptr;
364 :
365 793 : if (ctx) {
366 793 : secp256k1_context_destroy(ctx);
367 : }
368 793 : }
|