6239ba5712e1c848c7f0d8d23fa71b804c53cecd
[novacoin.git] / src / key.cpp
1 // Copyright (c) 2009-2012 The Bitcoin developers
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4
5 #include <map>
6
7 #include <openssl/ecdsa.h>
8 #include <openssl/obj_mac.h>
9
10 #include "key.h"
11
12 // Generate a private key from just the secret parameter
13 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
14 {
15     int ok = 0;
16     BN_CTX *ctx = NULL;
17     EC_POINT *pub_key = NULL;
18
19     if (!eckey) return 0;
20
21     const EC_GROUP *group = EC_KEY_get0_group(eckey);
22
23     if ((ctx = BN_CTX_new()) == NULL)
24         goto err;
25
26     pub_key = EC_POINT_new(group);
27
28     if (pub_key == NULL)
29         goto err;
30
31     if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
32         goto err;
33
34     EC_KEY_set_private_key(eckey,priv_key);
35     EC_KEY_set_public_key(eckey,pub_key);
36
37     ok = 1;
38
39 err:
40
41     if (pub_key)
42         EC_POINT_free(pub_key);
43     if (ctx != NULL)
44         BN_CTX_free(ctx);
45
46     return(ok);
47 }
48
49 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
50 // recid selects which key is recovered
51 // if check is non-zero, additional checks are performed
52 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
53 {
54     if (!eckey) return 0;
55
56     int ret = 0;
57     BN_CTX *ctx = NULL;
58
59     BIGNUM *x = NULL;
60     BIGNUM *e = NULL;
61     BIGNUM *order = NULL;
62     BIGNUM *sor = NULL;
63     BIGNUM *eor = NULL;
64     BIGNUM *field = NULL;
65     EC_POINT *R = NULL;
66     EC_POINT *O = NULL;
67     EC_POINT *Q = NULL;
68     BIGNUM *rr = NULL;
69     BIGNUM *zero = NULL;
70     int n = 0;
71     int i = recid / 2;
72
73     const EC_GROUP *group = EC_KEY_get0_group(eckey);
74     if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
75     BN_CTX_start(ctx);
76     order = BN_CTX_get(ctx);
77     if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
78     x = BN_CTX_get(ctx);
79     if (!BN_copy(x, order)) { ret=-1; goto err; }
80     if (!BN_mul_word(x, i)) { ret=-1; goto err; }
81     if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
82     field = BN_CTX_get(ctx);
83     if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
84     if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
85     if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
86     if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
87     if (check)
88     {
89         if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
90         if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
91         if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
92     }
93     if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
94     n = EC_GROUP_get_degree(group);
95     e = BN_CTX_get(ctx);
96     if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
97     if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
98     zero = BN_CTX_get(ctx);
99     if (!BN_zero(zero)) { ret=-1; goto err; }
100     if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
101     rr = BN_CTX_get(ctx);
102     if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
103     sor = BN_CTX_get(ctx);
104     if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
105     eor = BN_CTX_get(ctx);
106     if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
107     if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
108     if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
109
110     ret = 1;
111
112 err:
113     if (ctx) {
114         BN_CTX_end(ctx);
115         BN_CTX_free(ctx);
116     }
117     if (R != NULL) EC_POINT_free(R);
118     if (O != NULL) EC_POINT_free(O);
119     if (Q != NULL) EC_POINT_free(Q);
120     return ret;
121 }
122
123 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
124     while (c1len > c2len) {
125         if (*c1)
126             return 1;
127         c1++;
128         c1len--;
129     }
130     while (c2len > c1len) {
131         if (*c2)
132             return -1;
133         c2++;
134         c2len--;
135     }
136     while (c1len > 0) {
137         if (*c1 > *c2)
138             return 1;
139         if (*c2 > *c1)
140             return -1;
141         c1++;
142         c2++;
143         c1len--;
144     }
145     return 0;
146 }
147
148 // Order of secp256k1's generator minus 1.
149 const unsigned char vchMaxModOrder[32] = {
150     0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
151     0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
152     0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
153     0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
154 };
155
156 // Half of the order of secp256k1's generator minus 1.
157 const unsigned char vchMaxModHalfOrder[32] = {
158     0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
159     0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
160     0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
161     0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
162 };
163
164 const unsigned char *vchZero = NULL;
165
166
167
168 void CKey::SetCompressedPubKey()
169 {
170     EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
171     fCompressedPubKey = true;
172 }
173
174 void CKey::Reset()
175 {
176     fCompressedPubKey = false;
177     if (pkey != NULL)
178         EC_KEY_free(pkey);
179     pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
180     if (pkey == NULL)
181         throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
182     fSet = false;
183 }
184
185 CKey::CKey()
186 {
187     pkey = NULL;
188     Reset();
189 }
190
191 CKey::CKey(const CKey& b)
192 {
193     pkey = EC_KEY_dup(b.pkey);
194     if (pkey == NULL)
195         throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
196     fSet = b.fSet;
197 }
198
199 CKey& CKey::operator=(const CKey& b)
200 {
201     if (!EC_KEY_copy(pkey, b.pkey))
202         throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
203     fSet = b.fSet;
204     return (*this);
205 }
206
207 CKey::~CKey()
208 {
209     EC_KEY_free(pkey);
210 }
211
212 bool CKey::IsNull() const
213 {
214     return !fSet;
215 }
216
217 bool CKey::IsCompressed() const
218 {
219     return fCompressedPubKey;
220 }
221
222 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
223     return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
224         CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
225 }
226
227 bool CKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
228 {
229     if (vchSig.empty())
230         return false;
231
232     unsigned char *pos = &vchSig[0];
233     ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
234     if (sig == NULL)
235         return false;
236
237     bool ret = false;
238     int nSize = i2d_ECDSA_SIG(sig, NULL);
239     if (nSize > 0) {
240         vchSig.resize(nSize); // grow or shrink as needed
241
242         pos = &vchSig[0];
243         i2d_ECDSA_SIG(sig, &pos);
244
245         ret = true;
246     }
247
248     ECDSA_SIG_free(sig);
249
250     return ret;
251 }
252
253 void CKey::MakeNewKey(bool fCompressed)
254 {
255     if (!EC_KEY_generate_key(pkey))
256         throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
257     if (fCompressed)
258         SetCompressedPubKey();
259     fSet = true;
260 }
261
262 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
263 {
264     const unsigned char* pbegin = &vchPrivKey[0];
265     if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
266     {
267         // In testing, d2i_ECPrivateKey can return true
268         // but fill in pkey with a key that fails
269         // EC_KEY_check_key, so:
270         if (EC_KEY_check_key(pkey))
271         {
272             fSet = true;
273             return true;
274         }
275     }
276     // If vchPrivKey data is bad d2i_ECPrivateKey() can
277     // leave pkey in a state where calling EC_KEY_free()
278     // crashes. To avoid that, set pkey to NULL and
279     // leak the memory (a leak is better than a crash)
280     pkey = NULL;
281     Reset();
282     return false;
283 }
284
285 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
286 {
287     EC_KEY_free(pkey);
288     pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
289     if (pkey == NULL)
290         throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
291     if (vchSecret.size() != 32)
292         throw key_error("CKey::SetSecret() : secret must be 32 bytes");
293     BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
294     if (bn == NULL)
295         throw key_error("CKey::SetSecret() : BN_bin2bn failed");
296     if (!EC_KEY_regenerate_key(pkey,bn))
297     {
298         BN_clear_free(bn);
299         throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
300     }
301     BN_clear_free(bn);
302     fSet = true;
303     if (fCompressed || fCompressedPubKey)
304         SetCompressedPubKey();
305     return true;
306 }
307
308 CSecret CKey::GetSecret(bool &fCompressed) const
309 {
310     CSecret vchRet;
311     vchRet.resize(32);
312     const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
313     int nBytes = BN_num_bytes(bn);
314     if (bn == NULL)
315         throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
316     int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
317     if (n != nBytes)
318         throw key_error("CKey::GetSecret(): BN_bn2bin failed");
319     fCompressed = fCompressedPubKey;
320     return vchRet;
321 }
322
323 CPrivKey CKey::GetPrivKey() const
324 {
325     int nSize = i2d_ECPrivateKey(pkey, NULL);
326     if (!nSize)
327         throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
328     CPrivKey vchPrivKey(nSize, 0);
329     unsigned char* pbegin = &vchPrivKey[0];
330     if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
331         throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
332     return vchPrivKey;
333 }
334
335 bool CKey::SetPubKey(const CPubKey& vchPubKey)
336 {
337     const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
338     if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
339     {
340         fSet = true;
341         if (vchPubKey.vchPubKey.size() == 33)
342             SetCompressedPubKey();
343         return true;
344     }
345     pkey = NULL;
346     Reset();
347     return false;
348 }
349
350 CPubKey CKey::GetPubKey() const
351 {
352     int nSize = i2o_ECPublicKey(pkey, NULL);
353     if (!nSize)
354         throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
355     std::vector<unsigned char> vchPubKey(nSize, 0);
356     unsigned char* pbegin = &vchPubKey[0];
357     if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
358         throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
359     return CPubKey(vchPubKey);
360 }
361
362 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
363 {
364     vchSig.clear();
365     ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
366     if (sig==NULL)
367         return false;
368     const EC_GROUP *group = EC_KEY_get0_group(pkey);
369     CBigNum order, halforder;
370     EC_GROUP_get_order(group, &order, NULL);
371     BN_rshift1(&halforder, &order);
372     // enforce low S values, by negating the value (modulo the order) if above order/2.
373     if (BN_cmp(sig->s, &halforder) > 0) {
374         BN_sub(sig->s, &order, sig->s);
375     }
376     unsigned int nSize = ECDSA_size(pkey);
377     vchSig.resize(nSize); // Make sure it is big enough
378     unsigned char *pos = &vchSig[0];
379     nSize = i2d_ECDSA_SIG(sig, &pos);
380     ECDSA_SIG_free(sig);
381     vchSig.resize(nSize); // Shrink to fit actual size
382     // Testing our new signature
383     if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
384         vchSig.clear();
385         return false;
386     }
387     return true;
388 }
389
390 // create a compact signature (65 bytes), which allows reconstructing the used public key
391 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
392 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
393 //                  0x1D = second key with even y, 0x1E = second key with odd y
394 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
395 {
396     bool fOk = false;
397     ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
398     if (sig==NULL)
399         return false;
400     const EC_GROUP *group = EC_KEY_get0_group(pkey);
401     CBigNum order, halforder;
402     EC_GROUP_get_order(group, &order, NULL);
403     BN_rshift1(&halforder, &order);
404     // enforce low S values, by negating the value (modulo the order) if above order/2.
405     if (BN_cmp(sig->s, &halforder) > 0) {
406         BN_sub(sig->s, &order, sig->s);
407     }
408     vchSig.clear();
409     vchSig.resize(65,0);
410     int nBitsR = BN_num_bits(sig->r);
411     int nBitsS = BN_num_bits(sig->s);
412     if (nBitsR <= 256 && nBitsS <= 256)
413     {
414         int8_t nRecId = -1;
415         for (int8_t i=0; i<4; i++)
416         {
417             CKey keyRec;
418             keyRec.fSet = true;
419             if (fCompressedPubKey)
420                 keyRec.SetCompressedPubKey();
421             if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
422                 if (keyRec.GetPubKey() == this->GetPubKey())
423                 {
424                     nRecId = i;
425                     break;
426                 }
427         }
428
429         if (nRecId == -1)
430         {
431             ECDSA_SIG_free(sig);
432             throw key_error("CKey::SignCompact() : unable to construct recoverable key");
433         }
434
435         vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
436         BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
437         BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
438         fOk = true;
439     }
440     ECDSA_SIG_free(sig);
441     return fOk;
442 }
443
444 // reconstruct public key from a compact signature
445 // This is only slightly more CPU intensive than just verifying it.
446 // If this function succeeds, the recovered public key is guaranteed to be valid
447 // (the signature is a valid signature of the given data for that key)
448 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
449 {
450     if (vchSig.size() != 65)
451         return false;
452     int nV = vchSig[0];
453     if (nV<27 || nV>=35)
454         return false;
455     ECDSA_SIG *sig = ECDSA_SIG_new();
456     BN_bin2bn(&vchSig[1],32,sig->r);
457     BN_bin2bn(&vchSig[33],32,sig->s);
458
459     EC_KEY_free(pkey);
460     pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
461     if (nV >= 31)
462     {
463         SetCompressedPubKey();
464         nV -= 4;
465     }
466     if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
467     {
468         fSet = true;
469         ECDSA_SIG_free(sig);
470         return true;
471     }
472     ECDSA_SIG_free(sig);
473     return false;
474 }
475
476 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
477 {
478     if (vchSig.empty())
479         return false;
480
481     // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
482     unsigned char *norm_der = NULL;
483     ECDSA_SIG *norm_sig = ECDSA_SIG_new();
484     const unsigned char* sigptr = &vchSig[0];
485     assert(norm_sig);
486     if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
487     {
488         /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
489         * error. But OpenSSL's own use of this function redundantly frees the
490         * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
491         * clear contract for the function behaving the same way is more
492         * conservative.
493         */
494         ECDSA_SIG_free(norm_sig);
495         return false;
496     }
497     int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
498     ECDSA_SIG_free(norm_sig);
499     if (derlen <= 0)
500         return false;
501
502     // -1 = error, 0 = bad sig, 1 = good
503     bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
504     OPENSSL_free(norm_der);
505     return ret;
506 }
507
508 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
509 {
510     CKey key;
511     if (!key.SetCompactSignature(hash, vchSig))
512         return false;
513     if (GetPubKey() != key.GetPubKey())
514         return false;
515
516     return true;
517 }
518
519 bool CKey::IsValid()
520 {
521     if (!fSet)
522         return false;
523
524     if (!EC_KEY_check_key(pkey))
525         return false;
526
527     bool fCompr;
528     CSecret secret = GetSecret(fCompr);
529     CKey key2;
530     key2.SetSecret(secret, fCompr);
531     return GetPubKey() == key2.GetPubKey();
532 }