LCOV - code coverage report
Current view: top level - src - key.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 214 229 93.4 %
Date: 2020-09-26 01:30:44 Functions: 21 21 100.0 %

          Line data    Source code
       1             : // Copyright (c) 2009-2019 The Bitcoin Core developers
       2             : // Copyright (c) 2017 The Zcash developers
       3             : // Distributed under the MIT software license, see the accompanying
       4             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5             : 
       6             : #include <key.h>
       7             : 
       8             : #include <crypto/common.h>
       9             : #include <crypto/hmac_sha512.h>
      10             : #include <random.h>
      11             : 
      12             : #include <secp256k1.h>
      13             : #include <secp256k1_recovery.h>
      14             : 
      15             : static secp256k1_context* secp256k1_context_sign = nullptr;
      16             : 
      17             : /** These functions are taken from the libsecp256k1 distribution and are very ugly. */
      18             : 
      19             : /**
      20             :  * This parses a format loosely based on a DER encoding of the ECPrivateKey type from
      21             :  * section C.4 of SEC 1 <http://www.secg.org/sec1-v2.pdf>, with the following caveats:
      22             :  *
      23             :  * * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not
      24             :  *   required to be encoded as one octet if it is less than 256, as DER would require.
      25             :  * * The octet-length of the SEQUENCE must not be greater than the remaining
      26             :  *   length of the key encoding, but need not match it (i.e. the encoding may contain
      27             :  *   junk after the encoded SEQUENCE).
      28             :  * * The privateKey OCTET STRING is zero-filled on the left to 32 octets.
      29             :  * * Anything after the encoding of the privateKey OCTET STRING is ignored, whether
      30             :  *   or not it is validly encoded DER.
      31             :  *
      32             :  * out32 must point to an output buffer of length at least 32 bytes.
      33             :  */
      34       10907 : int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *seckey, size_t seckeylen) {
      35       10907 :     const unsigned char *end = seckey + seckeylen;
      36       10907 :     memset(out32, 0, 32);
      37             :     /* sequence header */
      38       10907 :     if (end - seckey < 1 || *seckey != 0x30u) {
      39           0 :         return 0;
      40             :     }
      41       10907 :     seckey++;
      42             :     /* sequence length constructor */
      43       10907 :     if (end - seckey < 1 || !(*seckey & 0x80u)) {
      44           0 :         return 0;
      45             :     }
      46       10907 :     ptrdiff_t lenb = *seckey & ~0x80u; seckey++;
      47       10907 :     if (lenb < 1 || lenb > 2) {
      48           0 :         return 0;
      49             :     }
      50       10907 :     if (end - seckey < lenb) {
      51           0 :         return 0;
      52             :     }
      53             :     /* sequence length */
      54       10907 :     ptrdiff_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u);
      55       10907 :     seckey += lenb;
      56       10907 :     if (end - seckey < len) {
      57           0 :         return 0;
      58             :     }
      59             :     /* sequence element 0: version number (=1) */
      60       10907 :     if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) {
      61           0 :         return 0;
      62             :     }
      63       10907 :     seckey += 3;
      64             :     /* sequence element 1: octet string, up to 32 bytes */
      65       10907 :     if (end - seckey < 2 || seckey[0] != 0x04u) {
      66           0 :         return 0;
      67             :     }
      68       10907 :     ptrdiff_t oslen = seckey[1];
      69       10907 :     seckey += 2;
      70       10907 :     if (oslen > 32 || end - seckey < oslen) {
      71           0 :         return 0;
      72             :     }
      73       10907 :     memcpy(out32 + (32 - oslen), seckey, oslen);
      74       10907 :     if (!secp256k1_ec_seckey_verify(ctx, out32)) {
      75           0 :         memset(out32, 0, 32);
      76           0 :         return 0;
      77             :     }
      78       10907 :     return 1;
      79       10907 : }
      80             : 
      81             : /**
      82             :  * This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1
      83             :  * <http://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are
      84             :  * included.
      85             :  *
      86             :  * seckey must point to an output buffer of length at least CKey::SIZE bytes.
      87             :  * seckeylen must initially be set to the size of the seckey buffer. Upon return it
      88             :  * will be set to the number of bytes used in the buffer.
      89             :  * key32 must point to a 32-byte raw private key.
      90             :  */
      91       26238 : int ec_seckey_export_der(const secp256k1_context *ctx, unsigned char *seckey, size_t *seckeylen, const unsigned char *key32, bool compressed) {
      92       26238 :     assert(*seckeylen >= CKey::SIZE);
      93       26238 :     secp256k1_pubkey pubkey;
      94       26238 :     size_t pubkeylen = 0;
      95       26238 :     if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
      96           0 :         *seckeylen = 0;
      97           0 :         return 0;
      98             :     }
      99       26238 :     if (compressed) {
     100             :         static const unsigned char begin[] = {
     101             :             0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
     102             :         };
     103             :         static const unsigned char middle[] = {
     104             :             0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
     105             :             0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     106             :             0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     107             :             0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
     108             :             0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
     109             :             0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
     110             :             0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     111             :             0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
     112             :             0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
     113             :         };
     114             :         unsigned char *ptr = seckey;
     115       21226 :         memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
     116       21226 :         memcpy(ptr, key32, 32); ptr += 32;
     117       21226 :         memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
     118       21226 :         pubkeylen = CPubKey::COMPRESSED_SIZE;
     119       21226 :         secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
     120       21226 :         ptr += pubkeylen;
     121       21226 :         *seckeylen = ptr - seckey;
     122       21226 :         assert(*seckeylen == CKey::COMPRESSED_SIZE);
     123       21226 :     } else {
     124             :         static const unsigned char begin[] = {
     125             :             0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
     126             :         };
     127             :         static const unsigned char middle[] = {
     128             :             0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
     129             :             0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     130             :             0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     131             :             0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
     132             :             0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
     133             :             0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
     134             :             0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
     135             :             0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
     136             :             0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     137             :             0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
     138             :             0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
     139             :         };
     140             :         unsigned char *ptr = seckey;
     141        5012 :         memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
     142        5012 :         memcpy(ptr, key32, 32); ptr += 32;
     143        5012 :         memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
     144        5012 :         pubkeylen = CPubKey::SIZE;
     145        5012 :         secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
     146        5012 :         ptr += pubkeylen;
     147        5012 :         *seckeylen = ptr - seckey;
     148        5012 :         assert(*seckeylen == CKey::SIZE);
     149             :     }
     150       26238 :     return 1;
     151       26238 : }
     152             : 
     153       30287 : bool CKey::Check(const unsigned char *vch) {
     154       30287 :     return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch);
     155             : }
     156             : 
     157        6042 : void CKey::MakeNewKey(bool fCompressedIn) {
     158        6042 :     do {
     159        6042 :         GetStrongRandBytes(keydata.data(), keydata.size());
     160        6042 :     } while (!Check(keydata.data()));
     161        6042 :     fValid = true;
     162        6042 :     fCompressed = fCompressedIn;
     163        6042 : }
     164             : 
     165           2 : bool CKey::Negate()
     166             : {
     167           2 :     assert(fValid);
     168           2 :     return secp256k1_ec_seckey_negate(secp256k1_context_sign, keydata.data());
     169             : }
     170             : 
     171       26238 : CPrivKey CKey::GetPrivKey() const {
     172       26238 :     assert(fValid);
     173       26238 :     CPrivKey seckey;
     174             :     int ret;
     175       26238 :     size_t seckeylen;
     176       26238 :     seckey.resize(SIZE);
     177       26238 :     seckeylen = SIZE;
     178       26238 :     ret = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, begin(), fCompressed);
     179       26238 :     assert(ret);
     180       26238 :     seckey.resize(seckeylen);
     181             :     return seckey;
     182       26238 : }
     183             : 
     184      946786 : CPubKey CKey::GetPubKey() const {
     185      946786 :     assert(fValid);
     186      946786 :     secp256k1_pubkey pubkey;
     187      946786 :     size_t clen = CPubKey::SIZE;
     188      946786 :     CPubKey result;
     189      946786 :     int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, begin());
     190      946786 :     assert(ret);
     191      946786 :     secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
     192      946786 :     assert(result.size() == clen);
     193      946786 :     assert(result.IsValid());
     194             :     return result;
     195      946786 : }
     196             : 
     197             : // Check that the sig has a low R value and will be less than 71 bytes
     198      108200 : bool SigHasLowR(const secp256k1_ecdsa_signature* sig)
     199             : {
     200      108200 :     unsigned char compact_sig[64];
     201      108200 :     secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_sign, compact_sig, sig);
     202             : 
     203             :     // In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates
     204             :     // its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted
     205             :     // to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that
     206             :     // our highest bit is always 0, and thus we must check that the first byte is less than 0x80.
     207      216400 :     return compact_sig[0] < 0x80;
     208      108200 : }
     209             : 
     210       54875 : bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const {
     211       54875 :     if (!fValid)
     212           0 :         return false;
     213       54875 :     vchSig.resize(CPubKey::SIGNATURE_SIZE);
     214       54875 :     size_t nSigLen = CPubKey::SIGNATURE_SIZE;
     215       54875 :     unsigned char extra_entropy[32] = {0};
     216       54875 :     WriteLE32(extra_entropy, test_case);
     217       54875 :     secp256k1_ecdsa_signature sig;
     218             :     uint32_t counter = 0;
     219       54875 :     int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr);
     220             : 
     221             :     // Grind for low R
     222      108200 :     while (ret && !SigHasLowR(&sig) && grind) {
     223       53325 :         WriteLE32(extra_entropy, ++counter);
     224       53325 :         ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, extra_entropy);
     225             :     }
     226       54875 :     assert(ret);
     227       54875 :     secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, vchSig.data(), &nSigLen, &sig);
     228       54875 :     vchSig.resize(nSigLen);
     229             :     return true;
     230       54875 : }
     231             : 
     232       30679 : bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
     233       30679 :     if (pubkey.IsCompressed() != fCompressed) {
     234           8 :         return false;
     235             :     }
     236       30671 :     unsigned char rnd[8];
     237       30671 :     std::string str = "Bitcoin key verification\n";
     238       30671 :     GetRandBytes(rnd, sizeof(rnd));
     239       30671 :     uint256 hash;
     240       30671 :     CHash256().Write(MakeUCharSpan(str)).Write(rnd).Finalize(hash);
     241       30671 :     std::vector<unsigned char> vchSig;
     242       30671 :     Sign(hash, vchSig);
     243       30671 :     return pubkey.Verify(hash, vchSig);
     244       30679 : }
     245             : 
     246          83 : bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
     247          83 :     if (!fValid)
     248           1 :         return false;
     249          82 :     vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
     250          82 :     int rec = -1;
     251          82 :     secp256k1_ecdsa_recoverable_signature sig;
     252          82 :     int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
     253          82 :     assert(ret);
     254          82 :     ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, &vchSig[1], &rec, &sig);
     255          82 :     assert(ret);
     256          82 :     assert(rec != -1);
     257          82 :     vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
     258             :     return true;
     259          83 : }
     260             : 
     261       10907 : bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
     262       10907 :     if (!ec_seckey_import_der(secp256k1_context_sign, (unsigned char*)begin(), seckey.data(), seckey.size()))
     263           0 :         return false;
     264       10907 :     fCompressed = vchPubKey.IsCompressed();
     265       10907 :     fValid = true;
     266             : 
     267       10907 :     if (fSkipCheck)
     268       10907 :         return true;
     269             : 
     270           0 :     return VerifyPubKey(vchPubKey);
     271       10907 : }
     272             : 
     273       82396 : bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
     274       82396 :     assert(IsValid());
     275       82396 :     assert(IsCompressed());
     276       82396 :     std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
     277       82396 :     if ((nChild >> 31) == 0) {
     278        7355 :         CPubKey pubkey = GetPubKey();
     279        7355 :         assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
     280        7355 :         BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
     281        7355 :     } else {
     282       75041 :         assert(size() == 32);
     283       75041 :         BIP32Hash(cc, nChild, 0, begin(), vout.data());
     284             :     }
     285       82396 :     memcpy(ccChild.begin(), vout.data()+32, 32);
     286       82396 :     memcpy((unsigned char*)keyChild.begin(), begin(), 32);
     287       82396 :     bool ret = secp256k1_ec_seckey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data());
     288       82396 :     keyChild.fCompressed = true;
     289       82396 :     keyChild.fValid = ret;
     290             :     return ret;
     291       82396 : }
     292             : 
     293       82396 : bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
     294       82396 :     out.nDepth = nDepth + 1;
     295       82396 :     CKeyID id = key.GetPubKey().GetID();
     296       82396 :     memcpy(&out.vchFingerprint[0], &id, 4);
     297       82396 :     out.nChild = _nChild;
     298      164792 :     return key.Derive(out.key, out.chaincode, _nChild, chaincode);
     299       82396 : }
     300             : 
     301       19968 : void CExtKey::SetSeed(const unsigned char *seed, unsigned int nSeedLen) {
     302             :     static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
     303       19968 :     std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
     304       19968 :     CHMAC_SHA512(hashkey, sizeof(hashkey)).Write(seed, nSeedLen).Finalize(vout.data());
     305       19968 :     key.Set(vout.data(), vout.data() + 32, true);
     306       19968 :     memcpy(chaincode.begin(), vout.data() + 32, 32);
     307       19968 :     nDepth = 0;
     308       19968 :     nChild = 0;
     309       19968 :     memset(vchFingerprint, 0, sizeof(vchFingerprint));
     310       19968 : }
     311             : 
     312       14374 : CExtPubKey CExtKey::Neuter() const {
     313       14374 :     CExtPubKey ret;
     314       14374 :     ret.nDepth = nDepth;
     315       14374 :     memcpy(&ret.vchFingerprint[0], &vchFingerprint[0], 4);
     316       14374 :     ret.nChild = nChild;
     317       14374 :     ret.pubkey = key.GetPubKey();
     318       14374 :     ret.chaincode = chaincode;
     319       14374 :     return ret;
     320             : }
     321             : 
     322         139 : void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
     323         139 :     code[0] = nDepth;
     324         139 :     memcpy(code+1, vchFingerprint, 4);
     325         139 :     code[5] = (nChild >> 24) & 0xFF; code[6] = (nChild >> 16) & 0xFF;
     326         139 :     code[7] = (nChild >>  8) & 0xFF; code[8] = (nChild >>  0) & 0xFF;
     327         139 :     memcpy(code+9, chaincode.begin(), 32);
     328         139 :     code[41] = 0;
     329         139 :     assert(key.size() == 32);
     330         139 :     memcpy(code+42, key.begin(), 32);
     331         139 : }
     332             : 
     333         137 : void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
     334         137 :     nDepth = code[0];
     335         137 :     memcpy(vchFingerprint, code+1, 4);
     336         137 :     nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
     337         137 :     memcpy(chaincode.begin(), code+9, 32);
     338         137 :     key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
     339         137 : }
     340             : 
     341         531 : bool ECC_InitSanityCheck() {
     342         531 :     CKey key;
     343         531 :     key.MakeNewKey(true);
     344         531 :     CPubKey pubkey = key.GetPubKey();
     345         531 :     return key.VerifyPubKey(pubkey);
     346         531 : }
     347             : 
     348        1028 : void ECC_Start() {
     349        1028 :     assert(secp256k1_context_sign == nullptr);
     350             : 
     351        1028 :     secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN);
     352        1028 :     assert(ctx != nullptr);
     353             : 
     354             :     {
     355             :         // Pass in a random blinding seed to the secp256k1 context.
     356        1028 :         std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
     357        1028 :         GetRandBytes(vseed.data(), 32);
     358        1028 :         bool ret = secp256k1_context_randomize(ctx, vseed.data());
     359        1028 :         assert(ret);
     360        1028 :     }
     361             : 
     362        1028 :     secp256k1_context_sign = ctx;
     363        1028 : }
     364             : 
     365        1022 : void ECC_Stop() {
     366        1022 :     secp256k1_context *ctx = secp256k1_context_sign;
     367        1022 :     secp256k1_context_sign = nullptr;
     368             : 
     369        1022 :     if (ctx) {
     370        1022 :         secp256k1_context_destroy(ctx);
     371        1022 :     }
     372        1022 : }

Generated by: LCOV version 1.15