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