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