-
+ 6B2389129DEC411D013D754EAEBC169A23F60B2169DC41CCED21248A603CED46DFDC64E016C082A154AF87784049333BE75C91FB08265306A3BDC2BC0AF2E6C5
bitcoin/src/key.h
(0 . 0)(1 . 406)
8569 // Copyright (c) 2009-2010 Satoshi Nakamoto
8570 // Copyright (c) 2009-2012 The Bitcoin developers
8571 // Distributed under the MIT/X11 software license, see the accompanying
8572 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
8573 #ifndef BITCOIN_KEY_H
8574 #define BITCOIN_KEY_H
8575
8576 #include <stdexcept>
8577 #include <vector>
8578
8579 #include <openssl/ec.h>
8580 #include <openssl/ecdsa.h>
8581 #include <openssl/obj_mac.h>
8582
8583 #include "serialize.h"
8584 #include "uint256.h"
8585 #include "base58.h"
8586
8587 // secp160k1
8588 // const unsigned int PRIVATE_KEY_SIZE = 192;
8589 // const unsigned int PUBLIC_KEY_SIZE = 41;
8590 // const unsigned int SIGNATURE_SIZE = 48;
8591 //
8592 // secp192k1
8593 // const unsigned int PRIVATE_KEY_SIZE = 222;
8594 // const unsigned int PUBLIC_KEY_SIZE = 49;
8595 // const unsigned int SIGNATURE_SIZE = 57;
8596 //
8597 // secp224k1
8598 // const unsigned int PRIVATE_KEY_SIZE = 250;
8599 // const unsigned int PUBLIC_KEY_SIZE = 57;
8600 // const unsigned int SIGNATURE_SIZE = 66;
8601 //
8602 // secp256k1:
8603 // const unsigned int PRIVATE_KEY_SIZE = 279;
8604 // const unsigned int PUBLIC_KEY_SIZE = 65;
8605 // const unsigned int SIGNATURE_SIZE = 72;
8606 //
8607 // see www.keylength.com
8608 // script supports up to 75 for single byte push
8609
8610 // Generate a private key from just the secret parameter
8611 int static inline EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key)
8612 {
8613 int ok = 0;
8614 BN_CTX *ctx = NULL;
8615 EC_POINT *pub_key = NULL;
8616
8617 if (!eckey) return 0;
8618
8619 const EC_GROUP *group = EC_KEY_get0_group(eckey);
8620
8621 if ((ctx = BN_CTX_new()) == NULL)
8622 goto err;
8623
8624 pub_key = EC_POINT_new(group);
8625
8626 if (pub_key == NULL)
8627 goto err;
8628
8629 if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx))
8630 goto err;
8631
8632 EC_KEY_set_private_key(eckey,priv_key);
8633 EC_KEY_set_public_key(eckey,pub_key);
8634
8635 ok = 1;
8636
8637 err:
8638
8639 if (pub_key)
8640 EC_POINT_free(pub_key);
8641 if (ctx != NULL)
8642 BN_CTX_free(ctx);
8643
8644 return(ok);
8645 }
8646
8647 // Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields
8648 // recid selects which key is recovered
8649 // if check is nonzero, additional checks are performed
8650 int static inline ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check)
8651 {
8652 if (!eckey) return 0;
8653
8654 int ret = 0;
8655 BN_CTX *ctx = NULL;
8656
8657 BIGNUM *x = NULL;
8658 BIGNUM *e = NULL;
8659 BIGNUM *order = NULL;
8660 BIGNUM *sor = NULL;
8661 BIGNUM *eor = NULL;
8662 BIGNUM *field = NULL;
8663 EC_POINT *R = NULL;
8664 EC_POINT *O = NULL;
8665 EC_POINT *Q = NULL;
8666 BIGNUM *rr = NULL;
8667 BIGNUM *zero = NULL;
8668 int n = 0;
8669 int i = recid / 2;
8670
8671 const EC_GROUP *group = EC_KEY_get0_group(eckey);
8672 if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; }
8673 BN_CTX_start(ctx);
8674 order = BN_CTX_get(ctx);
8675 if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; }
8676 x = BN_CTX_get(ctx);
8677 if (!BN_copy(x, order)) { ret=-1; goto err; }
8678 if (!BN_mul_word(x, i)) { ret=-1; goto err; }
8679 if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; }
8680 field = BN_CTX_get(ctx);
8681 if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; }
8682 if (BN_cmp(x, field) >= 0) { ret=0; goto err; }
8683 if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
8684 if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; }
8685 if (check)
8686 {
8687 if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
8688 if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; }
8689 if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; }
8690 }
8691 if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; }
8692 n = EC_GROUP_get_degree(group);
8693 e = BN_CTX_get(ctx);
8694 if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; }
8695 if (8*msglen > n) BN_rshift(e, e, 8-(n & 7));
8696 zero = BN_CTX_get(ctx);
8697 if (!BN_zero(zero)) { ret=-1; goto err; }
8698 if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; }
8699 rr = BN_CTX_get(ctx);
8700 if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; }
8701 sor = BN_CTX_get(ctx);
8702 if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; }
8703 eor = BN_CTX_get(ctx);
8704 if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; }
8705 if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; }
8706 if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; }
8707
8708 ret = 1;
8709
8710 err:
8711 if (ctx) {
8712 BN_CTX_end(ctx);
8713 BN_CTX_free(ctx);
8714 }
8715 if (R != NULL) EC_POINT_free(R);
8716 if (O != NULL) EC_POINT_free(O);
8717 if (Q != NULL) EC_POINT_free(Q);
8718 return ret;
8719 }
8720
8721 class key_error : public std::runtime_error
8722 {
8723 public:
8724 explicit key_error(const std::string& str) : std::runtime_error(str) {}
8725 };
8726
8727
8728 // secure_allocator is defined in serialize.h
8729 // CPrivKey is a serialized private key, with all parameters included (279 bytes)
8730 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CPrivKey;
8731 // CSecret is a serialization of just the secret parameter (32 bytes)
8732 typedef std::vector<unsigned char, secure_allocator<unsigned char> > CSecret;
8733
8734 class CKey
8735 {
8736 protected:
8737 EC_KEY* pkey;
8738 bool fSet;
8739
8740 public:
8741 CKey()
8742 {
8743 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
8744 if (pkey == NULL)
8745 throw key_error("CKey::CKey() : EC_KEY_new_by_curve_name failed");
8746 fSet = false;
8747 }
8748
8749 CKey(const CKey& b)
8750 {
8751 pkey = EC_KEY_dup(b.pkey);
8752 if (pkey == NULL)
8753 throw key_error("CKey::CKey(const CKey&) : EC_KEY_dup failed");
8754 fSet = b.fSet;
8755 }
8756
8757 CKey& operator=(const CKey& b)
8758 {
8759 if (!EC_KEY_copy(pkey, b.pkey))
8760 throw key_error("CKey::operator=(const CKey&) : EC_KEY_copy failed");
8761 fSet = b.fSet;
8762 return (*this);
8763 }
8764
8765 ~CKey()
8766 {
8767 EC_KEY_free(pkey);
8768 }
8769
8770 bool IsNull() const
8771 {
8772 return !fSet;
8773 }
8774
8775 void MakeNewKey()
8776 {
8777 if (!EC_KEY_generate_key(pkey))
8778 throw key_error("CKey::MakeNewKey() : EC_KEY_generate_key failed");
8779 fSet = true;
8780 }
8781
8782 bool SetPrivKey(const CPrivKey& vchPrivKey)
8783 {
8784 const unsigned char* pbegin = &vchPrivKey[0];
8785 if (!d2i_ECPrivateKey(&pkey, &pbegin, vchPrivKey.size()))
8786 return false;
8787 fSet = true;
8788 return true;
8789 }
8790
8791 bool SetSecret(const CSecret& vchSecret)
8792 {
8793 EC_KEY_free(pkey);
8794 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
8795 if (pkey == NULL)
8796 throw key_error("CKey::SetSecret() : EC_KEY_new_by_curve_name failed");
8797 if (vchSecret.size() != 32)
8798 throw key_error("CKey::SetSecret() : secret must be 32 bytes");
8799 BIGNUM *bn = BN_bin2bn(&vchSecret[0],32,BN_new());
8800 if (bn == NULL)
8801 throw key_error("CKey::SetSecret() : BN_bin2bn failed");
8802 if (!EC_KEY_regenerate_key(pkey,bn))
8803 {
8804 BN_clear_free(bn);
8805 throw key_error("CKey::SetSecret() : EC_KEY_regenerate_key failed");
8806 }
8807 BN_clear_free(bn);
8808 fSet = true;
8809 return true;
8810 }
8811
8812 CSecret GetSecret() const
8813 {
8814 CSecret vchRet;
8815 vchRet.resize(32);
8816 const BIGNUM *bn = EC_KEY_get0_private_key(pkey);
8817 int nBytes = BN_num_bytes(bn);
8818 if (bn == NULL)
8819 throw key_error("CKey::GetSecret() : EC_KEY_get0_private_key failed");
8820 int n=BN_bn2bin(bn,&vchRet[32 - nBytes]);
8821 if (n != nBytes)
8822 throw key_error("CKey::GetSecret(): BN_bn2bin failed");
8823 return vchRet;
8824 }
8825
8826 CPrivKey GetPrivKey() const
8827 {
8828 unsigned int nSize = i2d_ECPrivateKey(pkey, NULL);
8829 if (!nSize)
8830 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey failed");
8831 CPrivKey vchPrivKey(nSize, 0);
8832 unsigned char* pbegin = &vchPrivKey[0];
8833 if (i2d_ECPrivateKey(pkey, &pbegin) != nSize)
8834 throw key_error("CKey::GetPrivKey() : i2d_ECPrivateKey returned unexpected size");
8835 return vchPrivKey;
8836 }
8837
8838 bool SetPubKey(const std::vector<unsigned char>& vchPubKey)
8839 {
8840 const unsigned char* pbegin = &vchPubKey[0];
8841 if (!o2i_ECPublicKey(&pkey, &pbegin, vchPubKey.size()))
8842 return false;
8843 fSet = true;
8844 return true;
8845 }
8846
8847 std::vector<unsigned char> GetPubKey() const
8848 {
8849 unsigned int nSize = i2o_ECPublicKey(pkey, NULL);
8850 if (!nSize)
8851 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey failed");
8852 std::vector<unsigned char> vchPubKey(nSize, 0);
8853 unsigned char* pbegin = &vchPubKey[0];
8854 if (i2o_ECPublicKey(pkey, &pbegin) != nSize)
8855 throw key_error("CKey::GetPubKey() : i2o_ECPublicKey returned unexpected size");
8856 return vchPubKey;
8857 }
8858
8859 bool Sign(uint256 hash, std::vector<unsigned char>& vchSig)
8860 {
8861 vchSig.clear();
8862 unsigned char pchSig[10000];
8863 unsigned int nSize = 0;
8864 if (!ECDSA_sign(0, (unsigned char*)&hash, sizeof(hash), pchSig, &nSize, pkey))
8865 return false;
8866 vchSig.resize(nSize);
8867 memcpy(&vchSig[0], pchSig, nSize);
8868 return true;
8869 }
8870
8871 // create a compact signature (65 bytes), which allows reconstructing the used public key
8872 // The format is one header byte, followed by two times 32 bytes for the serialized r and s values.
8873 // The header byte: 0x1B = first key with even y, 0x1C = first key with odd y,
8874 // 0x1D = second key with even y, 0x1E = second key with odd y
8875 bool SignCompact(uint256 hash, std::vector<unsigned char>& vchSig)
8876 {
8877 bool fOk = false;
8878 ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey);
8879 if (sig==NULL)
8880 return false;
8881 vchSig.clear();
8882 vchSig.resize(65,0);
8883 int nBitsR = BN_num_bits(sig->r);
8884 int nBitsS = BN_num_bits(sig->s);
8885 if (nBitsR <= 256 && nBitsS <= 256)
8886 {
8887 int nRecId = -1;
8888 for (int i=0; i<4; i++)
8889 {
8890 CKey keyRec;
8891 keyRec.fSet = true;
8892 if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1)
8893 if (keyRec.GetPubKey() == this->GetPubKey())
8894 {
8895 nRecId = i;
8896 break;
8897 }
8898 }
8899
8900 if (nRecId == -1)
8901 throw key_error("CKey::SignCompact() : unable to construct recoverable key");
8902
8903 vchSig[0] = nRecId+27;
8904 BN_bn2bin(sig->r,&vchSig[33-(nBitsR+7)/8]);
8905 BN_bn2bin(sig->s,&vchSig[65-(nBitsS+7)/8]);
8906 fOk = true;
8907 }
8908 ECDSA_SIG_free(sig);
8909 return fOk;
8910 }
8911
8912 // reconstruct public key from a compact signature
8913 // This is only slightly more CPU intensive than just verifying it.
8914 // If this function succeeds, the recovered public key is guaranteed to be valid
8915 // (the signature is a valid signature of the given data for that key)
8916 bool SetCompactSignature(uint256 hash, const std::vector<unsigned char>& vchSig)
8917 {
8918 if (vchSig.size() != 65)
8919 return false;
8920 if (vchSig[0]<27 || vchSig[0]>=31)
8921 return false;
8922 ECDSA_SIG *sig = ECDSA_SIG_new();
8923 BN_bin2bn(&vchSig[1],32,sig->r);
8924 BN_bin2bn(&vchSig[33],32,sig->s);
8925
8926 EC_KEY_free(pkey);
8927 pkey = EC_KEY_new_by_curve_name(NID_secp256k1);
8928 if (ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), vchSig[0] - 27, 0) == 1)
8929 {
8930 fSet = true;
8931 ECDSA_SIG_free(sig);
8932 return true;
8933 }
8934 return false;
8935 }
8936
8937 bool Verify(uint256 hash, const std::vector<unsigned char>& vchSig)
8938 {
8939 // -1 = error, 0 = bad sig, 1 = good
8940 if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1)
8941 return false;
8942 return true;
8943 }
8944
8945 // Verify a compact signature
8946 bool VerifyCompact(uint256 hash, const std::vector<unsigned char>& vchSig)
8947 {
8948 CKey key;
8949 if (!key.SetCompactSignature(hash, vchSig))
8950 return false;
8951 if (GetPubKey() != key.GetPubKey())
8952 return false;
8953 return true;
8954 }
8955
8956 // Get the address corresponding to this key
8957 CBitcoinAddress GetAddress() const
8958 {
8959 return CBitcoinAddress(GetPubKey());
8960 }
8961
8962 bool IsValid()
8963 {
8964 if (!fSet)
8965 return false;
8966
8967 CSecret secret = GetSecret();
8968 CKey key2;
8969 key2.SetSecret(secret);
8970 return GetPubKey() == key2.GetPubKey();
8971 }
8972 };
8973
8974 #endif