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