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((unsigned char*)&hash, 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, NULL);
373 BN_rshift1(halforder, order);
375 // Get internal R and S pointers
376 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
378 // enforce low S values, by negating the value (modulo the order) if above order/2.
379 if (BN_cmp(current_s, halforder) > 0) {
380 BIGNUM *updated_s = BN_new();
381 BN_copy(updated_s, current_s);
382 BN_sub(updated_s, order, updated_s);
383 ECDSA_SIG_set0(sig, NULL, updated_s);
389 unsigned int nSize = ECDSA_size(pkey);
390 vchSig.resize(nSize); // Make sure it is big enough
391 unsigned char *pos = &vchSig[0];
392 nSize = i2d_ECDSA_SIG(sig, &pos);
394 vchSig.resize(nSize); // Shrink to fit actual size
395 // Testing our new signature
396 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
403 // create a compact signature (65 bytes), which allows reconstructing the used public key
404 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
405 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
406 // 0x1D = second key with even y, 0x1E = second key with odd y
407 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
410 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
413 const EC_GROUP *group = EC_KEY_get0_group(pkey);
414 BIGNUM* order = BN_new(), *halforder = BN_new();
415 EC_GROUP_get_order(group, order, NULL);
416 BN_rshift1(halforder, order);
418 // Get internal R and S pointers
419 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
421 // enforce low S values, by negating the value (modulo the order) if above order/2.
422 if (BN_cmp(current_s, halforder) > 0) {
423 BIGNUM *updated_s = BN_new();
424 BN_copy(updated_s, current_s);
425 BN_sub(updated_s, order, updated_s);
426 ECDSA_SIG_set0(sig, NULL, updated_s);
434 int nBitsR = BN_num_bits(ECDSA_SIG_get0_r(sig));
435 int nBitsS = BN_num_bits(ECDSA_SIG_get0_s(sig));
436 bool fCompressedPubKey = IsCompressed();
437 if (nBitsR <= 256 && nBitsS <= 256)
440 for (int8_t i=0; i<4; i++)
444 keyRec.SetCompressedPubKey(fCompressedPubKey);
445 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
446 if (keyRec.GetPubKey() == this->GetPubKey())
456 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
459 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
460 BN_bn2bin(ECDSA_SIG_get0_r(sig),&vchSig[33-(nBitsR+7)/8]);
461 BN_bn2bin(ECDSA_SIG_get0_s(sig),&vchSig[65-(nBitsS+7)/8]);
469 // reconstruct public key from a compact signature
470 // This is only slightly more CPU intensive than just verifying it.
471 // If this function succeeds, the recovered public key is guaranteed to be valid
472 // (the signature is a valid signature of the given data for that key)
473 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
475 if (vchSig.size() != 65)
480 ECDSA_SIG *sig = ECDSA_SIG_new();
481 BIGNUM *sig_r = BN_new(), *sig_s = BN_new();
482 BN_bin2bn(&vchSig[1],32,sig_r);
483 BN_bin2bn(&vchSig[33],32,sig_s);
484 ECDSA_SIG_set0(sig, sig_r, sig_s);
485 bool fSuccessful = false;
486 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
490 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
494 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
496 int nSize = i2o_ECPublicKey(pkey, NULL);
499 std::vector<unsigned char> vchPubKey(nSize, 0);
500 unsigned char* pbegin = &vchPubKey[0];
501 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
503 Set(vchPubKey.begin(), vchPubKey.end());
504 fSuccessful = IsValid();
514 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
516 if (vchSig.empty() || !IsValid())
519 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
520 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
529 uint8_t *norm_der = NULL;
530 const uint8_t* pbegin = &vbytes[0];
531 const uint8_t* sigptr = &vchSig[0];
533 // Trying to parse public key
534 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
536 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
537 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
539 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
542 // -1 = error, 0 = bad sig, 1 = good
543 ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
544 OPENSSL_free(norm_der);
547 ECDSA_SIG_free(norm_sig);
553 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
556 if (!key.SetCompactSignature(hash, vchSig))
566 if (!EC_KEY_check_key(pkey))
570 CSecret secret = GetSecret(fCompr);
572 key2.SetSecret(secret, fCompr);
574 return GetPubKey() == key2.GetPubKey();
584 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
586 err = "EC_KEY_new_by_curve_name failed.";
590 point = EC_POINT_new(group);
592 err = "EC_POINT_new failed.";
598 err = "BN_CTX_new failed.";
605 if (group) EC_GROUP_free(group);
606 if (point) EC_POINT_free(point);
607 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
610 bool CPoint::operator!=(const CPoint &a)
612 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
618 if (point) EC_POINT_free(point);
619 if (group) EC_GROUP_free(group);
620 if (ctx) BN_CTX_free(ctx);
623 // Initialize from octets stream
624 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
626 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
632 // Initialize from octets stream
633 bool CPoint::setPubKey(const CPubKey &key)
635 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
636 return setBytes(vchPubKey);
639 // Serialize to octets stream
640 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
642 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
643 vchBytes.resize(nSize);
644 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
650 // ECC multiplication by specified multiplier
651 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
653 BIGNUM* bnMul = bnMultiplier.get();
654 bool ok = EC_POINT_mul(group, point, NULL, point, bnMul, NULL);
655 if (!ok) printf("CPoint::ECMUL() : EC_POINT_mul failed");
661 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
663 BIGNUM* bnMul = bnMultiplier.get();
664 bool ok = EC_POINT_mul(group, point, bnMul, qPoint.point, BN_value_one(), NULL);
665 if (!ok) printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
672 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
674 EC_KEY *eckey = NULL;
675 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
677 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
680 // Use standard key generation function to get r and R values.
682 // r will be presented by private key;
683 // R is ECDSA public key which calculated as G*r
684 if (!EC_KEY_generate_key(eckey)) {
685 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
688 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
690 int nSize = i2o_ECPublicKey(eckey, NULL);
692 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
695 std::vector<unsigned char> vchPubKey(nSize, 0);
696 unsigned char* pbegin_R = &vchPubKey[0];
698 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
699 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
703 R = CPubKey(vchPubKey);
705 // OpenSSL BIGNUM representation of r value
706 CBigNum bnr(EC_KEY_get0_private_key(eckey));
710 if (!point.setPubKey(pubKeyL)) {
711 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
717 std::vector<unsigned char> vchLr;
718 if (!point.getBytes(vchLr)) {
719 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
722 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
724 bnHash.setuint160(Hash160(vchLr));
727 pointH.setPubKey(pubKeyH);
730 // Calculate P = Hash(L*r)*G + H
731 P.ECMULGEN(bnHash, pointH);
733 if (P.IsInfinity()) {
734 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
737 std::vector<unsigned char> vchResult;
738 P.getBytes(vchResult);
740 vchPubKeyVariant = CPubKey(vchResult);
743 std::string CMalleablePubKey::ToString() const
745 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
747 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
749 return EncodeBase58Check(vch);
752 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
754 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
760 std::vector<unsigned char> CMalleablePubKey::Raw() const
762 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
764 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
769 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
771 std::vector<unsigned char> vchTemp;
772 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
773 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
775 if (vchTemp.size() != 68)
778 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
784 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
786 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
792 void CMalleableKey::Reset()
798 void CMalleableKey::MakeNewKeys()
806 vchSecretL = keyL.GetSecret();
807 vchSecretH = keyH.GetSecret();
810 CMalleableKey::CMalleableKey()
815 CMalleableKey::CMalleableKey(const CMalleableKey &b)
817 SetSecrets(b.vchSecretL, b.vchSecretH);
820 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
825 CMalleableKey::~CMalleableKey()
829 bool CMalleableKey::IsNull() const
831 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
834 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
838 CKey keyL(pvchSecretL);
839 CKey keyH(pvchSecretH);
841 if (!keyL.IsValid() || !keyH.IsValid())
844 vchSecretL = pvchSecretL;
845 vchSecretH = pvchSecretH;
850 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
852 CKey L(vchSecretL), H(vchSecretH);
853 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
857 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
860 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
864 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
868 if (!vchPubKeyVariant.IsValid()) {
869 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
874 if (!point_R.setPubKey(R)) {
875 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
880 CPubKey vchPubKeyH = H.GetPubKey();
883 if (!point_H.setPubKey(vchPubKeyH)) {
884 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
889 if (!point_P.setPubKey(vchPubKeyVariant)) {
890 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
894 // Infinity points are senseless
895 if (point_P.IsInfinity()) {
896 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
901 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
905 std::vector<unsigned char> vchRl;
906 if (!point_R.getBytes(vchRl)) {
907 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
911 // Calculate Hash(R*l)
913 bnHash.setuint160(Hash160(vchRl));
916 // Calculate Ps = Hash(L*r)*G + H
917 point_Ps.ECMULGEN(bnHash, point_H);
919 // Infinity points are senseless
920 if (point_Ps.IsInfinity()) {
921 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
926 if (point_Ps != point_P) {
933 // Check ownership and restore private key
934 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
937 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
941 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
945 if (!vchPubKeyVariant.IsValid()) {
946 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
951 if (!point_R.setPubKey(R)) {
952 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
957 CPubKey vchPubKeyH = H.GetPubKey();
960 if (!point_H.setPubKey(vchPubKeyH)) {
961 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
966 if (!point_P.setPubKey(vchPubKeyVariant)) {
967 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
971 // Infinity points are senseless
972 if (point_P.IsInfinity()) {
973 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
978 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
982 std::vector<unsigned char> vchRl;
983 if (!point_R.getBytes(vchRl)) {
984 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
988 // Calculate Hash(R*l)
990 bnHash.setuint160(Hash160(vchRl));
993 // Calculate Ps = Hash(L*r)*G + H
994 point_Ps.ECMULGEN(bnHash, point_H);
996 // Infinity points are senseless
997 if (point_Ps.IsInfinity()) {
998 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
1003 if (point_Ps != point_P) {
1007 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1009 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1011 // Calculate p = Hash(R*l) + h
1012 CBigNum bnp = bnHash + bnh;
1014 std::vector<unsigned char> vchp = bnp.getBytes();
1015 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1020 std::string CMalleableKey::ToString() const
1022 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1024 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1026 return EncodeBase58Check(vch);
1029 std::vector<unsigned char> CMalleableKey::Raw() const
1031 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1033 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1038 bool CMalleableKey::SetString(const std::string& strMutableKey)
1040 std::vector<unsigned char> vchTemp;
1041 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1042 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1044 if (vchTemp.size() != 66)
1046 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1052 // CMalleableKeyView
1054 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1056 SetString(strMalleableKey);
1059 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1061 if (b.vchSecretL.size() != 32)
1062 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1064 if (b.vchSecretH.size() != 32)
1065 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1067 vchSecretL = b.vchSecretL;
1069 CKey H(b.vchSecretH);
1070 vchPubKeyH = H.GetPubKey();
1073 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1075 vchSecretL = b.vchSecretL;
1076 vchPubKeyH = b.vchPubKeyH;
1079 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1081 vchSecretL = b.vchSecretL;
1083 CKey H(b.vchSecretH);
1084 vchPubKeyH = H.GetPubKey();
1089 CMalleableKeyView::~CMalleableKeyView()
1093 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1095 CKey keyL(vchSecretL);
1096 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1100 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1103 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1107 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1111 if (!vchPubKeyVariant.IsValid()) {
1112 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1117 if (!point_R.setPubKey(R)) {
1118 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1123 if (!point_H.setPubKey(vchPubKeyH)) {
1124 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1129 if (!point_P.setPubKey(vchPubKeyVariant)) {
1130 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1134 // Infinity points are senseless
1135 if (point_P.IsInfinity()) {
1136 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1141 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1145 std::vector<unsigned char> vchRl;
1146 if (!point_R.getBytes(vchRl)) {
1147 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1151 // Calculate Hash(R*l)
1153 bnHash.setuint160(Hash160(vchRl));
1156 // Calculate Ps = Hash(L*r)*G + H
1157 point_Ps.ECMULGEN(bnHash, point_H);
1159 // Infinity points are senseless
1160 if (point_Ps.IsInfinity()) {
1161 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1166 if (point_Ps != point_P) {
1173 std::string CMalleableKeyView::ToString() const
1175 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1177 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1179 return EncodeBase58Check(vch);
1182 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1184 std::vector<unsigned char> vchTemp;
1185 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1186 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1189 if (vchTemp.size() != 67)
1192 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1198 std::vector<unsigned char> CMalleableKeyView::Raw() const
1200 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1202 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1208 bool CMalleableKeyView::IsValid() const
1210 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();