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>
14 // Generate a private key from just the secret parameter
15 int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
20 BN_CTX *ctx = nullptr;
21 EC_POINT *pub_key = nullptr;
23 const EC_GROUP *group = EC_KEY_get0_group(eckey);
25 if ((ctx = BN_CTX_new()) == nullptr)
28 pub_key = EC_POINT_new(group);
30 if (pub_key == nullptr)
33 if (!EC_POINT_mul(group, pub_key, priv_key, nullptr, nullptr, ctx))
36 if (!EC_KEY_set_private_key(eckey,priv_key))
38 if (!EC_KEY_set_public_key(eckey,pub_key))
46 EC_POINT_free(pub_key);
53 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
54 // recid selects which key is recovered
55 // if check is non-zero, additional checks are performed
56 int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
77 const EC_GROUP *group = EC_KEY_get0_group(eckey);
78 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
80 order = BN_CTX_get(ctx);
81 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
83 if (!BN_copy(x, order)) { ret=-1; goto err; }
84 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
86 // Get internal R and S pointers
87 const BIGNUM *ecsig_r, *ecsig_s;
88 ECDSA_SIG_get0(ecsig, &ecsig_r, &ecsig_s);
90 if (!BN_add(x, x, ecsig_r)) { ret=-1; goto err; }
91 field = BN_CTX_get(ctx);
92 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
93 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
94 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
95 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
98 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
99 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
100 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
102 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
103 n = EC_GROUP_get_degree(group);
105 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
106 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
107 zero = BN_CTX_get(ctx);
108 if (!BN_set_word(zero, 0)) { ret=-1; goto err; }
109 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
110 rr = BN_CTX_get(ctx);
111 if (!BN_mod_inverse(rr, ecsig_r, order, ctx)) { ret=-1; goto err; }
112 sor = BN_CTX_get(ctx);
113 if (!BN_mod_mul(sor, ecsig_s, rr, order, ctx)) { ret=-1; goto err; }
114 eor = BN_CTX_get(ctx);
115 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
116 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
117 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
126 if (R != NULL) EC_POINT_free(R);
127 if (O != NULL) EC_POINT_free(O);
128 if (Q != NULL) EC_POINT_free(Q);
132 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
133 while (c1len > c2len) {
139 while (c2len > c1len) {
157 // Order of secp256k1's generator minus 1.
158 const unsigned char vchMaxModOrder[32] = {
159 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
160 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
161 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
162 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
165 // Half of the order of secp256k1's generator minus 1.
166 const unsigned char vchMaxModHalfOrder[32] = {
167 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
168 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
169 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
170 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
173 const unsigned char *vchZero = NULL;
175 void CKey::SetCompressedPubKey(bool fCompressed)
177 EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED);
185 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
187 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
196 CKey::CKey(const CKey& b)
198 pkey = EC_KEY_dup(b.pkey);
200 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
204 CKey::CKey(const CSecret& b, bool fCompressed)
206 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
208 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
209 SetSecret(b, fCompressed);
212 CKey& CKey::operator=(const CKey& b)
214 if (!EC_KEY_copy(pkey, b.pkey))
215 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
226 bool CKey::IsNull() const
231 bool CKey::IsCompressed() const
233 return (EC_KEY_get_conv_form(pkey) == POINT_CONVERSION_COMPRESSED);
236 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
237 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
238 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
241 bool CPubKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
246 unsigned char *pos = &vchSig[0];
247 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
252 int nSize = i2d_ECDSA_SIG(sig, NULL);
254 vchSig.resize(nSize); // grow or shrink as needed
257 i2d_ECDSA_SIG(sig, &pos);
267 void CKey::MakeNewKey(bool fCompressed)
269 if (!EC_KEY_generate_key(pkey))
270 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
271 SetCompressedPubKey(fCompressed);
275 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
277 const unsigned char* pbegin = &vchPrivKey[0];
278 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
280 // In testing, d2i_ECPrivateKey can return true
281 // but fill in pkey with a key that fails
282 // EC_KEY_check_key, so:
283 if (EC_KEY_check_key(pkey))
289 // If vchPrivKey data is bad d2i_ECPrivateKey() can
290 // leave pkey in a state where calling EC_KEY_free()
291 // crashes. To avoid that, set pkey to NULL and
292 // leak the memory (a leak is better than a crash)
298 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
301 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
303 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
305 if (vchSecret.size() != 32)
306 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
307 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
309 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
310 if (!EC_KEY_regenerate_key(pkey,bn))
313 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
317 SetCompressedPubKey(fCompressed);
321 CSecret CKey::GetSecret(bool &fCompressed) const
325 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
326 int nBytes = BN_num_bytes(bn);
328 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
329 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
331 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
332 fCompressed = IsCompressed();
336 CSecret CKey::GetSecret() const
339 return GetSecret(fCompressed);
342 CPrivKey CKey::GetPrivKey() const
344 int nSize = i2d_ECPrivateKey(pkey, NULL);
346 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
347 CPrivKey vchPrivKey(nSize, 0);
348 unsigned char* pbegin = &vchPrivKey[0];
349 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
350 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
354 CPubKey CKey::GetPubKey() const
356 int nSize = i2o_ECPublicKey(pkey, NULL);
358 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
359 std::vector<unsigned char> vchPubKey(nSize, 0);
360 unsigned char* pbegin = &vchPubKey[0];
361 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
362 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
363 return CPubKey(vchPubKey);
366 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
369 ECDSA_SIG *sig = ECDSA_do_sign(hash.begin(), sizeof(hash), pkey);
372 const EC_GROUP *group = EC_KEY_get0_group(pkey);
374 BIGNUM* order = BN_new(), *halforder = BN_new();
375 EC_GROUP_get_order(group, order, nullptr);
376 BN_rshift1(halforder, order);
378 // Get internal R and S pointers
379 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
380 BIGNUM *current_r = BN_dup(ECDSA_SIG_get0_r(sig));
382 // enforce low S values, by negating the value (modulo the order) if above order/2.
383 if (BN_cmp(current_s, halforder) > 0) {
384 BIGNUM *updated_s = BN_new();
385 BN_copy(updated_s, current_s);
386 BN_sub(updated_s, order, updated_s);
387 ECDSA_SIG_set0(sig, current_r, updated_s);
393 unsigned int nSize = ECDSA_size(pkey);
394 vchSig.resize(nSize); // Make sure it is big enough
395 unsigned char *pos = &vchSig[0];
396 nSize = i2d_ECDSA_SIG(sig, &pos);
398 vchSig.resize(nSize); // Shrink to fit actual size
399 // Testing our new signature
400 if (ECDSA_verify(0, hash.begin(), sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
407 // create a compact signature (65 bytes), which allows reconstructing the used public key
408 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
409 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
410 // 0x1D = second key with even y, 0x1E = second key with odd y
411 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
414 ECDSA_SIG *sig = ECDSA_do_sign(hash.begin(), sizeof(hash), pkey);
417 const EC_GROUP *group = EC_KEY_get0_group(pkey);
418 BIGNUM* order = BN_new(), *halforder = BN_new();
419 EC_GROUP_get_order(group, order, nullptr);
420 BN_rshift1(halforder, order);
422 // Get internal R and S pointers
423 const BIGNUM *current_s = ECDSA_SIG_get0_s(sig);
424 BIGNUM *current_r = BN_dup(ECDSA_SIG_get0_r(sig));
426 // enforce low S values, by negating the value (modulo the order) if above order/2.
427 if (BN_cmp(current_s, halforder) > 0) {
428 BIGNUM *updated_s = BN_new();
429 BN_copy(updated_s, current_s);
430 BN_sub(updated_s, order, updated_s);
431 ECDSA_SIG_set0(sig, current_r, updated_s);
439 int nBitsR = BN_num_bits(ECDSA_SIG_get0_r(sig));
440 int nBitsS = BN_num_bits(ECDSA_SIG_get0_s(sig));
441 bool fCompressedPubKey = IsCompressed();
442 if (nBitsR <= 256 && nBitsS <= 256)
445 for (int8_t i=0; i<4; i++)
449 keyRec.SetCompressedPubKey(fCompressedPubKey);
450 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, hash.begin(), sizeof(hash), i, 1) == 1)
451 if (keyRec.GetPubKey() == this->GetPubKey())
461 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
464 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
465 BN_bn2bin(ECDSA_SIG_get0_r(sig),&vchSig[33-(nBitsR+7)/8]);
466 BN_bn2bin(ECDSA_SIG_get0_s(sig),&vchSig[65-(nBitsS+7)/8]);
474 // reconstruct public key from a compact signature
475 // This is only slightly more CPU intensive than just verifying it.
476 // If this function succeeds, the recovered public key is guaranteed to be valid
477 // (the signature is a valid signature of the given data for that key)
478 bool CPubKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
480 if (vchSig.size() != 65)
485 ECDSA_SIG *sig = ECDSA_SIG_new();
486 BIGNUM *sig_r = BN_new(), *sig_s = BN_new();
487 BN_bin2bn(&vchSig[1],32,sig_r);
488 BN_bin2bn(&vchSig[33],32,sig_s);
489 ECDSA_SIG_set0(sig, sig_r, sig_s);
490 bool fSuccessful = false;
491 EC_KEY* pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
495 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
499 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) != 1)
501 int nSize = i2o_ECPublicKey(pkey, NULL);
504 std::vector<unsigned char> vchPubKey(nSize, 0);
505 unsigned char* pbegin = &vchPubKey[0];
506 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
508 Set(vchPubKey.begin(), vchPubKey.end());
509 fSuccessful = IsValid();
519 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
521 if (vchSig.empty() || !IsValid())
524 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
525 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
534 uint8_t *norm_der = NULL;
535 const uint8_t* pbegin = &vbytes[0];
536 const uint8_t* sigptr = &vchSig[0];
538 // Trying to parse public key
539 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
541 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
542 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
544 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
547 // -1 = error, 0 = bad sig, 1 = good
548 ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
549 OPENSSL_free(norm_der);
552 ECDSA_SIG_free(norm_sig);
558 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
561 if (!key.SetCompactSignature(hash, vchSig))
571 if (!EC_KEY_check_key(pkey))
575 CSecret secret = GetSecret(fCompr);
577 key2.SetSecret(secret, fCompr);
579 return GetPubKey() == key2.GetPubKey();
589 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
591 err = "EC_KEY_new_by_curve_name failed.";
595 point = EC_POINT_new(group);
597 err = "EC_POINT_new failed.";
603 err = "BN_CTX_new failed.";
610 if (group) EC_GROUP_free(group);
611 if (point) EC_POINT_free(point);
612 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
615 bool CPoint::operator!=(const CPoint &a)
617 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
623 if (point) EC_POINT_free(point);
624 if (group) EC_GROUP_free(group);
625 if (ctx) BN_CTX_free(ctx);
628 // Initialize from octets stream
629 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
631 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
637 // Initialize from octets stream
638 bool CPoint::setPubKey(const CPubKey &key)
640 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
641 return setBytes(vchPubKey);
644 // Serialize to octets stream
645 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
647 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
648 vchBytes.resize(nSize);
649 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
655 // ECC multiplication by specified multiplier
656 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
658 BIGNUM* bnMul = bnMultiplier.get();
659 bool ok = EC_POINT_mul(group, point, NULL, point, bnMul, NULL);
660 if (!ok) printf("CPoint::ECMUL() : EC_POINT_mul failed");
666 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
668 BIGNUM* bnMul = bnMultiplier.get();
669 bool ok = EC_POINT_mul(group, point, bnMul, qPoint.point, BN_value_one(), NULL);
670 if (!ok) printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
677 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
679 EC_KEY *eckey = NULL;
680 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
682 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
685 // Use standard key generation function to get r and R values.
687 // r will be presented by private key;
688 // R is ECDSA public key which calculated as G*r
689 if (!EC_KEY_generate_key(eckey)) {
690 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
693 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
695 int nSize = i2o_ECPublicKey(eckey, NULL);
697 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
700 std::vector<unsigned char> vchPubKey(nSize, 0);
701 unsigned char* pbegin_R = &vchPubKey[0];
703 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
704 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
708 R = CPubKey(vchPubKey);
710 // OpenSSL BIGNUM representation of r value
711 CBigNum bnr(EC_KEY_get0_private_key(eckey));
715 if (!point.setPubKey(pubKeyL)) {
716 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
722 std::vector<unsigned char> vchLr;
723 if (!point.getBytes(vchLr)) {
724 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
727 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
729 bnHash.setuint160(Hash160(vchLr));
732 pointH.setPubKey(pubKeyH);
735 // Calculate P = Hash(L*r)*G + H
736 P.ECMULGEN(bnHash, pointH);
738 if (P.IsInfinity()) {
739 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
742 std::vector<unsigned char> vchResult;
743 P.getBytes(vchResult);
745 vchPubKeyVariant = CPubKey(vchResult);
748 std::string CMalleablePubKey::ToString() const
750 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
752 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
754 return EncodeBase58Check(vch);
757 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
759 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
765 std::vector<unsigned char> CMalleablePubKey::Raw() const
767 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
769 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
774 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
776 std::vector<unsigned char> vchTemp;
777 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
778 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
780 if (vchTemp.size() != 68)
783 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
789 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
791 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
797 void CMalleableKey::Reset()
803 void CMalleableKey::MakeNewKeys()
811 vchSecretL = keyL.GetSecret();
812 vchSecretH = keyH.GetSecret();
815 CMalleableKey::CMalleableKey()
820 CMalleableKey::CMalleableKey(const CMalleableKey &b)
822 SetSecrets(b.vchSecretL, b.vchSecretH);
825 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
830 CMalleableKey::~CMalleableKey()
834 bool CMalleableKey::IsNull() const
836 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
839 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
843 CKey keyL(pvchSecretL);
844 CKey keyH(pvchSecretH);
846 if (!keyL.IsValid() || !keyH.IsValid())
849 vchSecretL = pvchSecretL;
850 vchSecretH = pvchSecretH;
855 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
857 CKey L(vchSecretL), H(vchSecretH);
858 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
862 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
865 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
869 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
873 if (!vchPubKeyVariant.IsValid()) {
874 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
879 if (!point_R.setPubKey(R)) {
880 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
885 CPubKey vchPubKeyH = H.GetPubKey();
888 if (!point_H.setPubKey(vchPubKeyH)) {
889 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
894 if (!point_P.setPubKey(vchPubKeyVariant)) {
895 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
899 // Infinity points are senseless
900 if (point_P.IsInfinity()) {
901 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
906 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
910 std::vector<unsigned char> vchRl;
911 if (!point_R.getBytes(vchRl)) {
912 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
916 // Calculate Hash(R*l)
918 bnHash.setuint160(Hash160(vchRl));
921 // Calculate Ps = Hash(L*r)*G + H
922 point_Ps.ECMULGEN(bnHash, point_H);
924 // Infinity points are senseless
925 if (point_Ps.IsInfinity()) {
926 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
931 if (point_Ps != point_P) {
938 // Check ownership and restore private key
939 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
942 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
946 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
950 if (!vchPubKeyVariant.IsValid()) {
951 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
956 if (!point_R.setPubKey(R)) {
957 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
962 CPubKey vchPubKeyH = H.GetPubKey();
965 if (!point_H.setPubKey(vchPubKeyH)) {
966 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
971 if (!point_P.setPubKey(vchPubKeyVariant)) {
972 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
976 // Infinity points are senseless
977 if (point_P.IsInfinity()) {
978 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
983 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
987 std::vector<unsigned char> vchRl;
988 if (!point_R.getBytes(vchRl)) {
989 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
993 // Calculate Hash(R*l)
995 bnHash.setuint160(Hash160(vchRl));
998 // Calculate Ps = Hash(L*r)*G + H
999 point_Ps.ECMULGEN(bnHash, point_H);
1001 // Infinity points are senseless
1002 if (point_Ps.IsInfinity()) {
1003 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
1008 if (point_Ps != point_P) {
1012 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1014 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1016 // Calculate p = Hash(R*l) + h
1017 CBigNum bnp = bnHash + bnh;
1019 std::vector<unsigned char> vchp = bnp.getBytes();
1020 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1025 std::string CMalleableKey::ToString() const
1027 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1029 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1031 return EncodeBase58Check(vch);
1034 std::vector<unsigned char> CMalleableKey::Raw() const
1036 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1038 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1043 bool CMalleableKey::SetString(const std::string& strMutableKey)
1045 std::vector<unsigned char> vchTemp;
1046 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1047 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1049 if (vchTemp.size() != 66)
1051 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1057 // CMalleableKeyView
1059 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1061 SetString(strMalleableKey);
1064 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1066 if (b.vchSecretL.size() != 32)
1067 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1069 if (b.vchSecretH.size() != 32)
1070 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1072 vchSecretL = b.vchSecretL;
1074 CKey H(b.vchSecretH);
1075 vchPubKeyH = H.GetPubKey();
1078 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1080 vchSecretL = b.vchSecretL;
1081 vchPubKeyH = b.vchPubKeyH;
1084 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1086 vchSecretL = b.vchSecretL;
1088 CKey H(b.vchSecretH);
1089 vchPubKeyH = H.GetPubKey();
1094 CMalleableKeyView::~CMalleableKeyView()
1098 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1100 CKey keyL(vchSecretL);
1101 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1105 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1108 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1112 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1116 if (!vchPubKeyVariant.IsValid()) {
1117 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1122 if (!point_R.setPubKey(R)) {
1123 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1128 if (!point_H.setPubKey(vchPubKeyH)) {
1129 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1134 if (!point_P.setPubKey(vchPubKeyVariant)) {
1135 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1139 // Infinity points are senseless
1140 if (point_P.IsInfinity()) {
1141 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1146 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1150 std::vector<unsigned char> vchRl;
1151 if (!point_R.getBytes(vchRl)) {
1152 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1156 // Calculate Hash(R*l)
1158 bnHash.setuint160(Hash160(vchRl));
1161 // Calculate Ps = Hash(L*r)*G + H
1162 point_Ps.ECMULGEN(bnHash, point_H);
1164 // Infinity points are senseless
1165 if (point_Ps.IsInfinity()) {
1166 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1171 if (point_Ps != point_P) {
1178 std::string CMalleableKeyView::ToString() const
1180 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1182 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1184 return EncodeBase58Check(vch);
1187 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1189 std::vector<unsigned char> vchTemp;
1190 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1191 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1194 if (vchTemp.size() != 67)
1197 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1203 std::vector<unsigned char> CMalleableKeyView::Raw() const
1205 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1207 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1213 bool CMalleableKeyView::IsValid() const
1215 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();