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.
7 #include <openssl/ecdsa.h>
8 #include <openssl/evp.h>
13 // Generate a private key from just the secret parameter
14 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
18 EC_POINT *pub_key = NULL;
22 const EC_GROUP *group = EC_KEY_get0_group(eckey);
24 if ((ctx = BN_CTX_new()) == NULL)
27 pub_key = EC_POINT_new(group);
32 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
35 EC_KEY_set_private_key(eckey,priv_key);
36 EC_KEY_set_public_key(eckey,pub_key);
43 EC_POINT_free(pub_key);
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)
74 const EC_GROUP *group = EC_KEY_get0_group(eckey);
75 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
77 order = BN_CTX_get(ctx);
78 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
80 if (!BN_copy(x, order)) { ret=-1; goto err; }
81 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
83 // Get internal R and S pointers
84 const BIGNUM *ecsig_r, *ecsig_s;
85 ECDSA_SIG_get0(ecsig, &ecsig_r, &ecsig_s);
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; }
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; }
99 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
100 n = EC_GROUP_get_degree(group);
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);
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; }
123 if (R != NULL) EC_POINT_free(R);
124 if (O != NULL) EC_POINT_free(O);
125 if (Q != NULL) EC_POINT_free(Q);
129 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
130 while (c1len > c2len) {
136 while (c2len > c1len) {
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
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
170 const unsigned char *vchZero = NULL;
172 void CKey::SetCompressedPubKey(bool fCompressed)
174 EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
182 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
184 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
193 CKey::CKey(const CKey& b)
195 pkey = EC_KEY_dup(b.pkey);
197 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
201 CKey::CKey(const CSecret& b, bool fCompressed)
203 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
205 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
206 SetSecret(b, fCompressed);
209 CKey& CKey::operator=(const CKey& b)
211 if (!EC_KEY_copy(pkey, b.pkey))
212 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
223 bool CKey::IsNull() const
228 bool CKey::IsCompressed() const
230 return (EC_KEY_get_conv_form(pkey) == POINT_CONVERSION_COMPRESSED);
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;
238 bool CPubKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
243 unsigned char *pos = &vchSig[0];
244 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
249 int nSize = i2d_ECDSA_SIG(sig, NULL);
251 vchSig.resize(nSize); // grow or shrink as needed
254 i2d_ECDSA_SIG(sig, &pos);
264 void CKey::MakeNewKey(bool fCompressed)
266 if (!EC_KEY_generate_key(pkey))
267 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
268 SetCompressedPubKey(fCompressed);
272 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
274 const unsigned char* pbegin = &vchPrivKey[0];
275 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
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))
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)
295 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
298 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
300 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
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());
306 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
307 if (!EC_KEY_regenerate_key(pkey,bn))
310 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
314 SetCompressedPubKey(fCompressed);
318 CSecret CKey::GetSecret(bool &fCompressed) const
322 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
323 int nBytes = BN_num_bytes(bn);
325 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
326 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
328 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
329 fCompressed = IsCompressed();
333 CSecret CKey::GetSecret() const
336 return GetSecret(fCompressed);
339 CPrivKey CKey::GetPrivKey() const
341 int nSize = i2d_ECPrivateKey(pkey, NULL);
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");
351 CPubKey CKey::GetPubKey() const
353 int nSize = i2o_ECPublicKey(pkey, NULL);
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);
363 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
366 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
369 const EC_GROUP *group = EC_KEY_get0_group(pkey);
370 CBigNum order, halforder;
371 EC_GROUP_get_order(group, order.get(), NULL);
372 BN_rshift1(halforder.get(), order.get());
374 // Get internal R and S pointers
375 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
377 // enforce low S values, by negating the value (modulo the order) if above order/2.
378 if (BN_cmp(current_s, halforder.get()) > 0) {
379 BIGNUM *updated_s = BN_new();
380 BN_copy(updated_s, current_s);
381 BN_sub(updated_s, order.get(), updated_s);
382 ECDSA_SIG_set0(sig, NULL, updated_s);
385 unsigned int nSize = ECDSA_size(pkey);
386 vchSig.resize(nSize); // Make sure it is big enough
387 unsigned char *pos = &vchSig[0];
388 nSize = i2d_ECDSA_SIG(sig, &pos);
390 vchSig.resize(nSize); // Shrink to fit actual size
391 // Testing our new signature
392 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
399 // create a compact signature (65 bytes), which allows reconstructing the used public key
400 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
401 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
402 // 0x1D = second key with even y, 0x1E = second key with odd y
403 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
406 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
409 const EC_GROUP *group = EC_KEY_get0_group(pkey);
410 CBigNum order, halforder;
411 EC_GROUP_get_order(group, order.get(), NULL);
412 BN_rshift1(halforder.get(), order.get());
414 // Get internal R and S pointers
415 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
417 // enforce low S values, by negating the value (modulo the order) if above order/2.
418 if (BN_cmp(current_s, halforder.get()) > 0) {
419 BIGNUM *updated_s = BN_new();
420 BN_copy(updated_s, current_s);
421 BN_sub(updated_s, order.get(), updated_s);
422 ECDSA_SIG_set0(sig, NULL, updated_s);
427 int nBitsR = BN_num_bits(ECDSA_SIG_get0_r(sig));
428 int nBitsS = BN_num_bits(ECDSA_SIG_get0_s(sig));
429 bool fCompressedPubKey = IsCompressed();
430 if (nBitsR <= 256 && nBitsS <= 256)
433 for (int8_t i=0; i<4; i++)
437 keyRec.SetCompressedPubKey(fCompressedPubKey);
438 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
439 if (keyRec.GetPubKey() == this->GetPubKey())
449 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
452 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
453 BN_bn2bin(ECDSA_SIG_get0_r(sig),&vchSig[33-(nBitsR+7)/8]);
454 BN_bn2bin(ECDSA_SIG_get0_s(sig),&vchSig[65-(nBitsS+7)/8]);
461 // reconstruct public key from a compact signature
462 // This is only slightly more CPU intensive than just verifying it.
463 // If this function succeeds, the recovered public key is guaranteed to be valid
464 // (the signature is a valid signature of the given data for that key)
465 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
467 if (vchSig.size() != 65)
472 ECDSA_SIG *sig = ECDSA_SIG_new();
473 BIGNUM *sig_r = BN_new(), *sig_s = BN_new();
474 BN_bin2bn(&vchSig[1],32,sig_r);
475 BN_bin2bn(&vchSig[33],32,sig_s);
476 ECDSA_SIG_set0(sig, sig_r, sig_s);
477 bool fSuccessful = false;
478 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
482 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
486 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
488 int nSize = i2o_ECPublicKey(pkey, NULL);
491 std::vector<unsigned char> vchPubKey(nSize, 0);
492 unsigned char* pbegin = &vchPubKey[0];
493 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
495 Set(vchPubKey.begin(), vchPubKey.end());
496 fSuccessful = IsValid();
506 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
508 if (vchSig.empty() || !IsValid())
511 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
512 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
521 uint8_t *norm_der = NULL;
522 const uint8_t* pbegin = &vbytes[0];
523 const uint8_t* sigptr = &vchSig[0];
525 // Trying to parse public key
526 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
528 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
529 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
531 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
534 // -1 = error, 0 = bad sig, 1 = good
535 ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
536 OPENSSL_free(norm_der);
539 ECDSA_SIG_free(norm_sig);
545 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
548 if (!key.SetCompactSignature(hash, vchSig))
558 if (!EC_KEY_check_key(pkey))
562 CSecret secret = GetSecret(fCompr);
564 key2.SetSecret(secret, fCompr);
566 return GetPubKey() == key2.GetPubKey();
576 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
578 err = "EC_KEY_new_by_curve_name failed.";
582 point = EC_POINT_new(group);
584 err = "EC_POINT_new failed.";
590 err = "BN_CTX_new failed.";
597 if (group) EC_GROUP_free(group);
598 if (point) EC_POINT_free(point);
599 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
602 bool CPoint::operator!=(const CPoint &a)
604 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
610 if (point) EC_POINT_free(point);
611 if (group) EC_GROUP_free(group);
612 if (ctx) BN_CTX_free(ctx);
615 // Initialize from octets stream
616 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
618 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
624 // Initialize from octets stream
625 bool CPoint::setPubKey(const CPubKey &key)
627 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
628 return setBytes(vchPubKey);
631 // Serialize to octets stream
632 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
634 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
635 vchBytes.resize(nSize);
636 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
642 // ECC multiplication by specified multiplier
643 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
645 if (!EC_POINT_mul(group, point, NULL, point, bnMultiplier.get(), NULL)) {
646 printf("CPoint::ECMUL() : EC_POINT_mul failed");
654 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
656 if (!EC_POINT_mul(group, point, bnMultiplier.get(), qPoint.point, BN_value_one(), NULL)) {
657 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
666 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
668 EC_KEY *eckey = NULL;
669 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
671 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
674 // Use standard key generation function to get r and R values.
676 // r will be presented by private key;
677 // R is ECDSA public key which calculated as G*r
678 if (!EC_KEY_generate_key(eckey)) {
679 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
682 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
684 int nSize = i2o_ECPublicKey(eckey, NULL);
686 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
689 std::vector<unsigned char> vchPubKey(nSize, 0);
690 unsigned char* pbegin_R = &vchPubKey[0];
692 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
693 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
697 R = CPubKey(vchPubKey);
699 // OpenSSL BIGNUM representation of r value
701 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
705 if (!point.setPubKey(pubKeyL)) {
706 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
712 std::vector<unsigned char> vchLr;
713 if (!point.getBytes(vchLr)) {
714 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
717 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
719 bnHash.setuint160(Hash160(vchLr));
722 pointH.setPubKey(pubKeyH);
725 // Calculate P = Hash(L*r)*G + H
726 P.ECMULGEN(bnHash, pointH);
728 if (P.IsInfinity()) {
729 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
732 std::vector<unsigned char> vchResult;
733 P.getBytes(vchResult);
735 vchPubKeyVariant = CPubKey(vchResult);
738 std::string CMalleablePubKey::ToString() const
740 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
742 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
744 return EncodeBase58Check(vch);
747 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
749 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
755 std::vector<unsigned char> CMalleablePubKey::Raw() const
757 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
759 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
764 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
766 std::vector<unsigned char> vchTemp;
767 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
768 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
770 if (vchTemp.size() != 68)
773 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
779 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
781 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
787 void CMalleableKey::Reset()
793 void CMalleableKey::MakeNewKeys()
801 vchSecretL = keyL.GetSecret();
802 vchSecretH = keyH.GetSecret();
805 CMalleableKey::CMalleableKey()
810 CMalleableKey::CMalleableKey(const CMalleableKey &b)
812 SetSecrets(b.vchSecretL, b.vchSecretH);
815 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
820 CMalleableKey::~CMalleableKey()
824 bool CMalleableKey::IsNull() const
826 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
829 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
833 CKey keyL(pvchSecretL);
834 CKey keyH(pvchSecretH);
836 if (!keyL.IsValid() || !keyH.IsValid())
839 vchSecretL = pvchSecretL;
840 vchSecretH = pvchSecretH;
845 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
847 CKey L(vchSecretL), H(vchSecretH);
848 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
852 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
855 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
859 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
863 if (!vchPubKeyVariant.IsValid()) {
864 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
869 if (!point_R.setPubKey(R)) {
870 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
875 CPubKey vchPubKeyH = H.GetPubKey();
878 if (!point_H.setPubKey(vchPubKeyH)) {
879 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
884 if (!point_P.setPubKey(vchPubKeyVariant)) {
885 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
889 // Infinity points are senseless
890 if (point_P.IsInfinity()) {
891 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
896 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
900 std::vector<unsigned char> vchRl;
901 if (!point_R.getBytes(vchRl)) {
902 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
906 // Calculate Hash(R*l)
908 bnHash.setuint160(Hash160(vchRl));
911 // Calculate Ps = Hash(L*r)*G + H
912 point_Ps.ECMULGEN(bnHash, point_H);
914 // Infinity points are senseless
915 if (point_Ps.IsInfinity()) {
916 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
921 if (point_Ps != point_P) {
928 // Check ownership and restore private key
929 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
932 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
936 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
940 if (!vchPubKeyVariant.IsValid()) {
941 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
946 if (!point_R.setPubKey(R)) {
947 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
952 CPubKey vchPubKeyH = H.GetPubKey();
955 if (!point_H.setPubKey(vchPubKeyH)) {
956 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
961 if (!point_P.setPubKey(vchPubKeyVariant)) {
962 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
966 // Infinity points are senseless
967 if (point_P.IsInfinity()) {
968 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
973 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
977 std::vector<unsigned char> vchRl;
978 if (!point_R.getBytes(vchRl)) {
979 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
983 // Calculate Hash(R*l)
985 bnHash.setuint160(Hash160(vchRl));
988 // Calculate Ps = Hash(L*r)*G + H
989 point_Ps.ECMULGEN(bnHash, point_H);
991 // Infinity points are senseless
992 if (point_Ps.IsInfinity()) {
993 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
998 if (point_Ps != point_P) {
1002 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1004 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1006 // Calculate p = Hash(R*l) + h
1007 CBigNum bnp = bnHash + bnh;
1009 std::vector<unsigned char> vchp = bnp.getBytes();
1010 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1015 std::string CMalleableKey::ToString() const
1017 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1019 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1021 return EncodeBase58Check(vch);
1024 std::vector<unsigned char> CMalleableKey::Raw() const
1026 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1028 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1033 bool CMalleableKey::SetString(const std::string& strMutableKey)
1035 std::vector<unsigned char> vchTemp;
1036 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1037 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1039 if (vchTemp.size() != 66)
1041 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1047 // CMalleableKeyView
1049 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1051 SetString(strMalleableKey);
1054 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1056 if (b.vchSecretL.size() != 32)
1057 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1059 if (b.vchSecretH.size() != 32)
1060 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1062 vchSecretL = b.vchSecretL;
1064 CKey H(b.vchSecretH);
1065 vchPubKeyH = H.GetPubKey();
1068 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1070 vchSecretL = b.vchSecretL;
1071 vchPubKeyH = b.vchPubKeyH;
1074 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1076 vchSecretL = b.vchSecretL;
1078 CKey H(b.vchSecretH);
1079 vchPubKeyH = H.GetPubKey();
1084 CMalleableKeyView::~CMalleableKeyView()
1088 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1090 CKey keyL(vchSecretL);
1091 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1095 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1098 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1102 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1106 if (!vchPubKeyVariant.IsValid()) {
1107 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1112 if (!point_R.setPubKey(R)) {
1113 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1118 if (!point_H.setPubKey(vchPubKeyH)) {
1119 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1124 if (!point_P.setPubKey(vchPubKeyVariant)) {
1125 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1129 // Infinity points are senseless
1130 if (point_P.IsInfinity()) {
1131 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1136 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1140 std::vector<unsigned char> vchRl;
1141 if (!point_R.getBytes(vchRl)) {
1142 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1146 // Calculate Hash(R*l)
1148 bnHash.setuint160(Hash160(vchRl));
1151 // Calculate Ps = Hash(L*r)*G + H
1152 point_Ps.ECMULGEN(bnHash, point_H);
1154 // Infinity points are senseless
1155 if (point_Ps.IsInfinity()) {
1156 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1161 if (point_Ps != point_P) {
1168 std::string CMalleableKeyView::ToString() const
1170 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1172 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1174 return EncodeBase58Check(vch);
1177 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1179 std::vector<unsigned char> vchTemp;
1180 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1181 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1184 if (vchTemp.size() != 67)
1187 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1193 std::vector<unsigned char> CMalleableKeyView::Raw() const
1195 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1197 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1203 bool CMalleableKeyView::IsValid() const
1205 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();