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