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