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