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/obj_mac.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; }
82 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
83 field = BN_CTX_get(ctx);
84 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
85 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
86 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
87 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
90 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
91 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
92 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
94 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
95 n = EC_GROUP_get_degree(group);
97 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
98 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
99 zero = BN_CTX_get(ctx);
100 if (!BN_zero(zero)) { ret=-1; goto err; }
101 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
102 rr = BN_CTX_get(ctx);
103 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
104 sor = BN_CTX_get(ctx);
105 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
106 eor = BN_CTX_get(ctx);
107 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
108 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
109 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
118 if (R != NULL) EC_POINT_free(R);
119 if (O != NULL) EC_POINT_free(O);
120 if (Q != NULL) EC_POINT_free(Q);
124 int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) {
125 while (c1len > c2len) {
131 while (c2len > c1len) {
149 // Order of secp256k1's generator minus 1.
150 const unsigned char vchMaxModOrder[32] = {
151 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
152 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE,
153 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,
154 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40
157 // Half of the order of secp256k1's generator minus 1.
158 const unsigned char vchMaxModHalfOrder[32] = {
159 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
160 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
161 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D,
162 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0
165 const unsigned char *vchZero = NULL;
169 void CKey::SetCompressedPubKey()
171 EC_KEY_set_conv_form(pkey, POINT_CONVERSION_COMPRESSED);
172 fCompressedPubKey = true;
177 fCompressedPubKey = false;
180 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
182 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
192 CKey::CKey(const CKey& b)
194 pkey = EC_KEY_dup(b.pkey);
196 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
198 fCompressedPubKey = b.fCompressedPubKey;
201 CKey& CKey::operator=(const CKey& b)
203 if (!EC_KEY_copy(pkey, b.pkey))
204 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
206 fCompressedPubKey = b.fCompressedPubKey;
215 bool CKey::IsNull() const
220 bool CKey::IsCompressed() const
222 return fCompressedPubKey;
225 bool CKey::CheckSignatureElement(const unsigned char *vch, int len, bool half) {
226 return CompareBigEndian(vch, len, vchZero, 0) > 0 &&
227 CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0;
230 bool CKey::ReserealizeSignature(std::vector<unsigned char>& vchSig)
235 unsigned char *pos = &vchSig[0];
236 ECDSA_SIG *sig = d2i_ECDSA_SIG(NULL, (const unsigned char **)&pos, vchSig.size());
241 int nSize = i2d_ECDSA_SIG(sig, NULL);
243 vchSig.resize(nSize); // grow or shrink as needed
246 i2d_ECDSA_SIG(sig, &pos);
256 void CKey::MakeNewKey(bool fCompressed)
258 if (!EC_KEY_generate_key(pkey))
259 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
261 SetCompressedPubKey();
265 bool CKey::SetPrivKey(const CPrivKey& vchPrivKey)
267 const unsigned char* pbegin = &vchPrivKey[0];
268 if (d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
270 // In testing, d2i_ECPrivateKey can return true
271 // but fill in pkey with a key that fails
272 // EC_KEY_check_key, so:
273 if (EC_KEY_check_key(pkey))
279 // If vchPrivKey data is bad d2i_ECPrivateKey() can
280 // leave pkey in a state where calling EC_KEY_free()
281 // crashes. To avoid that, set pkey to NULL and
282 // leak the memory (a leak is better than a crash)
288 bool CKey::SetSecret(const CSecret& vchSecret, bool fCompressed)
291 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
293 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
294 if (vchSecret.size() != 32)
295 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
296 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
298 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
299 if (!EC_KEY_regenerate_key(pkey,bn))
302 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
306 if (fCompressed || fCompressedPubKey)
307 SetCompressedPubKey();
311 CSecret CKey::GetSecret(bool &fCompressed) const
315 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
316 int nBytes = BN_num_bytes(bn);
318 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
319 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
321 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
322 fCompressed = fCompressedPubKey;
326 CPrivKey CKey::GetPrivKey() const
328 int nSize = i2d_ECPrivateKey(pkey, NULL);
330 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
331 CPrivKey vchPrivKey(nSize, 0);
332 unsigned char* pbegin = &vchPrivKey[0];
333 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
334 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
338 bool CKey::SetPubKey(const CPubKey& vchPubKey)
340 const unsigned char* pbegin = &vchPubKey.vchPubKey[0];
341 if (o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.vchPubKey.size()))
344 if (vchPubKey.vchPubKey.size() == 33)
345 SetCompressedPubKey();
353 CPubKey CKey::GetPubKey() const
355 int nSize = i2o_ECPublicKey(pkey, NULL);
357 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
358 std::vector<unsigned char> vchPubKey(nSize, 0);
359 unsigned char* pbegin = &vchPubKey[0];
360 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
361 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
362 return CPubKey(vchPubKey);
365 bool CKey::Sign(uint256 hash, std::vector<unsigned char>& vchSig)
368 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
371 const EC_GROUP *group = EC_KEY_get0_group(pkey);
372 CBigNum order, halforder;
373 EC_GROUP_get_order(group, &order, NULL);
374 BN_rshift1(&halforder, &order);
375 // enforce low S values, by negating the value (modulo the order) if above order/2.
376 if (BN_cmp(sig->s, &halforder) > 0) {
377 BN_sub(sig->s, &order, sig->s);
379 unsigned int nSize = ECDSA_size(pkey);
380 vchSig.resize(nSize); // Make sure it is big enough
381 unsigned char *pos = &vchSig[0];
382 nSize = i2d_ECDSA_SIG(sig, &pos);
384 vchSig.resize(nSize); // Shrink to fit actual size
385 // Testing our new signature
386 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) {
393 // create a compact signature (65 bytes), which allows reconstructing the used public key
394 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
395 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
396 // 0x1D = second key with even y, 0x1E = second key with odd y
397 bool CKey::SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
400 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
403 const EC_GROUP *group = EC_KEY_get0_group(pkey);
404 CBigNum order, halforder;
405 EC_GROUP_get_order(group, &order, NULL);
406 BN_rshift1(&halforder, &order);
407 // enforce low S values, by negating the value (modulo the order) if above order/2.
408 if (BN_cmp(sig->s, &halforder) > 0) {
409 BN_sub(sig->s, &order, sig->s);
413 int nBitsR = BN_num_bits(sig->r);
414 int nBitsS = BN_num_bits(sig->s);
415 if (nBitsR <= 256 && nBitsS <= 256)
418 for (int8_t i=0; i<4; i++)
422 if (fCompressedPubKey)
423 keyRec.SetCompressedPubKey();
424 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
425 if (keyRec.GetPubKey() == this->GetPubKey())
435 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
438 vchSig[0] = nRecId+27+(fCompressedPubKey ? 4 : 0);
439 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
440 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
447 // reconstruct public key from a compact signature
448 // This is only slightly more CPU intensive than just verifying it.
449 // If this function succeeds, the recovered public key is guaranteed to be valid
450 // (the signature is a valid signature of the given data for that key)
451 bool CKey::SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
453 if (vchSig.size() != 65)
458 ECDSA_SIG *sig = ECDSA_SIG_new();
459 BN_bin2bn(&vchSig[1],32,sig->r);
460 BN_bin2bn(&vchSig[33],32,sig->s);
463 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
466 SetCompressedPubKey();
469 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), nV - 27, 0) == 1)
479 bool CKey::Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
484 // New versions of OpenSSL will reject non-canonical DER signatures. de/re-serialize first.
485 unsigned char *norm_der = NULL;
486 ECDSA_SIG *norm_sig = ECDSA_SIG_new();
487 const unsigned char* sigptr = &vchSig[0];
489 if (d2i_ECDSA_SIG(&norm_sig, &sigptr, vchSig.size()) == NULL)
491 /* As of OpenSSL 1.0.0p d2i_ECDSA_SIG frees and nulls the pointer on
492 * error. But OpenSSL's own use of this function redundantly frees the
493 * result. As ECDSA_SIG_free(NULL) is a no-op, and in the absence of a
494 * clear contract for the function behaving the same way is more
497 ECDSA_SIG_free(norm_sig);
500 int derlen = i2d_ECDSA_SIG(norm_sig, &norm_der);
501 ECDSA_SIG_free(norm_sig);
505 // -1 = error, 0 = bad sig, 1 = good
506 bool ret = ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), norm_der, derlen, pkey) == 1;
507 OPENSSL_free(norm_der);
511 bool CKey::VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
514 if (!key.SetCompactSignature(hash, vchSig))
516 if (GetPubKey() != key.GetPubKey())
527 if (!EC_KEY_check_key(pkey))
531 CSecret secret = GetSecret(fCompr);
533 key2.SetSecret(secret, fCompr);
534 return GetPubKey() == key2.GetPubKey();
544 group = EC_GROUP_new_by_curve_name(NID_secp256k1);
546 err = "EC_KEY_new_by_curve_name failed.";
550 point = EC_POINT_new(group);
552 err = "EC_POINT_new failed.";
558 err = "BN_CTX_new failed.";
565 if (group) EC_GROUP_free(group);
566 if (point) EC_POINT_free(point);
567 throw std::runtime_error(std::string("CPoint::CPoint() : - ") + err);
570 bool CPoint::operator!=(const CPoint &a)
572 if (EC_POINT_cmp(group, point, a.point, ctx) != 0)
578 if (point) EC_POINT_free(point);
579 if (group) EC_GROUP_free(group);
580 if (ctx) BN_CTX_free(ctx);
583 // Initialize from octets stream
584 bool CPoint::setBytes(const std::vector<unsigned char> &vchBytes)
586 if (!EC_POINT_oct2point(group, point, &vchBytes[0], vchBytes.size(), ctx)) {
592 // Serialize to octets stream
593 bool CPoint::getBytes(std::vector<unsigned char> &vchBytes)
595 unsigned int nSize = EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, NULL, 0, ctx);
596 vchBytes.resize(nSize);
597 if (!(nSize == EC_POINT_point2oct(group, point, POINT_CONVERSION_COMPRESSED, &vchBytes[0], nSize, ctx))) {
603 // ECC multiplication by specified multiplier
604 bool CPoint::ECMUL(const CBigNum &bnMultiplier)
606 if (!EC_POINT_mul(group, point, NULL, point, &bnMultiplier, NULL)) {
607 printf("CPoint::ECMUL() : EC_POINT_mul failed");
615 bool CPoint::ECMULGEN(const CBigNum &bnMultiplier, const CPoint &qPoint)
617 if (!EC_POINT_mul(group, point, &bnMultiplier, qPoint.point, BN_value_one(), NULL)) {
618 printf("CPoint::ECMULGEN() : EC_POINT_mul failed.");
627 void CMalleablePubKey::GetVariant(CPubKey &R, CPubKey &vchPubKeyVariant)
629 EC_KEY *eckey = NULL;
630 eckey = EC_KEY_new_by_curve_name(NID_secp256k1);
632 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_new_by_curve_name failed");
635 // Use standard key generation function to get r and R values.
637 // r will be presented by private key;
638 // R is ECDSA public key which calculated as G*r
639 if (!EC_KEY_generate_key(eckey)) {
640 throw key_error("CMalleablePubKey::GetVariant() : EC_KEY_generate_key failed");
643 EC_KEY_set_conv_form(eckey, POINT_CONVERSION_COMPRESSED);
645 int nSize = i2o_ECPublicKey(eckey, NULL);
647 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey failed");
650 std::vector<unsigned char> vchPubKey(nSize, 0);
651 unsigned char* pbegin_R = &vchPubKey[0];
653 if (i2o_ECPublicKey(eckey, &pbegin_R) != nSize) {
654 throw key_error("CMalleablePubKey::GetVariant() : i2o_ECPublicKey returned unexpected size");
658 R = CPubKey(vchPubKey);
660 // OpenSSL BIGNUM representation of r value
662 bnr = *(CBigNum*) EC_KEY_get0_private_key(eckey);
666 if (!point.setBytes(pubKeyL.Raw())) {
667 throw key_error("CMalleablePubKey::GetVariant() : Unable to decode L value");
673 std::vector<unsigned char> vchLr;
674 if (!point.getBytes(vchLr)) {
675 throw key_error("CMalleablePubKey::GetVariant() : Unable to convert Lr value");
678 // Calculate Hash(L*r) and then get a BIGNUM representation of hash value.
680 bnHash.setuint160(Hash160(vchLr));
683 pointH.setBytes(pubKeyH.Raw());
686 // Calculate P = Hash(L*r)*G + H
687 P.ECMULGEN(bnHash, pointH);
689 if (P.IsInfinity()) {
690 throw key_error("CMalleablePubKey::GetVariant() : P is infinity");
693 std::vector<unsigned char> vchResult;
694 P.getBytes(vchResult);
696 vchPubKeyVariant = CPubKey(vchResult);
699 std::string CMalleablePubKey::ToString()
701 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
703 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
705 return EncodeBase58Check(vch);
708 bool CMalleablePubKey::SetString(const std::string& strMalleablePubKey)
710 std::vector<unsigned char> vchTemp;
711 if (!DecodeBase58Check(strMalleablePubKey, vchTemp)) {
712 throw key_error("CMalleablePubKey::SetString() : Provided key data seems corrupted.");
715 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
721 bool CMalleablePubKey::operator==(const CMalleablePubKey &b)
723 return (nVersion == b.nVersion &&
724 pubKeyL == b.pubKeyL &&
725 pubKeyH == b.pubKeyH);
731 void CMalleableKey::Reset()
739 void CMalleableKey::MakeNewKeys()
742 bool fCompressed = true;
747 vchSecretL = L.GetSecret(fCompressed);
748 vchSecretH = H.GetSecret(fCompressed);
750 nVersion = CURRENT_VERSION;
753 CMalleableKey::CMalleableKey()
758 CMalleableKey::CMalleableKey(const CMalleableKey &b)
760 SetSecrets(b.vchSecretL, b.vchSecretH);
763 CMalleableKey::CMalleableKey(const CSecret &L, const CSecret &H)
768 CMalleableKey& CMalleableKey::operator=(const CMalleableKey &b)
770 SetSecrets(b.vchSecretL, b.vchSecretH);
775 CMalleableKey::~CMalleableKey()
779 bool CMalleableKey::IsNull() const
781 return nVersion != CURRENT_VERSION;
784 bool CMalleableKey::SetSecrets(const CSecret &pvchSecretL, const CSecret &pvchSecretH)
789 if (!L.SetSecret(pvchSecretL, true) || !H.SetSecret(pvchSecretH, true))
795 vchSecretL = pvchSecretL;
796 vchSecretH = pvchSecretH;
797 nVersion = CURRENT_VERSION;
802 void CMalleableKey::GetSecrets(CSecret &pvchSecretL, CSecret &pvchSecretH) const
804 pvchSecretL = vchSecretL;
805 pvchSecretH = vchSecretH;
808 CMalleablePubKey CMalleableKey::GetMalleablePubKey() const
811 L.SetSecret(vchSecretL, true);
812 H.SetSecret(vchSecretH, true);
814 std::vector<unsigned char> vchPubKeyL = L.GetPubKey().Raw();
815 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
817 return CMalleablePubKey(vchPubKeyL, vchPubKeyH);
821 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant)
824 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
828 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
831 if (!vchPubKeyVariant.IsValid()) {
832 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
836 if (!point_R.setBytes(R.Raw())) {
837 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
841 H.SetSecret(vchSecretH, true);
842 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
845 if (!point_H.setBytes(vchPubKeyH)) {
846 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
850 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
851 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
854 // Infinity points are senseless
855 if (point_P.IsInfinity()) {
856 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
860 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
864 std::vector<unsigned char> vchRl;
865 if (!point_R.getBytes(vchRl)) {
866 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
869 // Calculate Hash(R*l)
871 bnHash.setuint160(Hash160(vchRl));
874 // Calculate Ps = Hash(L*r)*G + H
875 point_Ps.ECMULGEN(bnHash, point_H);
877 // Infinity points are senseless
878 if (point_Ps.IsInfinity()) {
879 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
883 if (point_Ps != point_P) {
890 // Check ownership and restore private key
891 bool CMalleableKey::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant, CKey &privKeyVariant)
894 throw key_error("CMalleableKey::CheckKeyVariant() : Attempting to run on NULL key object.");
898 throw key_error("CMalleableKey::CheckKeyVariant() : R is invalid");
901 if (!vchPubKeyVariant.IsValid()) {
902 throw key_error("CMalleableKey::CheckKeyVariant() : public key variant is invalid");
906 if (!point_R.setBytes(R.Raw())) {
907 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode R value");
911 H.SetSecret(vchSecretH, true);
912 std::vector<unsigned char> vchPubKeyH = H.GetPubKey().Raw();
915 if (!point_H.setBytes(vchPubKeyH)) {
916 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode H value");
920 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
921 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to decode P value");
924 // Infinity points are senseless
925 if (point_P.IsInfinity()) {
926 throw key_error("CMalleableKey::CheckKeyVariant() : P is infinity");
930 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
934 std::vector<unsigned char> vchRl;
935 if (!point_R.getBytes(vchRl)) {
936 throw key_error("CMalleableKey::CheckKeyVariant() : Unable to convert Rl value");
939 // Calculate Hash(R*l)
941 bnHash.setuint160(Hash160(vchRl));
944 // Calculate Ps = Hash(L*r)*G + H
945 point_Ps.ECMULGEN(bnHash, point_H);
947 // Infinity points are senseless
948 if (point_Ps.IsInfinity()) {
949 throw key_error("CMalleableKey::CheckKeyVariant() : Ps is infinity");
953 if (point_Ps != point_P) {
957 // OpenSSL BIGNUM representation of the second private key from (l, h) pair
959 bnh.setBytes(std::vector<unsigned char>(vchSecretH.begin(), vchSecretH.end()));
961 // Calculate p = Hash(R*l) + h
962 CBigNum bnp = bnHash + bnh;
964 std::vector<unsigned char> vchp = bnp.getBytes();
965 privKeyVariant.SetSecret(CSecret(vchp.begin(), vchp.end()), true);
970 std::string CMalleableKey::ToString()
972 CDataStream ssKey(SER_NETWORK, PROTOCOL_VERSION);
974 std::vector<unsigned char> vch(ssKey.begin(), ssKey.end());
976 return EncodeBase58Check(vch);
979 bool CMalleableKey::SetString(const std::string& strMutableKey)
981 std::vector<unsigned char> vchTemp;
982 if (!DecodeBase58Check(strMutableKey, vchTemp)) {
983 throw key_error("CMalleableKey::SetString() : Provided key data seems corrupted.");
986 CDataStream ssKey(vchTemp, SER_NETWORK, PROTOCOL_VERSION);
994 CMalleableKeyView::CMalleableKeyView(const CMalleableKey &b)
996 assert(b.nVersion == CURRENT_VERSION);
997 vchSecretL = b.vchSecretL;
1000 H.SetSecret(b.vchSecretH, true);
1001 vchPubKeyH = H.GetPubKey().Raw();
1004 CMalleableKeyView::CMalleableKeyView(const CSecret &L, const CPubKey &pvchPubKeyH)
1007 vchPubKeyH = pvchPubKeyH.Raw();
1010 CMalleableKeyView& CMalleableKeyView::operator=(const CMalleableKey &b)
1012 assert(b.nVersion == CURRENT_VERSION);
1013 vchSecretL = b.vchSecretL;
1016 H.SetSecret(b.vchSecretH, true);
1017 vchPubKeyH = H.GetPubKey().Raw();
1022 CMalleableKeyView::~CMalleableKeyView()
1026 CMalleablePubKey CMalleableKeyView::GetMalleablePubKey() const
1029 keyL.SetSecret(vchSecretL, true);
1030 return CMalleablePubKey(keyL.GetPubKey(), vchPubKeyH);
1034 bool CMalleableKeyView::CheckKeyVariant(const CPubKey &R, const CPubKey &vchPubKeyVariant)
1037 throw key_error("CMalleableKeyView::CheckKeyVariant() : R is invalid");
1040 if (!vchPubKeyVariant.IsValid()) {
1041 throw key_error("CMalleableKeyView::CheckKeyVariant() : public key variant is invalid");
1045 if (!point_R.setBytes(R.Raw())) {
1046 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode R value");
1050 if (!point_H.setBytes(vchPubKeyH)) {
1051 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode H value");
1055 if (!point_P.setBytes(vchPubKeyVariant.Raw())) {
1056 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to decode P value");
1059 // Infinity points are senseless
1060 if (point_P.IsInfinity()) {
1061 throw key_error("CMalleableKeyView::CheckKeyVariant() : P is infinity");
1065 bnl.setBytes(std::vector<unsigned char>(vchSecretL.begin(), vchSecretL.end()));
1069 std::vector<unsigned char> vchRl;
1070 if (!point_R.getBytes(vchRl)) {
1071 throw key_error("CMalleableKeyView::CheckKeyVariant() : Unable to convert Rl value");
1074 // Calculate Hash(R*l)
1076 bnHash.setuint160(Hash160(vchRl));
1079 // Calculate Ps = Hash(L*r)*G + H
1080 point_Ps.ECMULGEN(bnHash, point_H);
1082 // Infinity points are senseless
1083 if (point_Ps.IsInfinity()) {
1084 throw key_error("CMalleableKeyView::CheckKeyVariant() : Ps is infinity");
1088 if (point_Ps != point_P) {