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.
10 #include <openssl/ecdsa.h>
11 #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 CKeyID CPubKey::GetID() const
521 return CKeyID(Hash160(vbytes, vbytes + size()));
524 uint256 CPubKey::GetHash() const
526 return Hash(vbytes, vbytes + size());
529 bool CPubKey::Verify(const uint256 &hash, const std::vector<unsigned char>& vchSig) const
531 if (vchSig.empty() || !IsValid())
534 EC_KEY *pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
535 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
544 uint8_t *norm_der = NULL;
545 const uint8_t* pbegin = &vbytes[0];
546 const uint8_t* sigptr = &vchSig[0];
548 // Trying to parse public key
549 if (!o2i_ECPublicKey(&pkey, &pbegin, size()))
551 // New versions of OpenSSL are rejecting a non-canonical DER signatures, de/re-serialize first.
552 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
554 if ((derlen = i2d_ECDSA_SIG(norm_sig, &norm_der)) <= 0)
557 // -1 = error, 0 = bad sig, 1 = good
558 ret = ECDSA_verify(0, (const unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
559 OPENSSL_free(norm_der);
562 ECDSA_SIG_free(norm_sig);
568 bool CPubKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
571 if (!key.SetCompactSignature(hash, vchSig))
581 if (!EC_KEY_check_key(pkey))
585 CSecret secret = GetSecret(fCompr);
587 key2.SetSecret(secret, fCompr);
589 return GetPubKey() == key2.GetPubKey();
599 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
601 err = "EC_KEY_new_by_curve_name failed.";
605 point = EC_POINT_new(group);
607 err = "EC_POINT_new failed.";
613 err = "BN_CTX_new failed.";
620 if (group) EC_GROUP_free(group);
621 if (point) EC_POINT_free(point);
622 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
625 bool CPoint::operator!=(const CPoint &a)
627 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
633 if (point) EC_POINT_free(point);
634 if (group) EC_GROUP_free(group);
635 if (ctx) BN_CTX_free(ctx);
638 // Initialize from octets stream
639 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
641 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
647 // Initialize from octets stream
648 bool CPoint::setPubKey(const CPubKey &key)
650 std::vector<uint8_t> vchPubKey(key.begin(), key.end());
651 return setBytes(vchPubKey);
654 // Serialize to octets stream
655 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
657 size_t nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
658 vchBytes.resize(nSize);
659 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
665 // ECC multiplication by specified multiplier
666 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
668 BIGNUM* bnMul = bnMultiplier.get();
669 bool ok = EC_POINT_mul(group, point, NULL, point, bnMul, NULL);
670 if (!ok) printf("CPoint::ECMUL() : EC_POINT_mul failed");
676 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
678 BIGNUM* bnMul = bnMultiplier.get();
679 bool ok = EC_POINT_mul(group, point, bnMul, qPoint.point, BN_value_one(), NULL);
680 if (!ok) printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
687 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
689 EC_KEY *eckey = NULL;
690 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
692 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
695 // Use standard key generation function to get r and R values.
697 // r will be presented by private key;
698 // R is ECDSA public key which calculated as G*r
699 if (!EC_KEY_generate_key(eckey)) {
700 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
703 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
705 int nSize = i2o_ECPublicKey(eckey, NULL);
707 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
710 std::vector<unsigned char> vchPubKey(nSize, 0);
711 unsigned char* pbegin_R = &vchPubKey[0];
713 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
714 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
718 R = CPubKey(vchPubKey);
720 // OpenSSL BIGNUM representation of r value
721 CBigNum bnr(EC_KEY_get0_private_key(eckey));
725 if (!point.setPubKey(pubKeyL)) {
726 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
732 std::vector<unsigned char> vchLr;
733 if (!point.getBytes(vchLr)) {
734 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
737 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
739 bnHash.setuint160(Hash160(vchLr));
742 pointH.setPubKey(pubKeyH);
745 // Calculate P = Hash(L*r)*G + H
746 P.ECMULGEN(bnHash, pointH);
748 if (P.IsInfinity()) {
749 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
752 std::vector<unsigned char> vchResult;
753 P.getBytes(vchResult);
755 vchPubKeyVariant = CPubKey(vchResult);
758 std::string CMalleablePubKey::ToString() const
760 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
762 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
764 return EncodeBase58Check(vch);
767 bool CMalleablePubKey::setvch(const std::vector<unsigned char> &vchPubKeyPair)
769 CDataStream ssKey(vchPubKeyPair, SER_NETWORK, PROTOCOL_VERSION);
775 std::vector<unsigned char> CMalleablePubKey::Raw() const
777 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
779 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
784 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
786 std::vector<unsigned char> vchTemp;
787 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
788 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
790 if (vchTemp.size() != 68)
793 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
799 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
801 return pubKeyL == b.pubKeyL && pubKeyH == b.pubKeyH;
807 void CMalleableKey::Reset()
813 void CMalleableKey::MakeNewKeys()
821 vchSecretL = keyL.GetSecret();
822 vchSecretH = keyH.GetSecret();
825 CMalleableKey::CMalleableKey()
830 CMalleableKey::CMalleableKey(const CMalleableKey &b)
832 SetSecrets(b.vchSecretL, b.vchSecretH);
835 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
840 CMalleableKey::~CMalleableKey()
844 bool CMalleableKey::IsNull() const
846 return vchSecretL.size() != 32 || vchSecretH.size() != 32;
849 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
853 CKey keyL(pvchSecretL);
854 CKey keyH(pvchSecretH);
856 if (!keyL.IsValid() || !keyH.IsValid())
859 vchSecretL = pvchSecretL;
860 vchSecretH = pvchSecretH;
865 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
867 CKey L(vchSecretL), H(vchSecretH);
868 return CMalleablePubKey(L.GetPubKey(), H.GetPubKey());
872 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
875 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
879 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
883 if (!vchPubKeyVariant.IsValid()) {
884 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
889 if (!point_R.setPubKey(R)) {
890 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
895 CPubKey vchPubKeyH = H.GetPubKey();
898 if (!point_H.setPubKey(vchPubKeyH)) {
899 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
904 if (!point_P.setPubKey(vchPubKeyVariant)) {
905 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
909 // Infinity points are senseless
910 if (point_P.IsInfinity()) {
911 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
916 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
920 std::vector<unsigned char> vchRl;
921 if (!point_R.getBytes(vchRl)) {
922 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
926 // Calculate Hash(R*l)
928 bnHash.setuint160(Hash160(vchRl));
931 // Calculate Ps = Hash(L*r)*G + H
932 point_Ps.ECMULGEN(bnHash, point_H);
934 // Infinity points are senseless
935 if (point_Ps.IsInfinity()) {
936 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
941 if (point_Ps != point_P) {
948 // Check ownership and restore private key
949 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant) const
952 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
956 printf("CMalleableKey::CheckKeyVariant() : R is invalid");
960 if (!vchPubKeyVariant.IsValid()) {
961 printf("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
966 if (!point_R.setPubKey(R)) {
967 printf("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
972 CPubKey vchPubKeyH = H.GetPubKey();
975 if (!point_H.setPubKey(vchPubKeyH)) {
976 printf("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
981 if (!point_P.setPubKey(vchPubKeyVariant)) {
982 printf("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
986 // Infinity points are senseless
987 if (point_P.IsInfinity()) {
988 printf("CMalleableKey::CheckKeyVariant() : P is infinity");
993 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
997 std::vector<unsigned char> vchRl;
998 if (!point_R.getBytes(vchRl)) {
999 printf("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
1003 // Calculate Hash(R*l)
1005 bnHash.setuint160(Hash160(vchRl));
1008 // Calculate Ps = Hash(L*r)*G + H
1009 point_Ps.ECMULGEN(bnHash, point_H);
1011 // Infinity points are senseless
1012 if (point_Ps.IsInfinity()) {
1013 printf("CMalleableKey::CheckKeyVariant() : Ps is infinity");
1018 if (point_Ps != point_P) {
1022 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
1024 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
1026 // Calculate p = Hash(R*l) + h
1027 CBigNum bnp = bnHash + bnh;
1029 std::vector<unsigned char> vchp = bnp.getBytes();
1030 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()));
1035 std::string CMalleableKey::ToString() const
1037 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1039 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1041 return EncodeBase58Check(vch);
1044 std::vector<unsigned char> CMalleableKey::Raw() const
1046 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1048 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1053 bool CMalleableKey::SetString(const std::string& strMutableKey)
1055 std::vector<unsigned char> vchTemp;
1056 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1057 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
1059 if (vchTemp.size() != 66)
1061 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1067 // CMalleableKeyView
1069 CMalleableKeyView::CMalleableKeyView(const std::string &strMalleableKey)
1071 SetString(strMalleableKey);
1074 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
1076 if (b.vchSecretL.size() != 32)
1077 throw key_error("CMalleableKeyView::CMalleableKeyView() : L size must be 32 bytes");
1079 if (b.vchSecretH.size() != 32)
1080 throw key_error("CMalleableKeyView::CMalleableKeyView() : H size must be 32 bytes");
1082 vchSecretL = b.vchSecretL;
1084 CKey H(b.vchSecretH);
1085 vchPubKeyH = H.GetPubKey();
1088 CMalleableKeyView::CMalleableKeyView(const CMalleableKeyView &b)
1090 vchSecretL = b.vchSecretL;
1091 vchPubKeyH = b.vchPubKeyH;
1094 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1096 vchSecretL = b.vchSecretL;
1098 CKey H(b.vchSecretH);
1099 vchPubKeyH = H.GetPubKey();
1104 CMalleableKeyView::~CMalleableKeyView()
1108 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1110 CKey keyL(vchSecretL);
1111 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1115 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant) const
1118 throw key_error("CMalleableKeyView::CheckKeyVariant() : Attempting to run on invalid view object.");
1122 printf("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1126 if (!vchPubKeyVariant.IsValid()) {
1127 printf("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1132 if (!point_R.setPubKey(R)) {
1133 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1138 if (!point_H.setPubKey(vchPubKeyH)) {
1139 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1144 if (!point_P.setPubKey(vchPubKeyVariant)) {
1145 printf("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1149 // Infinity points are senseless
1150 if (point_P.IsInfinity()) {
1151 printf("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1156 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1160 std::vector<unsigned char> vchRl;
1161 if (!point_R.getBytes(vchRl)) {
1162 printf("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1166 // Calculate Hash(R*l)
1168 bnHash.setuint160(Hash160(vchRl));
1171 // Calculate Ps = Hash(L*r)*G + H
1172 point_Ps.ECMULGEN(bnHash, point_H);
1174 // Infinity points are senseless
1175 if (point_Ps.IsInfinity()) {
1176 printf("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1181 if (point_Ps != point_P) {
1188 bool CMalleableKeyView::operator <(const CMalleableKeyView &kv) const { return vchPubKeyH.GetID() < kv.vchPubKeyH.GetID(); }
1190 std::string CMalleableKeyView::ToString() const
1192 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1194 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1196 return EncodeBase58Check(vch);
1199 bool CMalleableKeyView::SetString(const std::string& strMutableKey)
1201 std::vector<unsigned char> vchTemp;
1202 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
1203 throw key_error("CMalleableKeyView::SetString() : Provided key data seems corrupted.");
1206 if (vchTemp.size() != 67)
1209 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
1215 std::vector<unsigned char> CMalleableKeyView::Raw() const
1217 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
1219 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
1225 bool CMalleableKeyView::IsValid() const
1227 return vchSecretL.size() == 32 && GetMalleablePubKey().IsValid();
1230 CScriptID::CScriptID() : uint160(0) { }
1232 CScriptID::CScriptID(const uint160 &in) : uint160(in) { }
1234 CKeyID::CKeyID() : uint160(0) { }
1236 CKeyID::CKeyID(const uint160 &in) : uint160(in) { }