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