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