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