OpenSSL API hacks
[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/evp.h>
9 #include <openssl/obj_mac.h>
10
11 #include "key.h"
12 #include "base58.h"
13
14 // Generate a private key from just the secret parameter
15 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
16 {
17     int ok = 0;
18     BN_CTX *ctx = NULL;
19     EC_POINT *pub_key = NULL;
20
21     if (!eckey) return 0;
22
23     const EC_GROUP *group = EC_KEY_get0_group(eckey);
24
25     if ((ctx = BN_CTX_new()) == NULL)
26         goto err;
27
28     pub_key = EC_POINT_new(group);
29
30     if (pub_key == NULL)
31         goto err;
32
33     if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
34         goto err;
35
36     EC_KEY_set_private_key(eckey,priv_key);
37     EC_KEY_set_public_key(eckey,pub_key);
38
39     ok = 1;
40
41 err:
42
43     if (pub_key)
44         EC_POINT_free(pub_key);
45     if (ctx != NULL)
46         BN_CTX_free(ctx);
47
48     return(ok);
49 }
50
51 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
52 // recid selects which key is recovered
53 // if check is non-zero, additional checks are performed
54 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
55 {
56     if (!eckey) return 0;
57
58     int ret = 0;
59     BN_CTX *ctx = NULL;
60
61     BIGNUM *x = NULL;
62     BIGNUM *e = NULL;
63     BIGNUM *order = NULL;
64     BIGNUM *sor = NULL;
65     BIGNUM *eor = NULL;
66     BIGNUM *field = NULL;
67     EC_POINT *R = NULL;
68     EC_POINT *O = NULL;
69     EC_POINT *Q = NULL;
70     BIGNUM *rr = NULL;
71     BIGNUM *zero = NULL;
72     int n = 0;
73     int i = recid / 2;
74
75     const EC_GROUP *group = EC_KEY_get0_group(eckey);
76     if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
77     BN_CTX_start(ctx);
78     order = BN_CTX_get(ctx);
79     if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
80     x = BN_CTX_get(ctx);
81     if (!BN_copy(x, order)) { ret=-1; goto err; }
82     if (!BN_mul_word(x, i)) { ret=-1; goto err; }
83
84     // Get internal R and S pointers
85     const BIGNUM *ecsig_r, *ecsig_s;
86     ECDSA_SIG_get0(ecsig, &ecsig_r, &ecsig_s);
87
88     if (!BN_add(x, x, ecsig_r)) { ret=-1; goto err; }
89     field = BN_CTX_get(ctx);
90     if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
91     if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
92     if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
93     if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
94     if (check)
95     {
96         if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
97         if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
98         if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
99     }
100     if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
101     n = EC_GROUP_get_degree(group);
102     e = BN_CTX_get(ctx);
103     if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
104     if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
105     zero = BN_CTX_get(ctx);
106     BN_zero(zero);
107     if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
108     rr = BN_CTX_get(ctx);
109     if (!BN_mod_inverse(rr, ecsig_r, order, ctx)) { ret=-1; goto err; }
110     sor = BN_CTX_get(ctx);
111     if (!BN_mod_mul(sor, ecsig_s, rr, order, ctx)) { ret=-1; goto err; }
112     eor = BN_CTX_get(ctx);
113     if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
114     if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
115     if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
116
117     ret = 1;
118
119 err:
120     if (ctx) {
121         BN_CTX_end(ctx);
122         BN_CTX_free(ctx);
123     }
124     if (R != NULL) EC_POINT_free(R);
125     if (O != NULL) EC_POINT_free(O);
126     if (Q != NULL) EC_POINT_free(Q);
127     return ret;
128 }
129
130 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
131     while (c1len > c2len) {
132         if (*c1)
133             return 1;
134         c1++;
135         c1len--;
136     }
137     while (c2len > c1len) {
138         if (*c2)
139             return -1;
140         c2++;
141         c2len--;
142     }
143     while (c1len > 0) {
144         if (*c1 > *c2)
145             return 1;
146         if (*c2 > *c1)
147             return -1;
148         c1++;
149         c2++;
150         c1len--;
151     }
152     return 0;
153 }
154
155 // Order of secp256k1's generator minus 1.
156 const unsigned char vchMaxModOrder[32] = {
157     0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
158     0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
159     0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
160     0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
161 };
162
163 // Half of the order of secp256k1's generator minus 1.
164 const unsigned char vchMaxModHalfOrder[32] = {
165     0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
166     0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
167     0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
168     0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
169 };
170
171 const unsigned char *vchZero = NULL;
172
173 void CKey::SetCompressedPubKey(bool fCompressed)
174 {
175     EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
176 }
177
178 void CKey::Reset()
179 {
180     fSet = false;
181     if (pkey != NULL)
182         EC_KEY_free(pkey);
183     pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
184     if (pkey == NULL)
185         throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
186 }
187
188 CKey::CKey()
189 {
190     pkey = NULL;
191     Reset();
192 }
193
194 CKey::CKey(const CKey& b)
195 {
196     pkey = EC_KEY_dup(b.pkey);
197     if (pkey == NULL)
198         throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
199     fSet = b.fSet;
200 }
201
202 CKey::CKey(const CSecret& b, bool fCompressed)
203 {
204     pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
205     if (pkey == NULL)
206         throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
207     SetSecret(b, fCompressed);
208 }
209
210 CKey& CKey::operator=(const CKey& b)
211 {
212     if (!EC_KEY_copy(pkey, b.pkey))
213         throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
214     fSet = b.fSet;
215     return (*this);
216 }
217
218 CKey::~CKey()
219 {
220     if (pkey != NULL)
221         EC_KEY_free(pkey);
222 }
223
224 bool CKey::IsNull() const
225 {
226     return !fSet;
227 }
228
229 bool CKey::IsCompressed() const
230 {
231     return (EC_KEY_get_conv_form(pkey) == POINT_CONVERSION_COMPRESSED);
232 }
233
234 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
235     return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
236         CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
237 }
238
239 bool CPubKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
240 {
241     if (vchSig.empty())
242         return false;
243
244     unsigned char *pos = &vchSig[0];
245     ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
246     if (sig == NULL)
247         return false;
248
249     bool ret = false;
250     int nSize = i2d_ECDSA_SIG(sig, NULL);
251     if (nSize > 0) {
252         vchSig.resize(nSize); // grow or shrink as needed
253
254         pos = &vchSig[0];
255         i2d_ECDSA_SIG(sig, &pos);
256
257         ret = true;
258     }
259
260     ECDSA_SIG_free(sig);
261
262     return ret;
263 }
264
265 void CKey::MakeNewKey(bool fCompressed)
266 {
267     if (!EC_KEY_generate_key(pkey))
268         throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
269     SetCompressedPubKey(fCompressed);
270     fSet = true;
271 }
272
273 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
274 {
275     const unsigned char* pbegin = &vchPrivKey[0];
276     if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
277     {
278         // In testing, d2i_ECPrivateKey can return true
279         // but fill in pkey with a key that fails
280         // EC_KEY_check_key, so:
281         if (EC_KEY_check_key(pkey))
282         {
283             fSet = true;
284             return true;
285         }
286     }
287     // If vchPrivKey data is bad d2i_ECPrivateKey() can
288     // leave pkey in a state where calling EC_KEY_free()
289     // crashes. To avoid that, set pkey to NULL and
290     // leak the memory (a leak is better than a crash)
291     pkey = NULL;
292     Reset();
293     return false;
294 }
295
296 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
297 {
298     EC_KEY_free(pkey);
299     pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
300     if (pkey == NULL)
301         throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
302
303     if (vchSecret.size() != 32)
304         throw key_error("CKey::SetSecret() : secret must be 32 bytes");
305     BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
306     if (bn == NULL)
307         throw key_error("CKey::SetSecret() : BN_bin2bn failed");
308     if (!EC_KEY_regenerate_key(pkey,bn))
309     {
310         BN_clear_free(bn);
311         throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
312     }
313     BN_clear_free(bn);
314     fSet = true;
315     SetCompressedPubKey(fCompressed);
316     return true;
317 }
318
319 CSecret CKey::GetSecret(bool &fCompressed) const
320 {
321     CSecret vchRet;
322     vchRet.resize(32);
323     const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
324     int nBytes = BN_num_bytes(bn);
325     if (bn == NULL)
326         throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
327     int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
328     if (n != nBytes)
329         throw key_error("CKey::GetSecret(): BN_bn2bin failed");
330     fCompressed = IsCompressed();
331     return vchRet;
332 }
333
334 bool CKey::WritePEM(BIO *streamObj, const SecureString &strPassKey) const // dumppem 4KJLA99FyqMMhjjDe7KnRXK4sjtv9cCtNS /tmp/test.pem 123
335 {
336     EVP_PKEY *evpKey = EVP_PKEY_new();
337     if (!EVP_PKEY_assign_EC_KEY(evpKey, pkey))
338         return error("CKey::WritePEM() : Error initializing EVP_PKEY instance.");
339     if(!PEM_write_bio_PKCS8PrivateKey(streamObj, evpKey, EVP_aes_256_cbc(), (char *)&strPassKey[0], strPassKey.size(), NULL, NULL))
340         return error("CKey::WritePEM() : Error writing private key data to stream object");
341
342     return true;
343 }
344
345 CSecret CKey::GetSecret() const
346 {
347     bool fCompressed;
348     return GetSecret(fCompressed);
349 }
350
351 CPrivKey CKey::GetPrivKey() const
352 {
353     int nSize = i2d_ECPrivateKey(pkey, NULL);
354     if (!nSize)
355         throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
356     CPrivKey vchPrivKey(nSize, 0);
357     unsigned char* pbegin = &vchPrivKey[0];
358     if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
359         throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
360     return vchPrivKey;
361 }
362
363 CPubKey CKey::GetPubKey() const
364 {
365     int nSize = i2o_ECPublicKey(pkey, NULL);
366     if (!nSize)
367         throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
368     std::vector<unsigned char> vchPubKey(nSize, 0);
369     unsigned char* pbegin = &vchPubKey[0];
370     if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
371         throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
372     return CPubKey(vchPubKey);
373 }
374
375 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
376 {
377     vchSig.clear();
378     ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
379     if (sig==NULL)
380         return false;
381     const EC_GROUP *group = EC_KEY_get0_group(pkey);
382     CBigNum order, halforder;
383     EC_GROUP_get_order(group, order.get(), NULL);
384     BN_rshift1(halforder.get(), order.get());
385
386     // Get internal R and S pointers
387     const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
388
389     // enforce low S values, by negating the value (modulo the order) if above order/2.
390     if (BN_cmp(current_s, halforder.get()) > 0) {
391         BIGNUM *updated_s = BN_new();
392         BN_copy(updated_s, current_s);
393         BN_sub(updated_s, order.get(), updated_s);
394         ECDSA_SIG_set0(sig, NULL, updated_s);
395     }
396
397     unsigned int nSize = ECDSA_size(pkey);
398     vchSig.resize(nSize); // Make sure it is big enough
399     unsigned char *pos = &vchSig[0];
400     nSize = i2d_ECDSA_SIG(sig, &pos);
401     ECDSA_SIG_free(sig);
402     vchSig.resize(nSize); // Shrink to fit actual size
403     // Testing our new signature
404     if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
405         vchSig.clear();
406         return false;
407     }
408     return true;
409 }
410
411 // create a compact signature (65 bytes), which allows reconstructing the used public key
412 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
413 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
414 //                  0x1D = second key with even y, 0x1E = second key with odd y
415 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
416 {
417     bool fOk = false;
418     ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
419     if (sig==NULL)
420         return false;
421     const EC_GROUP *group = EC_KEY_get0_group(pkey);
422     CBigNum order, halforder;
423     EC_GROUP_get_order(group, order.get(), NULL);
424     BN_rshift1(halforder.get(), order.get());
425
426     // Get internal R and S pointers
427     const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
428
429     // enforce low S values, by negating the value (modulo the order) if above order/2.
430     if (BN_cmp(current_s, halforder.get()) > 0) {
431         BIGNUM *updated_s = BN_new();
432         BN_copy(updated_s, current_s);
433         BN_sub(updated_s, order.get(), updated_s);
434         ECDSA_SIG_set0(sig, NULL, updated_s);
435     }
436
437     vchSig.clear();
438     vchSig.resize(65,0);
439     int nBitsR = BN_num_bits(ECDSA_SIG_get0_r(sig));
440     int nBitsS = BN_num_bits(ECDSA_SIG_get0_s(sig));
441     bool fCompressedPubKey = IsCompressed();
442     if (nBitsR <= 256 && nBitsS <= 256)
443     {
444         int8_t nRecId = -1;
445         for (int8_t i=0; i<4; i++)
446         {
447             CKey keyRec;
448             keyRec.fSet = true;
449             keyRec.SetCompressedPubKey(fCompressedPubKey);
450             if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
451                 if (keyRec.GetPubKey() == this->GetPubKey())
452                 {
453                     nRecId = i;
454                     break;
455                 }
456         }
457
458         if (nRecId == -1)
459         {
460             ECDSA_SIG_free(sig);
461             throw key_error("CKey::SignCompact() : unable to construct recoverable key");
462         }
463
464         vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
465         BN_bn2bin(ECDSA_SIG_get0_r(sig),&vchSig[33-(nBitsR+7)/8]);
466         BN_bn2bin(ECDSA_SIG_get0_s(sig),&vchSig[65-(nBitsS+7)/8]);
467         fOk = true;
468     }
469     ECDSA_SIG_free(sig);
470     return fOk;
471 }
472
473 // reconstruct public key from a compact signature
474 // This is only slightly more CPU intensive than just verifying it.
475 // If this function succeeds, the recovered public key is guaranteed to be valid
476 // (the signature is a valid signature of the given data for that key)
477 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
478 {
479     if (vchSig.size() != 65)
480         return false;
481     int nV = vchSig[0];
482     if (nV<27 || nV>=35)
483         return false;
484     ECDSA_SIG *sig = ECDSA_SIG_new();
485     BIGNUM *sig_r, *sig_s;
486     BN_bin2bn(&vchSig[1],32,sig_r);
487     BN_bin2bn(&vchSig[33],32,sig_s);
488     ECDSA_SIG_set0(sig, sig_r, sig_s);
489     bool fSuccessful = false;
490     EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
491     if (nV >= 31)
492     {
493         nV -= 4;
494         EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
495     }
496     do
497     {
498         if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
499             break;
500         int nSize = i2o_ECPublicKey(pkey, NULL);
501         if (!nSize)
502             break;
503         std::vector<unsigned char> vchPubKey(nSize, 0);
504         unsigned char* pbegin = &vchPubKey[0];
505         if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
506             break;
507         Set(vchPubKey.begin(), vchPubKey.end());
508         fSuccessful = IsValid();
509
510     } while (false);
511     ECDSA_SIG_free(sig);
512     EC_KEY_free(pkey);
513     if (!fSuccessful)
514         Invalidate();
515     return fSuccessful;
516 }
517
518 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
519 {
520     if (vchSig.empty() || !IsValid())
521         return false;
522
523     EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
524     ECDSA_SIG *norm_sig = ECDSA_SIG_new();
525
526     assert(norm_sig);
527     assert(pkey);
528
529     bool ret = false;
530     do
531     {
532         int derlen;
533         uint8_t *norm_der = NULL;
534         const uint8_t* pbegin = &vbytes[0];
535         const uint8_t* sigptr = &vchSig[0];
536
537         // Trying to parse public key
538         if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
539             break;
540         // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
541         if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
542             break;
543         if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
544             break;
545
546         // -1 = error, 0 = bad sig, 1 = good
547         ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
548         OPENSSL_free(norm_der);
549     } while(false);
550
551     ECDSA_SIG_free(norm_sig);
552     EC_KEY_free(pkey);
553
554     return ret;
555 }
556
557 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
558 {
559     CPubKey key;
560     if (!key.SetCompactSignature(hash, vchSig))
561         return false;
562     return true;
563 }
564
565 bool CKey::IsValid()
566 {
567     if (!fSet)
568         return false;
569
570     if (!EC_KEY_check_key(pkey))
571         return false;
572
573     bool fCompr;
574     CSecret secret = GetSecret(fCompr);
575     CKey key2;
576     key2.SetSecret(secret, fCompr);
577
578     return GetPubKey() == key2.GetPubKey();
579 }
580
581 CPoint::CPoint()
582 {
583     std::string err;
584     group = NULL;
585     point = NULL;
586     ctx   = NULL;
587
588     group = EC_GROUP_new_by_curve_name(NID_secp256k1);
589     if (!group) {
590         err = "EC_KEY_new_by_curve_name failed.";
591         goto finish;
592     }
593
594     point = EC_POINT_new(group);
595     if (!point) {
596         err = "EC_POINT_new failed.";
597         goto finish;
598     }
599
600     ctx = BN_CTX_new();
601     if (!ctx) {
602         err = "BN_CTX_new failed.";
603         goto finish;
604     }
605
606     return;
607
608 finish:
609     if (group) EC_GROUP_free(group);
610     if (point) EC_POINT_free(point);
611     throw std::runtime_error(std::string("CPoint::CPoint() :  - ") + err);
612 }
613
614 bool CPoint::operator!=(const CPoint &a)
615 {
616     if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
617         return true;
618     return false;
619 }
620 CPoint::~CPoint()
621 {
622     if (point) EC_POINT_free(point);
623     if (group) EC_GROUP_free(group);
624     if (ctx)   BN_CTX_free(ctx);
625 }
626
627 // Initialize from octets stream
628 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
629 {
630     if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
631         return false;
632     }
633     return true;
634 }
635
636 // Initialize from octets stream
637 bool CPoint::setPubKey(const CPubKey &key)
638 {
639     std::vector<uint8_t> vchPubKey(key.begin(), key.end());
640     return setBytes(vchPubKey);
641 }
642
643 // Serialize to octets stream
644 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
645 {
646     size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
647     vchBytes.resize(nSize);
648     if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
649         return false;
650     }
651     return true;
652 }
653
654 // ECC multiplication by specified multiplier
655 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
656 {
657     if (!EC_POINT_mul(group, point, NULL, point, bnMultiplier.get(), NULL)) {
658         printf("CPoint::ECMUL() : EC_POINT_mul failed");
659         return false;
660     }
661
662     return true;
663 }
664
665 // Calculate G*m + q
666 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
667 {
668     if (!EC_POINT_mul(group, point, bnMultiplier.get(), qPoint.point, BN_value_one(), NULL)) {
669         printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
670         return false;
671     }
672
673     return true;
674 }
675
676 // CMalleablePubKey
677
678 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
679 {
680     EC_KEY *eckey = NULL;
681     eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
682     if (eckey == NULL) {
683         throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
684     }
685
686     // Use standard key generation function to get r and R values.
687     //
688     // r will be presented by private key;
689     // R is ECDSA public key which calculated as G*r
690     if (!EC_KEY_generate_key(eckey)) {
691         throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
692     }
693
694     EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
695
696     int nSize = i2o_ECPublicKey(eckey, NULL);
697     if (!nSize) {
698         throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
699     }
700
701     std::vector<unsigned char> vchPubKey(nSize, 0);
702     unsigned char* pbegin_R = &vchPubKey[0];
703
704     if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
705         throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
706     }
707
708     // R = G*r
709     R = CPubKey(vchPubKey);
710
711     // OpenSSL BIGNUM representation of r value
712     CBigNum bnr;
713     bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
714     EC_KEY_free(eckey);
715
716     CPoint point;
717     if (!point.setPubKey(pubKeyL)) {
718         throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
719     }
720
721     // Calculate L*r
722     point.ECMUL(bnr);
723
724     std::vector<unsigned char> vchLr;
725     if (!point.getBytes(vchLr)) {
726         throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
727     }
728
729     // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
730     CBigNum bnHash;
731     bnHash.setuint160(Hash160(vchLr));
732
733     CPoint pointH;
734     pointH.setPubKey(pubKeyH);
735
736     CPoint P;
737     // Calculate P = Hash(L*r)*G + H
738     P.ECMULGEN(bnHash, pointH);
739
740     if (P.IsInfinity()) {
741         throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
742     }
743
744     std::vector<unsigned char> vchResult;
745     P.getBytes(vchResult);
746
747     vchPubKeyVariant = CPubKey(vchResult);
748 }
749
750 std::string CMalleablePubKey::ToString() const
751 {
752     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
753     ssKey << *this;
754     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
755
756     return EncodeBase58Check(vch);
757 }
758
759 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
760 {
761     CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
762     ssKey >> *this;
763
764     return IsValid();
765 }
766
767 std::vector<unsigned char> CMalleablePubKey::Raw() const
768 {
769     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
770     ssKey << *this;
771     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
772
773     return vch;
774 }
775
776 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
777 {
778     std::vector<unsigned char> vchTemp;
779     if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
780         throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
781     }
782     if (vchTemp.size() != 68)
783         return false;
784
785     CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
786     ssKey >> *this;
787
788     return IsValid();
789 }
790
791 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
792 {
793     return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
794 }
795
796
797 // CMalleableKey
798
799 void CMalleableKey::Reset()
800 {
801     vchSecretL.clear();
802     vchSecretH.clear();
803 }
804
805 void CMalleableKey::MakeNewKeys()
806 {
807     Reset();
808
809     CKey keyL, keyH;
810     keyL.MakeNewKey();
811     keyH.MakeNewKey();
812
813     vchSecretL = keyL.GetSecret();
814     vchSecretH = keyH.GetSecret();
815 }
816
817 CMalleableKey::CMalleableKey()
818 {
819     Reset();
820 }
821
822 CMalleableKey::CMalleableKey(const CMalleableKey &b)
823 {
824     SetSecrets(b.vchSecretL, b.vchSecretH);
825 }
826
827 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
828 {
829     SetSecrets(L, H);
830 }
831
832 CMalleableKey::~CMalleableKey()
833 {
834 }
835
836 bool CMalleableKey::IsNull() const
837 {
838     return vchSecretL.size() != 32 || vchSecretH.size() != 32;
839 }
840
841 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
842 {
843     Reset();
844
845     CKey keyL(pvchSecretL);
846     CKey keyH(pvchSecretH);
847
848     if (!keyL.IsValid() || !keyH.IsValid())
849         return false;
850
851     vchSecretL = pvchSecretL;
852     vchSecretH = pvchSecretH;
853
854     return true;
855 }
856
857 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
858 {
859     CKey L(vchSecretL), H(vchSecretH);
860     return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
861 }
862
863 // Check ownership
864 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
865 {
866     if (IsNull()) {
867         throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
868     }
869
870     if (!R.IsValid()) {
871         printf("CMalleableKey::CheckKeyVariant() : R is invalid");
872         return false;
873     }
874
875     if (!vchPubKeyVariant.IsValid()) {
876         printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
877         return false;
878     }
879
880     CPoint point_R;
881     if (!point_R.setPubKey(R)) {
882         printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
883         return false;
884     }
885
886     CKey H(vchSecretH);
887     CPubKey vchPubKeyH = H.GetPubKey();
888
889     CPoint point_H;
890     if (!point_H.setPubKey(vchPubKeyH)) {
891         printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
892         return false;
893     }
894
895     CPoint point_P;
896     if (!point_P.setPubKey(vchPubKeyVariant)) {
897         printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
898         return false;
899     }
900
901     // Infinity points are senseless
902     if (point_P.IsInfinity()) {
903         printf("CMalleableKey::CheckKeyVariant() : P is infinity");
904         return false;
905     }
906
907     CBigNum bnl;
908     bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
909
910     point_R.ECMUL(bnl);
911
912     std::vector<unsigned char> vchRl;
913     if (!point_R.getBytes(vchRl)) {
914         printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
915         return false;
916     }
917
918     // Calculate Hash(R*l)
919     CBigNum bnHash;
920     bnHash.setuint160(Hash160(vchRl));
921
922     CPoint point_Ps;
923     // Calculate Ps = Hash(L*r)*G + H
924     point_Ps.ECMULGEN(bnHash, point_H);
925
926     // Infinity points are senseless
927     if (point_Ps.IsInfinity()) {
928         printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
929         return false;
930     }
931
932     // Check ownership
933     if (point_Ps != point_P) {
934         return false;
935     }
936
937     return true;
938 }
939
940 // Check ownership and restore private key
941 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
942 {
943     if (IsNull()) {
944         throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
945     }
946
947     if (!R.IsValid()) {
948         printf("CMalleableKey::CheckKeyVariant() : R is invalid");
949         return false;
950     }
951
952     if (!vchPubKeyVariant.IsValid()) {
953         printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
954         return false;
955     }
956
957     CPoint point_R;
958     if (!point_R.setPubKey(R)) {
959         printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
960         return false;
961     }
962
963     CKey H(vchSecretH);
964     CPubKey vchPubKeyH = H.GetPubKey();
965
966     CPoint point_H;
967     if (!point_H.setPubKey(vchPubKeyH)) {
968         printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
969         return false;
970     }
971
972     CPoint point_P;
973     if (!point_P.setPubKey(vchPubKeyVariant)) {
974         printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
975         return false;
976     }
977
978     // Infinity points are senseless
979     if (point_P.IsInfinity()) {
980         printf("CMalleableKey::CheckKeyVariant() : P is infinity");
981         return false;
982     }
983
984     CBigNum bnl;
985     bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
986
987     point_R.ECMUL(bnl);
988
989     std::vector<unsigned char> vchRl;
990     if (!point_R.getBytes(vchRl)) {
991         printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
992         return false;
993     }
994
995     // Calculate Hash(R*l)
996     CBigNum bnHash;
997     bnHash.setuint160(Hash160(vchRl));
998
999     CPoint point_Ps;
1000     // Calculate Ps = Hash(L*r)*G + H
1001     point_Ps.ECMULGEN(bnHash, point_H);
1002
1003     // Infinity points are senseless
1004     if (point_Ps.IsInfinity()) {
1005         printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
1006         return false;
1007     }
1008
1009     // Check ownership
1010     if (point_Ps != point_P) {
1011         return false;
1012     }
1013
1014     // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1015     CBigNum bnh;
1016     bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1017
1018     // Calculate p = Hash(R*l) + h
1019     CBigNum bnp = bnHash + bnh;
1020
1021     std::vector<unsigned char> vchp = bnp.getBytes();
1022     privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1023
1024     return true;
1025 }
1026
1027 std::string CMalleableKey::ToString() const
1028 {
1029     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1030     ssKey << *this;
1031     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1032
1033     return EncodeBase58Check(vch);
1034 }
1035
1036 std::vector<unsigned char> CMalleableKey::Raw() const
1037 {
1038     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1039     ssKey << *this;
1040     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1041
1042     return vch;
1043 }
1044
1045 bool CMalleableKey::SetString(const std::string& strMutableKey)
1046 {
1047     std::vector<unsigned char> vchTemp;
1048     if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1049         throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1050     }
1051     if (vchTemp.size() != 66)
1052         return false;
1053     CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1054     ssKey >> *this;
1055
1056     return IsValid();
1057 }
1058
1059 // CMalleableKeyView
1060
1061 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1062 {
1063     SetString(strMalleableKey);
1064 }
1065
1066 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1067 {
1068     if (b.vchSecretL.size() != 32)
1069         throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1070
1071     if (b.vchSecretH.size() != 32)
1072         throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1073
1074     vchSecretL = b.vchSecretL;
1075
1076     CKey H(b.vchSecretH);
1077     vchPubKeyH = H.GetPubKey();
1078 }
1079
1080 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1081 {
1082     vchSecretL = b.vchSecretL;
1083     vchPubKeyH = b.vchPubKeyH;
1084 }
1085
1086 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1087 {
1088     vchSecretL = b.vchSecretL;
1089
1090     CKey H(b.vchSecretH);
1091     vchPubKeyH = H.GetPubKey();
1092
1093     return (*this);
1094 }
1095
1096 CMalleableKeyView::~CMalleableKeyView()
1097 {
1098 }
1099
1100 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1101 {
1102     CKey keyL(vchSecretL);
1103     return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1104 }
1105
1106 // Check ownership
1107 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1108 {
1109     if (!IsValid()) {
1110         throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1111     }
1112
1113     if (!R.IsValid()) {
1114         printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1115         return false;
1116     }
1117
1118     if (!vchPubKeyVariant.IsValid()) {
1119         printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1120         return false;
1121     }
1122
1123     CPoint point_R;
1124     if (!point_R.setPubKey(R)) {
1125         printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1126         return false;
1127     }
1128
1129     CPoint point_H;
1130     if (!point_H.setPubKey(vchPubKeyH)) {
1131         printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1132         return false;
1133     }
1134
1135     CPoint point_P;
1136     if (!point_P.setPubKey(vchPubKeyVariant)) {
1137         printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1138         return false;
1139     }
1140
1141     // Infinity points are senseless
1142     if (point_P.IsInfinity()) {
1143         printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1144         return false;
1145     }
1146
1147     CBigNum bnl;
1148     bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1149
1150     point_R.ECMUL(bnl);
1151
1152     std::vector<unsigned char> vchRl;
1153     if (!point_R.getBytes(vchRl)) {
1154         printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1155         return false;
1156     }
1157
1158     // Calculate Hash(R*l)
1159     CBigNum bnHash;
1160     bnHash.setuint160(Hash160(vchRl));
1161
1162     CPoint point_Ps;
1163     // Calculate Ps = Hash(L*r)*G + H
1164     point_Ps.ECMULGEN(bnHash, point_H);
1165
1166     // Infinity points are senseless
1167     if (point_Ps.IsInfinity()) {
1168         printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1169         return false;
1170     }
1171
1172     // Check ownership
1173     if (point_Ps != point_P) {
1174         return false;
1175     }
1176
1177     return true;
1178 }
1179
1180 std::string CMalleableKeyView::ToString() const
1181 {
1182     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1183     ssKey << *this;
1184     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1185
1186     return EncodeBase58Check(vch);
1187 }
1188
1189 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1190 {
1191     std::vector<unsigned char> vchTemp;
1192     if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1193         throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1194     }
1195
1196     if (vchTemp.size() != 67)
1197         return false;
1198
1199     CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1200     ssKey >> *this;
1201
1202     return IsValid();
1203 }
1204
1205 std::vector<unsigned char> CMalleableKeyView::Raw() const
1206 {
1207     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1208     ssKey << *this;
1209     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1210
1211     return vch;
1212 }
1213
1214
1215 bool CMalleableKeyView::IsValid() const
1216 {
1217     return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1218 }
1219
1220 //// Asymmetric encryption
1221
1222 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1223 {
1224     ies_ctx_t *ctx;
1225     char error[1024] = "Unknown error";
1226     cryptogram_t *cryptogram;
1227
1228     const unsigned char* pbegin = &vbytes[0];
1229     EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
1230     if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
1231         throw key_error("Unable to parse EC key");
1232
1233     ctx = create_context(pkey);
1234     if (!EC_KEY_get0_public_key(ctx->user_key))
1235         throw key_error("Given EC key is not public key");
1236
1237     cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1238     if (cryptogram == NULL) {
1239         delete ctx;
1240         ctx = NULL;
1241         throw key_error(std::string("Error in encryption: %s") + error);
1242     }
1243
1244     encrypted.resize(cryptogram_data_sum_length(cryptogram));
1245     unsigned char *key_data = cryptogram_key_data(cryptogram);
1246     memcpy(&encrypted[0], key_data, encrypted.size());
1247     cryptogram_free(cryptogram);
1248     delete ctx;
1249 }
1250
1251 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1252 {
1253     ies_ctx_t *ctx;
1254     char error[1024] = "Unknown error";
1255     cryptogram_t *cryptogram;
1256     size_t length;
1257     unsigned char *decrypted;
1258
1259     ctx = create_context(pkey);
1260     if (!EC_KEY_get0_private_key(ctx->user_key))
1261         throw key_error("Given EC key is not private key");
1262
1263     size_t key_length = ctx->stored_key_length;
1264     size_t mac_length = EVP_MD_size(ctx->md);
1265     cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1266
1267     memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1268
1269     decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1270     cryptogram_free(cryptogram);
1271     delete ctx;
1272
1273     if (decrypted == NULL) {
1274         throw key_error(std::string("Error in decryption: %s") + error);
1275     }
1276
1277     data.resize(length);
1278     memcpy(&data[0], decrypted, length);
1279     free(decrypted);
1280 }