Switch nSize to size_t
[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(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     fCompressedPubKey = b.fCompressedPubKey;
215     return (*this);
216 }
217
218 CKey::~CKey()
219 {
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 fCompressedPubKey;
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 CKey::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     if (fCompressed)
269         SetCompressedPubKey();
270     fSet = true;
271 }
272
273 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
274 {
275     const unsigned char* pbegin = &vchPrivKey[0];
276     if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
277     {
278         // In testing, d2i_ECPrivateKey can return true
279         // but fill in pkey with a key that fails
280         // EC_KEY_check_key, so:
281         if (EC_KEY_check_key(pkey))
282         {
283             fSet = true;
284             return true;
285         }
286     }
287     // If vchPrivKey data is bad d2i_ECPrivateKey() can
288     // leave pkey in a state where calling EC_KEY_free()
289     // crashes. To avoid that, set pkey to NULL and
290     // leak the memory (a leak is better than a crash)
291     pkey = NULL;
292     Reset();
293     return false;
294 }
295
296 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
297 {
298     EC_KEY_free(pkey);
299     pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
300     if (pkey == NULL)
301         throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
302     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     if (fCompressed || fCompressedPubKey)
315         SetCompressedPubKey();
316     return true;
317 }
318
319 CSecret CKey::GetSecret(bool &fCompressed) const
320 {
321     CSecret vchRet;
322     vchRet.resize(32);
323     const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
324     int nBytes = BN_num_bytes(bn);
325     if (bn == NULL)
326         throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
327     int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
328     if (n != nBytes)
329         throw key_error("CKey::GetSecret(): BN_bn2bin failed");
330     fCompressed = fCompressedPubKey;
331     return vchRet;
332 }
333
334 CSecret CKey::GetSecret() const
335 {
336     bool fCompressed;
337     return GetSecret(fCompressed);
338 }
339
340 CPrivKey CKey::GetPrivKey() const
341 {
342     int nSize = i2d_ECPrivateKey(pkey, NULL);
343     if (!nSize)
344         throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
345     CPrivKey vchPrivKey(nSize, 0);
346     unsigned char* pbegin = &vchPrivKey[0];
347     if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
348         throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
349     return vchPrivKey;
350 }
351
352 bool CKey::SetPubKey(const CPubKey& vchPubKey)
353 {
354     const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
355     if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
356     {
357         fSet = true;
358         if (vchPubKey.vchPubKey.size() == 33)
359             SetCompressedPubKey();
360         return true;
361     }
362     pkey = NULL;
363     Reset();
364     return false;
365 }
366
367 CPubKey CKey::GetPubKey() const
368 {
369     int nSize = i2o_ECPublicKey(pkey, NULL);
370     if (!nSize)
371         throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
372     std::vector<unsigned char> vchPubKey(nSize, 0);
373     unsigned char* pbegin = &vchPubKey[0];
374     if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
375         throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
376     return CPubKey(vchPubKey);
377 }
378
379 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
380 {
381     vchSig.clear();
382     ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
383     if (sig==NULL)
384         return false;
385     const EC_GROUP *group = EC_KEY_get0_group(pkey);
386     CBigNum order, halforder;
387     EC_GROUP_get_order(group, &order, NULL);
388     BN_rshift1(&halforder, &order);
389     // enforce low S values, by negating the value (modulo the order) if above order/2.
390     if (BN_cmp(sig->s, &halforder) > 0) {
391         BN_sub(sig->s, &order, sig->s);
392     }
393     unsigned int nSize = ECDSA_size(pkey);
394     vchSig.resize(nSize); // Make sure it is big enough
395     unsigned char *pos = &vchSig[0];
396     nSize = i2d_ECDSA_SIG(sig, &pos);
397     ECDSA_SIG_free(sig);
398     vchSig.resize(nSize); // Shrink to fit actual size
399     // Testing our new signature
400     if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
401         vchSig.clear();
402         return false;
403     }
404     return true;
405 }
406
407 // create a compact signature (65 bytes), which allows reconstructing the used public key
408 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
409 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
410 //                  0x1D = second key with even y, 0x1E = second key with odd y
411 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
412 {
413     bool fOk = false;
414     ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
415     if (sig==NULL)
416         return false;
417     const EC_GROUP *group = EC_KEY_get0_group(pkey);
418     CBigNum order, halforder;
419     EC_GROUP_get_order(group, &order, NULL);
420     BN_rshift1(&halforder, &order);
421     // enforce low S values, by negating the value (modulo the order) if above order/2.
422     if (BN_cmp(sig->s, &halforder) > 0) {
423         BN_sub(sig->s, &order, sig->s);
424     }
425     vchSig.clear();
426     vchSig.resize(65,0);
427     int nBitsR = BN_num_bits(sig->r);
428     int nBitsS = BN_num_bits(sig->s);
429     if (nBitsR <= 256 && nBitsS <= 256)
430     {
431         int8_t nRecId = -1;
432         for (int8_t i=0; i<4; i++)
433         {
434             CKey keyRec;
435             keyRec.fSet = true;
436             if (fCompressedPubKey)
437                 keyRec.SetCompressedPubKey();
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(sig->r,&vchSig[33-(nBitsR+7)/8]);
454         BN_bn2bin(sig->s,&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 CKey::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     BN_bin2bn(&vchSig[1],32,sig->r);
474     BN_bin2bn(&vchSig[33],32,sig->s);
475
476     EC_KEY_free(pkey);
477     pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
478     if (nV >= 31)
479     {
480         SetCompressedPubKey();
481         nV -= 4;
482     }
483     if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
484     {
485         fSet = true;
486         ECDSA_SIG_free(sig);
487         return true;
488     }
489     ECDSA_SIG_free(sig);
490     return false;
491 }
492
493 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
494 {
495     if (vchSig.empty())
496         return false;
497
498     // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
499     unsigned char *norm_der = NULL;
500     ECDSA_SIG *norm_sig = ECDSA_SIG_new();
501     const unsigned char* sigptr = &vchSig[0];
502     assert(norm_sig);
503     if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
504     {
505         /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
506         * error. But OpenSSL's own use of this function redundantly frees the
507         * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
508         * clear contract for the function behaving the same way is more
509         * conservative.
510         */
511         ECDSA_SIG_free(norm_sig);
512         return false;
513     }
514     int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
515     ECDSA_SIG_free(norm_sig);
516     if (derlen <= 0)
517         return false;
518
519     // -1 = error, 0 = bad sig, 1 = good
520     bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
521     OPENSSL_free(norm_der);
522     return ret;
523 }
524
525 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
526 {
527     CKey key;
528     if (!key.SetCompactSignature(hash, vchSig))
529         return false;
530     if (GetPubKey() != key.GetPubKey())
531         return false;
532
533     return true;
534 }
535
536 bool CKey::IsValid()
537 {
538     if (!fSet)
539         return false;
540
541     if (!EC_KEY_check_key(pkey))
542         return false;
543
544     bool fCompr;
545     CSecret secret = GetSecret(fCompr);
546     CKey key2;
547     key2.SetSecret(secret, fCompr);
548     return GetPubKey() == key2.GetPubKey();
549 }
550
551 CPoint::CPoint()
552 {
553     std::string err;
554     group = NULL;
555     point = NULL;
556     ctx   = NULL;
557
558     group = EC_GROUP_new_by_curve_name(NID_secp256k1);
559     if (!group) {
560         err = "EC_KEY_new_by_curve_name failed.";
561         goto finish;
562     }
563
564     point = EC_POINT_new(group);
565     if (!point) {
566         err = "EC_POINT_new failed.";
567         goto finish;
568     }
569
570     ctx = BN_CTX_new();
571     if (!ctx) {
572         err = "BN_CTX_new failed.";
573         goto finish;
574     }
575
576     return;
577
578 finish:
579     if (group) EC_GROUP_free(group);
580     if (point) EC_POINT_free(point);
581     throw std::runtime_error(std::string("CPoint::CPoint() :  - ") + err);
582 }
583
584 bool CPoint::operator!=(const CPoint &a)
585 {
586     if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
587         return true;
588     return false;
589 }
590 CPoint::~CPoint()
591 {
592     if (point) EC_POINT_free(point);
593     if (group) EC_GROUP_free(group);
594     if (ctx)   BN_CTX_free(ctx);
595 }
596
597 // Initialize from octets stream
598 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
599 {
600     if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
601         return false;
602     }
603     return true;
604 }
605
606 // Initialize from octets stream
607 bool CPoint::setPubKey(const CPubKey &vchPubKey)
608 {
609     return setBytes(vchPubKey.Raw());
610 }
611
612 // Serialize to octets stream
613 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
614 {
615     size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
616     vchBytes.resize(nSize);
617     if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
618         return false;
619     }
620     return true;
621 }
622
623 // ECC multiplication by specified multiplier
624 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
625 {
626     if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
627         printf("CPoint::ECMUL() : EC_POINT_mul failed");
628         return false;
629     }
630
631     return true;
632 }
633
634 // Calculate G*m + q
635 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
636 {
637     if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
638         printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
639         return false;
640     }
641
642     return true;
643 }
644
645 // CMalleablePubKey
646
647 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
648 {
649     EC_KEY *eckey = NULL;
650     eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
651     if (eckey == NULL) {
652         throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
653     }
654
655     // Use standard key generation function to get r and R values.
656     //
657     // r will be presented by private key;
658     // R is ECDSA public key which calculated as G*r
659     if (!EC_KEY_generate_key(eckey)) {
660         throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
661     }
662
663     EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
664
665     int nSize = i2o_ECPublicKey(eckey, NULL);
666     if (!nSize) {
667         throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
668     }
669
670     std::vector<unsigned char> vchPubKey(nSize, 0);
671     unsigned char* pbegin_R = &vchPubKey[0];
672
673     if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
674         throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
675     }
676
677     // R = G*r
678     R = CPubKey(vchPubKey);
679
680     // OpenSSL BIGNUM representation of r value
681     CBigNum bnr;
682     bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
683     EC_KEY_free(eckey);
684
685     CPoint point;
686     if (!point.setPubKey(pubKeyL)) {
687         throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
688     }
689
690     // Calculate L*r
691     point.ECMUL(bnr);
692
693     std::vector<unsigned char> vchLr;
694     if (!point.getBytes(vchLr)) {
695         throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
696     }
697
698     // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
699     CBigNum bnHash;
700     bnHash.setuint160(Hash160(vchLr));
701
702     CPoint pointH;
703     pointH.setPubKey(pubKeyH);
704
705     CPoint P;
706     // Calculate P = Hash(L*r)*G + H
707     P.ECMULGEN(bnHash, pointH);
708
709     if (P.IsInfinity()) {
710         throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
711     }
712
713     std::vector<unsigned char> vchResult;
714     P.getBytes(vchResult);
715
716     vchPubKeyVariant = CPubKey(vchResult);
717 }
718
719 std::string CMalleablePubKey::ToString() const
720 {
721     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
722     ssKey << *this;
723     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
724
725     return EncodeBase58Check(vch);
726 }
727
728 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
729 {
730     CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
731     ssKey >> *this;
732
733     return IsValid();
734 }
735
736 std::vector<unsigned char> CMalleablePubKey::Raw() const
737 {
738     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
739     ssKey << *this;
740     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
741
742     return vch;
743 }
744
745 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
746 {
747     std::vector<unsigned char> vchTemp;
748     if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
749         throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
750     }
751
752     CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
753     ssKey >> *this;
754
755     return IsValid();
756 }
757
758 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
759 {
760     return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
761 }
762
763
764 // CMalleableKey
765
766 void CMalleableKey::Reset()
767 {
768     vchSecretL.clear();
769     vchSecretH.clear();
770 }
771
772 void CMalleableKey::MakeNewKeys()
773 {
774     Reset();
775
776     CKey keyL, keyH;
777     keyL.MakeNewKey();
778     keyH.MakeNewKey();
779
780     vchSecretL = keyL.GetSecret();
781     vchSecretH = keyH.GetSecret();
782 }
783
784 CMalleableKey::CMalleableKey()
785 {
786     Reset();
787 }
788
789 CMalleableKey::CMalleableKey(const CMalleableKey &b)
790 {
791     SetSecrets(b.vchSecretL, b.vchSecretH);
792 }
793
794 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
795 {
796     SetSecrets(L, H);
797 }
798
799 CMalleableKey::~CMalleableKey()
800 {
801 }
802
803 bool CMalleableKey::IsNull() const
804 {
805     return vchSecretL.size() != 32 || vchSecretH.size() != 32;
806 }
807
808 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
809 {
810     Reset();
811
812     CKey keyL(pvchSecretL);
813     CKey keyH(pvchSecretH);
814
815     if (!keyL.IsValid() || !keyH.IsValid())
816         return false;
817
818     vchSecretL = pvchSecretL;
819     vchSecretH = pvchSecretH;
820
821     return true;
822 }
823
824 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
825 {
826     CKey L(vchSecretL), H(vchSecretH);
827     return CMalleablePubKey(L.GetPubKey().Raw(), H.GetPubKey().Raw());
828 }
829
830 // Check ownership
831 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
832 {
833     if (IsNull()) {
834         throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
835     }
836
837     if (!R.IsValid()) {
838         printf("CMalleableKey::CheckKeyVariant() : R is invalid");
839         return false;
840     }
841
842     if (!vchPubKeyVariant.IsValid()) {
843         printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
844         return false;
845     }
846
847     CPoint point_R;
848     if (!point_R.setPubKey(R)) {
849         printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
850         return false;
851     }
852
853     CKey H(vchSecretH);
854     std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
855
856     CPoint point_H;
857     if (!point_H.setPubKey(vchPubKeyH)) {
858         printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
859         return false;
860     }
861
862     CPoint point_P;
863     if (!point_P.setPubKey(vchPubKeyVariant)) {
864         printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
865         return false;
866     }
867
868     // Infinity points are senseless
869     if (point_P.IsInfinity()) {
870         printf("CMalleableKey::CheckKeyVariant() : P is infinity");
871         return false;
872     }
873
874     CBigNum bnl;
875     bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
876
877     point_R.ECMUL(bnl);
878
879     std::vector<unsigned char> vchRl;
880     if (!point_R.getBytes(vchRl)) {
881         printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
882         return false;
883     }
884
885     // Calculate Hash(R*l)
886     CBigNum bnHash;
887     bnHash.setuint160(Hash160(vchRl));
888
889     CPoint point_Ps;
890     // Calculate Ps = Hash(L*r)*G + H
891     point_Ps.ECMULGEN(bnHash, point_H);
892
893     // Infinity points are senseless
894     if (point_Ps.IsInfinity()) {
895         printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
896         return false;
897     }
898
899     // Check ownership
900     if (point_Ps != point_P) {
901         return false;
902     }
903
904     return true;
905 }
906
907 // Check ownership and restore private key
908 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
909 {
910     if (IsNull()) {
911         throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
912     }
913
914     if (!R.IsValid()) {
915         printf("CMalleableKey::CheckKeyVariant() : R is invalid");
916         return false;
917     }
918
919     if (!vchPubKeyVariant.IsValid()) {
920         printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
921         return false;
922     }
923
924     CPoint point_R;
925     if (!point_R.setPubKey(R)) {
926         printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
927         return false;
928     }
929
930     CKey H(vchSecretH);
931     std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
932
933     CPoint point_H;
934     if (!point_H.setPubKey(vchPubKeyH)) {
935         printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
936         return false;
937     }
938
939     CPoint point_P;
940     if (!point_P.setPubKey(vchPubKeyVariant)) {
941         printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
942         return false;
943     }
944
945     // Infinity points are senseless
946     if (point_P.IsInfinity()) {
947         printf("CMalleableKey::CheckKeyVariant() : P is infinity");
948         return false;
949     }
950
951     CBigNum bnl;
952     bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
953
954     point_R.ECMUL(bnl);
955
956     std::vector<unsigned char> vchRl;
957     if (!point_R.getBytes(vchRl)) {
958         printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
959         return false;
960     }
961
962     // Calculate Hash(R*l)
963     CBigNum bnHash;
964     bnHash.setuint160(Hash160(vchRl));
965
966     CPoint point_Ps;
967     // Calculate Ps = Hash(L*r)*G + H
968     point_Ps.ECMULGEN(bnHash, point_H);
969
970     // Infinity points are senseless
971     if (point_Ps.IsInfinity()) {
972         printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
973         return false;
974     }
975
976     // Check ownership
977     if (point_Ps != point_P) {
978         return false;
979     }
980
981     // OpenSSL BIGNUM representation of the second private key from (l, h) pair
982     CBigNum bnh;
983     bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
984
985     // Calculate p = Hash(R*l) + h
986     CBigNum bnp = bnHash + bnh;
987
988     std::vector<unsigned char> vchp = bnp.getBytes();
989     privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
990
991     return true;
992 }
993
994 std::string CMalleableKey::ToString() const
995 {
996     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
997     ssKey << *this;
998     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
999
1000     return EncodeBase58Check(vch);
1001 }
1002
1003 std::vector<unsigned char> CMalleableKey::Raw() const
1004 {
1005     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1006     ssKey << *this;
1007     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1008
1009     return vch;
1010 }
1011
1012 bool CMalleableKey::SetString(const std::string& strMutableKey)
1013 {
1014     std::vector<unsigned char> vchTemp;
1015     if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1016         throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1017     }
1018
1019     CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1020     ssKey >> *this;
1021
1022     return IsValid();
1023 }
1024
1025 // CMalleableKeyView
1026
1027 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1028 {
1029     SetString(strMalleableKey);
1030 }
1031
1032 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1033 {
1034     if (b.vchSecretL.size() != 32)
1035         throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1036
1037     if (b.vchSecretH.size() != 32)
1038         throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1039
1040     vchSecretL = b.vchSecretL;
1041
1042     CKey H(b.vchSecretH);
1043     vchPubKeyH = H.GetPubKey().Raw();
1044 }
1045
1046 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1047 {
1048     vchSecretL = b.vchSecretL;
1049     vchPubKeyH = b.vchPubKeyH;
1050 }
1051
1052 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1053 {
1054     vchSecretL = b.vchSecretL;
1055
1056     CKey H(b.vchSecretH);
1057     vchPubKeyH = H.GetPubKey().Raw();
1058
1059     return (*this);
1060 }
1061
1062 CMalleableKeyView::~CMalleableKeyView()
1063 {
1064 }
1065
1066 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1067 {
1068     CKey keyL(vchSecretL);
1069     return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1070 }
1071
1072 // Check ownership
1073 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1074 {
1075     if (!IsValid()) {
1076         throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1077     }
1078
1079     if (!R.IsValid()) {
1080         printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1081         return false;
1082     }
1083
1084     if (!vchPubKeyVariant.IsValid()) {
1085         printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1086         return false;
1087     }
1088
1089     CPoint point_R;
1090     if (!point_R.setPubKey(R)) {
1091         printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1092         return false;
1093     }
1094
1095     CPoint point_H;
1096     if (!point_H.setPubKey(vchPubKeyH)) {
1097         printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1098         return false;
1099     }
1100
1101     CPoint point_P;
1102     if (!point_P.setPubKey(vchPubKeyVariant)) {
1103         printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1104         return false;
1105     }
1106
1107     // Infinity points are senseless
1108     if (point_P.IsInfinity()) {
1109         printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1110         return false;
1111     }
1112
1113     CBigNum bnl;
1114     bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1115
1116     point_R.ECMUL(bnl);
1117
1118     std::vector<unsigned char> vchRl;
1119     if (!point_R.getBytes(vchRl)) {
1120         printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1121         return false;
1122     }
1123
1124     // Calculate Hash(R*l)
1125     CBigNum bnHash;
1126     bnHash.setuint160(Hash160(vchRl));
1127
1128     CPoint point_Ps;
1129     // Calculate Ps = Hash(L*r)*G + H
1130     point_Ps.ECMULGEN(bnHash, point_H);
1131
1132     // Infinity points are senseless
1133     if (point_Ps.IsInfinity()) {
1134         printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1135         return false;
1136     }
1137
1138     // Check ownership
1139     if (point_Ps != point_P) {
1140         return false;
1141     }
1142
1143     return true;
1144 }
1145
1146 std::string CMalleableKeyView::ToString() const
1147 {
1148     CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1149     ssKey << *this;
1150     std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1151
1152     return EncodeBase58Check(vch);
1153 }
1154
1155 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1156 {
1157     std::vector<unsigned char> vchTemp;
1158     if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1159         throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1160     }
1161
1162     CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1163     ssKey >> *this;
1164
1165     return IsValid();
1166 }
1167
1168 std::vector<unsigned char> CMalleableKeyView::Raw() 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 vch;
1175 }
1176
1177
1178 bool CMalleableKeyView::IsValid() const
1179 {
1180     return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1181 }
1182
1183 //// Asymmetric encryption
1184
1185 void CPubKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1186 {
1187     CKey key;
1188     key.SetPubKey(*this);
1189
1190     key.EncryptData(data, encrypted);
1191 }
1192
1193 void CKey::EncryptData(const std::vector<unsigned char>& data, std::vector<unsigned char>& encrypted)
1194 {
1195     ies_ctx_t *ctx;
1196     char error[1024] = "Unknown error";
1197     cryptogram_t *cryptogram;
1198
1199     ctx = create_context(pkey);
1200     if (!EC_KEY_get0_public_key(ctx->user_key))
1201         throw key_error("Given EC key is not public key");
1202
1203     cryptogram = ecies_encrypt(ctx, (unsigned char*)&data[0], data.size(), error);
1204     if (cryptogram == NULL) {
1205         delete ctx;
1206         ctx = NULL;
1207         throw key_error(std::string("Error in encryption: %s") + error);
1208     }
1209
1210     encrypted.resize(cryptogram_data_sum_length(cryptogram));
1211     unsigned char *key_data = cryptogram_key_data(cryptogram);
1212     memcpy(&encrypted[0], key_data, encrypted.size());
1213     cryptogram_free(cryptogram);
1214     delete ctx;
1215 }
1216
1217 void CKey::DecryptData(const std::vector<unsigned char>& encrypted, std::vector<unsigned char>& data)
1218 {
1219     ies_ctx_t *ctx;
1220     char error[1024] = "Unknown error";
1221     cryptogram_t *cryptogram;
1222     size_t length;
1223     unsigned char *decrypted;
1224
1225     ctx = create_context(pkey);
1226     if (!EC_KEY_get0_private_key(ctx->user_key))
1227         throw key_error("Given EC key is not private key");
1228
1229     size_t key_length = ctx->stored_key_length;
1230     size_t mac_length = EVP_MD_size(ctx->md);
1231     cryptogram = cryptogram_alloc(key_length, mac_length, encrypted.size() - key_length - mac_length);
1232
1233     memcpy(cryptogram_key_data(cryptogram), &encrypted[0], encrypted.size());
1234
1235     decrypted = ecies_decrypt(ctx, cryptogram, &length, error);
1236     cryptogram_free(cryptogram);
1237     delete ctx;
1238
1239     if (decrypted == NULL) {
1240         throw key_error(std::string("Error in decryption: %s") + error);
1241     }
1242
1243     data.resize(length);
1244     memcpy(&data[0], decrypted, length);
1245     free(decrypted);
1246 }