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);
105 if (!BN_set_word(zero, 0)) { ret=-1; goto err; }
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(hash.begin(), sizeof(hash), pkey);
369 const EC_GROUP *group = EC_KEY_get0_group(pkey);
371 BIGNUM* order = BN_new(), *halforder = BN_new();
372 EC_GROUP_get_order(group, order, nullptr);
373 BN_rshift1(halforder, order);
375 // Get internal R and S pointers
376 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
377 BIGNUM *current_r = BN_dup(ECDSA_SIG_get0_r(sig));
379 // enforce low S values, by negating the value (modulo the order) if above order/2.
380 if (BN_cmp(current_s, halforder) > 0) {
381 BIGNUM *updated_s = BN_new();
382 BN_copy(updated_s, current_s);
383 BN_sub(updated_s, order, updated_s);
384 ECDSA_SIG_set0(sig, current_r, updated_s);
390 unsigned int nSize = ECDSA_size(pkey);
391 vchSig.resize(nSize); // Make sure it is big enough
392 unsigned char *pos = &vchSig[0];
393 nSize = i2d_ECDSA_SIG(sig, &pos);
395 vchSig.resize(nSize); // Shrink to fit actual size
396 // Testing our new signature
397 if (ECDSA_verify(0, hash.begin(), sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
404 // create a compact signature (65 bytes), which allows reconstructing the used public key
405 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
406 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
407 // 0x1D = second key with even y, 0x1E = second key with odd y
408 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
411 ECDSA_SIG *sig = ECDSA_do_sign(hash.begin(), sizeof(hash), pkey);
414 const EC_GROUP *group = EC_KEY_get0_group(pkey);
415 BIGNUM* order = BN_new(), *halforder = BN_new();
416 EC_GROUP_get_order(group, order, nullptr);
417 BN_rshift1(halforder, order);
419 // Get internal R and S pointers
420 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
421 BIGNUM *current_r = BN_dup(ECDSA_SIG_get0_r(sig));
423 // enforce low S values, by negating the value (modulo the order) if above order/2.
424 if (BN_cmp(current_s, halforder) > 0) {
425 BIGNUM *updated_s = BN_new();
426 BN_copy(updated_s, current_s);
427 BN_sub(updated_s, order, updated_s);
428 ECDSA_SIG_set0(sig, current_r, updated_s);
436 int nBitsR = BN_num_bits(ECDSA_SIG_get0_r(sig));
437 int nBitsS = BN_num_bits(ECDSA_SIG_get0_s(sig));
438 bool fCompressedPubKey = IsCompressed();
439 if (nBitsR <= 256 && nBitsS <= 256)
442 for (int8_t i=0; i<4; i++)
446 keyRec.SetCompressedPubKey(fCompressedPubKey);
447 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, hash.begin(), sizeof(hash), i, 1) == 1)
448 if (keyRec.GetPubKey() == this->GetPubKey())
458 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
461 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
462 BN_bn2bin(ECDSA_SIG_get0_r(sig),&vchSig[33-(nBitsR+7)/8]);
463 BN_bn2bin(ECDSA_SIG_get0_s(sig),&vchSig[65-(nBitsS+7)/8]);
471 // reconstruct public key from a compact signature
472 // This is only slightly more CPU intensive than just verifying it.
473 // If this function succeeds, the recovered public key is guaranteed to be valid
474 // (the signature is a valid signature of the given data for that key)
475 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
477 if (vchSig.size() != 65)
482 ECDSA_SIG *sig = ECDSA_SIG_new();
483 BIGNUM *sig_r = BN_new(), *sig_s = BN_new();
484 BN_bin2bn(&vchSig[1],32,sig_r);
485 BN_bin2bn(&vchSig[33],32,sig_s);
486 ECDSA_SIG_set0(sig, sig_r, sig_s);
487 bool fSuccessful = false;
488 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
492 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
496 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
498 int nSize = i2o_ECPublicKey(pkey, NULL);
501 std::vector<unsigned char> vchPubKey(nSize, 0);
502 unsigned char* pbegin = &vchPubKey[0];
503 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
505 Set(vchPubKey.begin(), vchPubKey.end());
506 fSuccessful = IsValid();
516 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
518 if (vchSig.empty() || !IsValid())
521 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
522 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
531 uint8_t *norm_der = NULL;
532 const uint8_t* pbegin = &vbytes[0];
533 const uint8_t* sigptr = &vchSig[0];
535 // Trying to parse public key
536 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
538 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
539 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
541 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
544 // -1 = error, 0 = bad sig, 1 = good
545 ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
546 OPENSSL_free(norm_der);
549 ECDSA_SIG_free(norm_sig);
555 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
558 if (!key.SetCompactSignature(hash, vchSig))
568 if (!EC_KEY_check_key(pkey))
572 CSecret secret = GetSecret(fCompr);
574 key2.SetSecret(secret, fCompr);
576 return GetPubKey() == key2.GetPubKey();
586 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
588 err = "EC_KEY_new_by_curve_name failed.";
592 point = EC_POINT_new(group);
594 err = "EC_POINT_new failed.";
600 err = "BN_CTX_new failed.";
607 if (group) EC_GROUP_free(group);
608 if (point) EC_POINT_free(point);
609 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
612 bool CPoint::operator!=(const CPoint &a)
614 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
620 if (point) EC_POINT_free(point);
621 if (group) EC_GROUP_free(group);
622 if (ctx) BN_CTX_free(ctx);
625 // Initialize from octets stream
626 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
628 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
634 // Initialize from octets stream
635 bool CPoint::setPubKey(const CPubKey &key)
637 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
638 return setBytes(vchPubKey);
641 // Serialize to octets stream
642 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
644 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
645 vchBytes.resize(nSize);
646 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
652 // ECC multiplication by specified multiplier
653 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
655 BIGNUM* bnMul = bnMultiplier.get();
656 bool ok = EC_POINT_mul(group, point, NULL, point, bnMul, NULL);
657 if (!ok) printf("CPoint::ECMUL() : EC_POINT_mul failed");
663 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
665 BIGNUM* bnMul = bnMultiplier.get();
666 bool ok = EC_POINT_mul(group, point, bnMul, qPoint.point, BN_value_one(), NULL);
667 if (!ok) printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
674 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
676 EC_KEY *eckey = NULL;
677 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
679 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
682 // Use standard key generation function to get r and R values.
684 // r will be presented by private key;
685 // R is ECDSA public key which calculated as G*r
686 if (!EC_KEY_generate_key(eckey)) {
687 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
690 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
692 int nSize = i2o_ECPublicKey(eckey, NULL);
694 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
697 std::vector<unsigned char> vchPubKey(nSize, 0);
698 unsigned char* pbegin_R = &vchPubKey[0];
700 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
701 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
705 R = CPubKey(vchPubKey);
707 // OpenSSL BIGNUM representation of r value
708 CBigNum bnr(EC_KEY_get0_private_key(eckey));
712 if (!point.setPubKey(pubKeyL)) {
713 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
719 std::vector<unsigned char> vchLr;
720 if (!point.getBytes(vchLr)) {
721 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
724 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
726 bnHash.setuint160(Hash160(vchLr));
729 pointH.setPubKey(pubKeyH);
732 // Calculate P = Hash(L*r)*G + H
733 P.ECMULGEN(bnHash, pointH);
735 if (P.IsInfinity()) {
736 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
739 std::vector<unsigned char> vchResult;
740 P.getBytes(vchResult);
742 vchPubKeyVariant = CPubKey(vchResult);
745 std::string CMalleablePubKey::ToString() const
747 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
749 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
751 return EncodeBase58Check(vch);
754 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
756 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
762 std::vector<unsigned char> CMalleablePubKey::Raw() const
764 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
766 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
771 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
773 std::vector<unsigned char> vchTemp;
774 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
775 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
777 if (vchTemp.size() != 68)
780 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
786 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
788 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
794 void CMalleableKey::Reset()
800 void CMalleableKey::MakeNewKeys()
808 vchSecretL = keyL.GetSecret();
809 vchSecretH = keyH.GetSecret();
812 CMalleableKey::CMalleableKey()
817 CMalleableKey::CMalleableKey(const CMalleableKey &b)
819 SetSecrets(b.vchSecretL, b.vchSecretH);
822 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
827 CMalleableKey::~CMalleableKey()
831 bool CMalleableKey::IsNull() const
833 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
836 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
840 CKey keyL(pvchSecretL);
841 CKey keyH(pvchSecretH);
843 if (!keyL.IsValid() || !keyH.IsValid())
846 vchSecretL = pvchSecretL;
847 vchSecretH = pvchSecretH;
852 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
854 CKey L(vchSecretL), H(vchSecretH);
855 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
859 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
862 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
866 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
870 if (!vchPubKeyVariant.IsValid()) {
871 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
876 if (!point_R.setPubKey(R)) {
877 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
882 CPubKey vchPubKeyH = H.GetPubKey();
885 if (!point_H.setPubKey(vchPubKeyH)) {
886 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
891 if (!point_P.setPubKey(vchPubKeyVariant)) {
892 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
896 // Infinity points are senseless
897 if (point_P.IsInfinity()) {
898 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
903 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
907 std::vector<unsigned char> vchRl;
908 if (!point_R.getBytes(vchRl)) {
909 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
913 // Calculate Hash(R*l)
915 bnHash.setuint160(Hash160(vchRl));
918 // Calculate Ps = Hash(L*r)*G + H
919 point_Ps.ECMULGEN(bnHash, point_H);
921 // Infinity points are senseless
922 if (point_Ps.IsInfinity()) {
923 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
928 if (point_Ps != point_P) {
935 // Check ownership and restore private key
936 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
939 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
943 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
947 if (!vchPubKeyVariant.IsValid()) {
948 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
953 if (!point_R.setPubKey(R)) {
954 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
959 CPubKey vchPubKeyH = H.GetPubKey();
962 if (!point_H.setPubKey(vchPubKeyH)) {
963 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
968 if (!point_P.setPubKey(vchPubKeyVariant)) {
969 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
973 // Infinity points are senseless
974 if (point_P.IsInfinity()) {
975 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
980 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
984 std::vector<unsigned char> vchRl;
985 if (!point_R.getBytes(vchRl)) {
986 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
990 // Calculate Hash(R*l)
992 bnHash.setuint160(Hash160(vchRl));
995 // Calculate Ps = Hash(L*r)*G + H
996 point_Ps.ECMULGEN(bnHash, point_H);
998 // Infinity points are senseless
999 if (point_Ps.IsInfinity()) {
1000 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
1005 if (point_Ps != point_P) {
1009 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1011 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1013 // Calculate p = Hash(R*l) + h
1014 CBigNum bnp = bnHash + bnh;
1016 std::vector<unsigned char> vchp = bnp.getBytes();
1017 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1022 std::string CMalleableKey::ToString() const
1024 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1026 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1028 return EncodeBase58Check(vch);
1031 std::vector<unsigned char> CMalleableKey::Raw() const
1033 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1035 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1040 bool CMalleableKey::SetString(const std::string& strMutableKey)
1042 std::vector<unsigned char> vchTemp;
1043 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1044 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1046 if (vchTemp.size() != 66)
1048 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1054 // CMalleableKeyView
1056 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1058 SetString(strMalleableKey);
1061 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1063 if (b.vchSecretL.size() != 32)
1064 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1066 if (b.vchSecretH.size() != 32)
1067 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1069 vchSecretL = b.vchSecretL;
1071 CKey H(b.vchSecretH);
1072 vchPubKeyH = H.GetPubKey();
1075 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1077 vchSecretL = b.vchSecretL;
1078 vchPubKeyH = b.vchPubKeyH;
1081 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1083 vchSecretL = b.vchSecretL;
1085 CKey H(b.vchSecretH);
1086 vchPubKeyH = H.GetPubKey();
1091 CMalleableKeyView::~CMalleableKeyView()
1095 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1097 CKey keyL(vchSecretL);
1098 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1102 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1105 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1109 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1113 if (!vchPubKeyVariant.IsValid()) {
1114 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1119 if (!point_R.setPubKey(R)) {
1120 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1125 if (!point_H.setPubKey(vchPubKeyH)) {
1126 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1131 if (!point_P.setPubKey(vchPubKeyVariant)) {
1132 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1136 // Infinity points are senseless
1137 if (point_P.IsInfinity()) {
1138 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1143 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1147 std::vector<unsigned char> vchRl;
1148 if (!point_R.getBytes(vchRl)) {
1149 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1153 // Calculate Hash(R*l)
1155 bnHash.setuint160(Hash160(vchRl));
1158 // Calculate Ps = Hash(L*r)*G + H
1159 point_Ps.ECMULGEN(bnHash, point_H);
1161 // Infinity points are senseless
1162 if (point_Ps.IsInfinity()) {
1163 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1168 if (point_Ps != point_P) {
1175 std::string CMalleableKeyView::ToString() const
1177 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1179 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1181 return EncodeBase58Check(vch);
1184 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1186 std::vector<unsigned char> vchTemp;
1187 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1188 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1191 if (vchTemp.size() != 67)
1194 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1200 std::vector<unsigned char> CMalleableKeyView::Raw() const
1202 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1204 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1210 bool CMalleableKeyView::IsValid() const
1212 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();