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