LCOV - code coverage report
Current view: top level - src - key.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 79.5 % 312 248
Test Date: 2024-09-01 05:20:30 Functions: 72.4 % 29 21
Branches: 45.9 % 266 122

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2009-2022 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 <hash.h>
      11                 :             : #include <random.h>
      12                 :             : 
      13                 :             : #include <secp256k1.h>
      14                 :             : #include <secp256k1_ellswift.h>
      15                 :             : #include <secp256k1_extrakeys.h>
      16                 :             : #include <secp256k1_recovery.h>
      17                 :             : #include <secp256k1_schnorrsig.h>
      18                 :             : 
      19                 :             : static secp256k1_context* secp256k1_context_sign = nullptr;
      20                 :             : 
      21                 :             : /** These functions are taken from the libsecp256k1 distribution and are very ugly. */
      22                 :             : 
      23                 :             : /**
      24                 :             :  * This parses a format loosely based on a DER encoding of the ECPrivateKey type from
      25                 :             :  * section C.4 of SEC 1 <https://www.secg.org/sec1-v2.pdf>, with the following caveats:
      26                 :             :  *
      27                 :             :  * * The octet-length of the SEQUENCE must be encoded as 1 or 2 octets. It is not
      28                 :             :  *   required to be encoded as one octet if it is less than 256, as DER would require.
      29                 :             :  * * The octet-length of the SEQUENCE must not be greater than the remaining
      30                 :             :  *   length of the key encoding, but need not match it (i.e. the encoding may contain
      31                 :             :  *   junk after the encoded SEQUENCE).
      32                 :             :  * * The privateKey OCTET STRING is zero-filled on the left to 32 octets.
      33                 :             :  * * Anything after the encoding of the privateKey OCTET STRING is ignored, whether
      34                 :             :  *   or not it is validly encoded DER.
      35                 :             :  *
      36                 :             :  * out32 must point to an output buffer of length at least 32 bytes.
      37                 :             :  */
      38                 :        1114 : int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *seckey, size_t seckeylen) {
      39                 :        1114 :     const unsigned char *end = seckey + seckeylen;
      40                 :        1114 :     memset(out32, 0, 32);
      41                 :             :     /* sequence header */
      42   [ +  -  +  + ]:        1114 :     if (end - seckey < 1 || *seckey != 0x30u) {
      43                 :           6 :         return 0;
      44                 :             :     }
      45                 :        1108 :     seckey++;
      46                 :             :     /* sequence length constructor */
      47   [ +  -  +  + ]:        1108 :     if (end - seckey < 1 || !(*seckey & 0x80u)) {
      48                 :           1 :         return 0;
      49                 :             :     }
      50                 :        1107 :     ptrdiff_t lenb = *seckey & ~0x80u; seckey++;
      51   [ +  +  +  + ]:        1107 :     if (lenb < 1 || lenb > 2) {
      52                 :           4 :         return 0;
      53                 :             :     }
      54         [ -  + ]:        1103 :     if (end - seckey < lenb) {
      55                 :           0 :         return 0;
      56                 :             :     }
      57                 :             :     /* sequence length */
      58         [ +  + ]:        1103 :     ptrdiff_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u);
      59                 :        1103 :     seckey += lenb;
      60         [ +  + ]:        1103 :     if (end - seckey < len) {
      61                 :           5 :         return 0;
      62                 :             :     }
      63                 :             :     /* sequence element 0: version number (=1) */
      64   [ +  -  +  +  :        1098 :     if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) {
             +  +  +  + ]
      65                 :           9 :         return 0;
      66                 :             :     }
      67                 :        1089 :     seckey += 3;
      68                 :             :     /* sequence element 1: octet string, up to 32 bytes */
      69   [ +  -  +  + ]:        1089 :     if (end - seckey < 2 || seckey[0] != 0x04u) {
      70                 :           1 :         return 0;
      71                 :             :     }
      72                 :        1088 :     ptrdiff_t oslen = seckey[1];
      73                 :        1088 :     seckey += 2;
      74   [ +  +  -  + ]:        1088 :     if (oslen > 32 || end - seckey < oslen) {
      75                 :           2 :         return 0;
      76                 :             :     }
      77                 :        1086 :     memcpy(out32 + (32 - oslen), seckey, oslen);
      78         [ +  + ]:        1086 :     if (!secp256k1_ec_seckey_verify(ctx, out32)) {
      79                 :           2 :         memset(out32, 0, 32);
      80                 :           2 :         return 0;
      81                 :             :     }
      82                 :        1084 :     return 1;
      83                 :        1114 : }
      84                 :             : 
      85                 :             : /**
      86                 :             :  * This serializes to a DER encoding of the ECPrivateKey type from section C.4 of SEC 1
      87                 :             :  * <https://www.secg.org/sec1-v2.pdf>. The optional parameters and publicKey fields are
      88                 :             :  * included.
      89                 :             :  *
      90                 :             :  * seckey must point to an output buffer of length at least CKey::SIZE bytes.
      91                 :             :  * seckeylen must initially be set to the size of the seckey buffer. Upon return it
      92                 :             :  * will be set to the number of bytes used in the buffer.
      93                 :             :  * key32 must point to a 32-byte raw private key.
      94                 :             :  */
      95                 :       29107 : int ec_seckey_export_der(const secp256k1_context *ctx, unsigned char *seckey, size_t *seckeylen, const unsigned char *key32, bool compressed) {
      96         [ +  - ]:       29107 :     assert(*seckeylen >= CKey::SIZE);
      97                 :       29107 :     secp256k1_pubkey pubkey;
      98                 :       29107 :     size_t pubkeylen = 0;
      99         [ +  + ]:       29107 :     if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
     100                 :          18 :         *seckeylen = 0;
     101                 :          18 :         return 0;
     102                 :             :     }
     103         [ +  + ]:       29089 :     if (compressed) {
     104                 :             :         static const unsigned char begin[] = {
     105                 :             :             0x30,0x81,0xD3,0x02,0x01,0x01,0x04,0x20
     106                 :             :         };
     107                 :             :         static const unsigned char middle[] = {
     108                 :             :             0xA0,0x81,0x85,0x30,0x81,0x82,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
     109                 :             :             0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     110                 :             :             0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     111                 :             :             0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
     112                 :             :             0x21,0x02,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
     113                 :             :             0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
     114                 :             :             0x17,0x98,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     115                 :             :             0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
     116                 :             :             0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x24,0x03,0x22,0x00
     117                 :             :         };
     118                 :       29077 :         unsigned char *ptr = seckey;
     119                 :       29077 :         memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
     120                 :       29077 :         memcpy(ptr, key32, 32); ptr += 32;
     121                 :       29077 :         memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
     122                 :       29077 :         pubkeylen = CPubKey::COMPRESSED_SIZE;
     123                 :       29077 :         secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
     124                 :       29077 :         ptr += pubkeylen;
     125                 :       29077 :         *seckeylen = ptr - seckey;
     126         [ +  - ]:       29077 :         assert(*seckeylen == CKey::COMPRESSED_SIZE);
     127                 :       29077 :     } else {
     128                 :             :         static const unsigned char begin[] = {
     129                 :             :             0x30,0x82,0x01,0x13,0x02,0x01,0x01,0x04,0x20
     130                 :             :         };
     131                 :             :         static const unsigned char middle[] = {
     132                 :             :             0xA0,0x81,0xA5,0x30,0x81,0xA2,0x02,0x01,0x01,0x30,0x2C,0x06,0x07,0x2A,0x86,0x48,
     133                 :             :             0xCE,0x3D,0x01,0x01,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     134                 :             :             0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     135                 :             :             0xFF,0xFF,0xFE,0xFF,0xFF,0xFC,0x2F,0x30,0x06,0x04,0x01,0x00,0x04,0x01,0x07,0x04,
     136                 :             :             0x41,0x04,0x79,0xBE,0x66,0x7E,0xF9,0xDC,0xBB,0xAC,0x55,0xA0,0x62,0x95,0xCE,0x87,
     137                 :             :             0x0B,0x07,0x02,0x9B,0xFC,0xDB,0x2D,0xCE,0x28,0xD9,0x59,0xF2,0x81,0x5B,0x16,0xF8,
     138                 :             :             0x17,0x98,0x48,0x3A,0xDA,0x77,0x26,0xA3,0xC4,0x65,0x5D,0xA4,0xFB,0xFC,0x0E,0x11,
     139                 :             :             0x08,0xA8,0xFD,0x17,0xB4,0x48,0xA6,0x85,0x54,0x19,0x9C,0x47,0xD0,0x8F,0xFB,0x10,
     140                 :             :             0xD4,0xB8,0x02,0x21,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
     141                 :             :             0xFF,0xFF,0xFF,0xFF,0xFE,0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B,0xBF,0xD2,0x5E,
     142                 :             :             0x8C,0xD0,0x36,0x41,0x41,0x02,0x01,0x01,0xA1,0x44,0x03,0x42,0x00
     143                 :             :         };
     144                 :          12 :         unsigned char *ptr = seckey;
     145                 :          12 :         memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
     146                 :          12 :         memcpy(ptr, key32, 32); ptr += 32;
     147                 :          12 :         memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
     148                 :          12 :         pubkeylen = CPubKey::SIZE;
     149                 :          12 :         secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
     150                 :          12 :         ptr += pubkeylen;
     151                 :          12 :         *seckeylen = ptr - seckey;
     152         [ +  - ]:          12 :         assert(*seckeylen == CKey::SIZE);
     153                 :          12 :     }
     154                 :       29089 :     return 1;
     155                 :       29107 : }
     156                 :             : 
     157                 :      332676 : bool CKey::Check(const unsigned char *vch) {
     158                 :      332676 :     return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch);
     159                 :             : }
     160                 :             : 
     161                 :           0 : void CKey::MakeNewKey(bool fCompressedIn) {
     162                 :           0 :     MakeKeyData();
     163                 :           0 :     do {
     164                 :           0 :         GetStrongRandBytes(*keydata);
     165         [ #  # ]:           0 :     } while (!Check(keydata->data()));
     166                 :           0 :     fCompressed = fCompressedIn;
     167                 :           0 : }
     168                 :             : 
     169                 :       29075 : CPrivKey CKey::GetPrivKey() const {
     170         [ +  - ]:       29075 :     assert(keydata);
     171                 :       29075 :     CPrivKey seckey;
     172                 :       29075 :     int ret;
     173                 :       29075 :     size_t seckeylen;
     174         [ +  - ]:       29075 :     seckey.resize(SIZE);
     175                 :       29075 :     seckeylen = SIZE;
     176   [ +  -  +  -  :       29075 :     ret = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, UCharCast(begin()), fCompressed);
                   +  - ]
     177         [ +  - ]:       29075 :     assert(ret);
     178         [ +  - ]:       29075 :     seckey.resize(seckeylen);
     179                 :       29075 :     return seckey;
     180         [ +  - ]:       29075 : }
     181                 :             : 
     182                 :      613351 : CPubKey CKey::GetPubKey() const {
     183         [ +  - ]:      613351 :     assert(keydata);
     184                 :      613351 :     secp256k1_pubkey pubkey;
     185                 :      613351 :     size_t clen = CPubKey::SIZE;
     186                 :      613351 :     CPubKey result;
     187                 :      613351 :     int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, UCharCast(begin()));
     188         [ +  - ]:      613351 :     assert(ret);
     189                 :      613351 :     secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
     190         [ +  - ]:      613351 :     assert(result.size() == clen);
     191         [ +  - ]:      613351 :     assert(result.IsValid());
     192                 :             :     return result;
     193                 :      613351 : }
     194                 :             : 
     195                 :             : // Check that the sig has a low R value and will be less than 71 bytes
     196                 :       66023 : bool SigHasLowR(const secp256k1_ecdsa_signature* sig)
     197                 :             : {
     198                 :       66023 :     unsigned char compact_sig[64];
     199                 :       66023 :     secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_sign, compact_sig, sig);
     200                 :             : 
     201                 :             :     // In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates
     202                 :             :     // its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted
     203                 :             :     // to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that
     204                 :             :     // our highest bit is always 0, and thus we must check that the first byte is less than 0x80.
     205                 :      132046 :     return compact_sig[0] < 0x80;
     206                 :       66023 : }
     207                 :             : 
     208                 :       31306 : bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const {
     209         [ -  + ]:       31306 :     if (!keydata)
     210                 :           0 :         return false;
     211                 :       31306 :     vchSig.resize(CPubKey::SIGNATURE_SIZE);
     212                 :       31306 :     size_t nSigLen = CPubKey::SIGNATURE_SIZE;
     213                 :       31306 :     unsigned char extra_entropy[32] = {0};
     214                 :       31306 :     WriteLE32(extra_entropy, test_case);
     215                 :       31306 :     secp256k1_ecdsa_signature sig;
     216                 :       31306 :     uint32_t counter = 0;
     217   [ +  +  +  - ]:       31306 :     int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr);
     218                 :             : 
     219                 :             :     // Grind for low R
     220   [ +  -  +  +  :       65926 :     while (ret && !SigHasLowR(&sig) && grind) {
                   +  + ]
     221                 :       34620 :         WriteLE32(extra_entropy, ++counter);
     222                 :       34620 :         ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, extra_entropy);
     223                 :             :     }
     224         [ +  - ]:       31306 :     assert(ret);
     225                 :       31306 :     secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, vchSig.data(), &nSigLen, &sig);
     226                 :       31306 :     vchSig.resize(nSigLen);
     227                 :             :     // Additional verification step to prevent using a potentially corrupted signature
     228                 :       31306 :     secp256k1_pubkey pk;
     229                 :       31306 :     ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pk, UCharCast(begin()));
     230         [ +  - ]:       31306 :     assert(ret);
     231                 :       31306 :     ret = secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pk);
     232         [ +  - ]:       31306 :     assert(ret);
     233                 :       31306 :     return true;
     234                 :       31306 : }
     235                 :             : 
     236                 :        1068 : bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
     237         [ -  + ]:        1068 :     if (pubkey.IsCompressed() != fCompressed) {
     238                 :           0 :         return false;
     239                 :             :     }
     240                 :        1068 :     unsigned char rnd[8];
     241         [ +  - ]:        1068 :     std::string str = "Bitcoin key verification\n";
     242                 :        1068 :     GetRandBytes(rnd);
     243         [ +  - ]:        1068 :     uint256 hash{Hash(str, rnd)};
     244                 :        1068 :     std::vector<unsigned char> vchSig;
     245         [ +  - ]:        1068 :     Sign(hash, vchSig);
     246         [ +  - ]:        1068 :     return pubkey.Verify(hash, vchSig);
     247                 :        1068 : }
     248                 :             : 
     249                 :        2909 : bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
     250         [ +  + ]:        2909 :     if (!keydata)
     251                 :          80 :         return false;
     252                 :        2829 :     vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
     253                 :        2829 :     int rec = -1;
     254                 :        2829 :     secp256k1_ecdsa_recoverable_signature rsig;
     255                 :        2829 :     int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &rsig, hash.begin(), UCharCast(begin()), secp256k1_nonce_function_rfc6979, nullptr);
     256         [ +  - ]:        2829 :     assert(ret);
     257                 :        2829 :     ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, &vchSig[1], &rec, &rsig);
     258         [ +  - ]:        2829 :     assert(ret);
     259         [ +  - ]:        2829 :     assert(rec != -1);
     260                 :        2829 :     vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
     261                 :             :     // Additional verification step to prevent using a potentially corrupted signature
     262                 :        2829 :     secp256k1_pubkey epk, rpk;
     263                 :        2829 :     ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &epk, UCharCast(begin()));
     264         [ +  - ]:        2829 :     assert(ret);
     265                 :        2829 :     ret = secp256k1_ecdsa_recover(secp256k1_context_static, &rpk, &rsig, hash.begin());
     266         [ +  - ]:        2829 :     assert(ret);
     267                 :        2829 :     ret = secp256k1_ec_pubkey_cmp(secp256k1_context_static, &epk, &rpk);
     268         [ +  - ]:        2829 :     assert(ret == 0);
     269                 :        2829 :     return true;
     270                 :        2909 : }
     271                 :             : 
     272                 :           0 : bool CKey::SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const
     273                 :             : {
     274                 :           0 :     KeyPair kp = ComputeKeyPair(merkle_root);
     275         [ #  # ]:           0 :     return kp.SignSchnorr(hash, sig, aux);
     276                 :           0 : }
     277                 :             : 
     278                 :        1068 : bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
     279                 :        1068 :     MakeKeyData();
     280         [ +  - ]:        1068 :     if (!ec_seckey_import_der(secp256k1_context_sign, (unsigned char*)begin(), seckey.data(), seckey.size())) {
     281                 :           0 :         ClearKeyData();
     282                 :           0 :         return false;
     283                 :             :     }
     284                 :        1068 :     fCompressed = vchPubKey.IsCompressed();
     285                 :             : 
     286         [ +  + ]:        1068 :     if (fSkipCheck)
     287                 :         534 :         return true;
     288                 :             : 
     289                 :         534 :     return VerifyPubKey(vchPubKey);
     290                 :        1068 : }
     291                 :             : 
     292                 :      123315 : bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
     293         [ +  - ]:      123315 :     assert(IsValid());
     294         [ +  - ]:      123315 :     assert(IsCompressed());
     295                 :      123315 :     std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
     296         [ +  + ]:      123315 :     if ((nChild >> 31) == 0) {
     297         [ +  - ]:       77474 :         CPubKey pubkey = GetPubKey();
     298   [ +  -  +  - ]:       77474 :         assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
     299   [ +  -  +  -  :       77474 :         BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
                   +  - ]
     300                 :       77474 :     } else {
     301   [ +  -  +  - ]:       45841 :         assert(size() == 32);
     302   [ +  -  +  -  :       45841 :         BIP32Hash(cc, nChild, 0, UCharCast(begin()), vout.data());
                   +  - ]
     303                 :             :     }
     304         [ +  - ]:      123315 :     memcpy(ccChild.begin(), vout.data()+32, 32);
     305   [ +  -  +  -  :      123315 :     keyChild.Set(begin(), begin() + 32, true);
                   +  - ]
     306   [ +  -  +  - ]:      123315 :     bool ret = secp256k1_ec_seckey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data());
     307   [ -  +  #  # ]:      123315 :     if (!ret) keyChild.ClearKeyData();
     308                 :      123315 :     return ret;
     309                 :      123315 : }
     310                 :             : 
     311                 :        5368 : EllSwiftPubKey CKey::EllSwiftCreate(Span<const std::byte> ent32) const
     312                 :             : {
     313         [ +  - ]:        5368 :     assert(keydata);
     314         [ +  - ]:        5368 :     assert(ent32.size() == 32);
     315                 :        5368 :     std::array<std::byte, EllSwiftPubKey::size()> encoded_pubkey;
     316                 :             : 
     317                 :       10736 :     auto success = secp256k1_ellswift_create(secp256k1_context_sign,
     318                 :        5368 :                                              UCharCast(encoded_pubkey.data()),
     319                 :        5368 :                                              keydata->data(),
     320                 :        5368 :                                              UCharCast(ent32.data()));
     321                 :             : 
     322                 :             :     // Should always succeed for valid keys (asserted above).
     323         [ +  - ]:        5368 :     assert(success);
     324                 :        5368 :     return {encoded_pubkey};
     325                 :        5368 : }
     326                 :             : 
     327                 :        4293 : ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, const EllSwiftPubKey& our_ellswift, bool initiating) const
     328                 :             : {
     329         [ +  - ]:        4293 :     assert(keydata);
     330                 :             : 
     331                 :             :     ECDHSecret output;
     332                 :             :     // BIP324 uses the initiator as party A, and the responder as party B. Remap the inputs
     333                 :             :     // accordingly:
     334                 :        8586 :     bool success = secp256k1_ellswift_xdh(secp256k1_context_sign,
     335                 :        4293 :                                           UCharCast(output.data()),
     336         [ +  + ]:        4293 :                                           UCharCast(initiating ? our_ellswift.data() : their_ellswift.data()),
     337         [ +  + ]:        4293 :                                           UCharCast(initiating ? their_ellswift.data() : our_ellswift.data()),
     338                 :        4293 :                                           keydata->data(),
     339                 :        4293 :                                           initiating ? 0 : 1,
     340                 :        4293 :                                           secp256k1_ellswift_xdh_hash_function_bip324,
     341                 :             :                                           nullptr);
     342                 :             :     // Should always succeed for valid keys (assert above).
     343         [ +  - ]:        4293 :     assert(success);
     344                 :             :     return output;
     345                 :        4293 : }
     346                 :             : 
     347                 :           0 : KeyPair CKey::ComputeKeyPair(const uint256* merkle_root) const
     348                 :             : {
     349                 :           0 :     return KeyPair(*this, merkle_root);
     350                 :             : }
     351                 :             : 
     352                 :           0 : CKey GenerateRandomKey(bool compressed) noexcept
     353                 :             : {
     354                 :           0 :     CKey key;
     355         [ #  # ]:           0 :     key.MakeNewKey(/*fCompressed=*/compressed);
     356                 :           0 :     return key;
     357         [ #  # ]:           0 : }
     358                 :             : 
     359                 :      122781 : bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
     360         [ -  + ]:      122781 :     if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
     361                 :      122781 :     out.nDepth = nDepth + 1;
     362                 :      122781 :     CKeyID id = key.GetPubKey().GetID();
     363                 :      122781 :     memcpy(out.vchFingerprint, &id, 4);
     364                 :      122781 :     out.nChild = _nChild;
     365                 :      122781 :     return key.Derive(out.key, out.chaincode, _nChild, chaincode);
     366                 :      122781 : }
     367                 :             : 
     368                 :           0 : void CExtKey::SetSeed(Span<const std::byte> seed)
     369                 :             : {
     370                 :             :     static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
     371                 :           0 :     std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
     372   [ #  #  #  #  :           0 :     CHMAC_SHA512{hashkey, sizeof(hashkey)}.Write(UCharCast(seed.data()), seed.size()).Finalize(vout.data());
             #  #  #  # ]
     373         [ #  # ]:           0 :     key.Set(vout.data(), vout.data() + 32, true);
     374         [ #  # ]:           0 :     memcpy(chaincode.begin(), vout.data() + 32, 32);
     375                 :           0 :     nDepth = 0;
     376                 :           0 :     nChild = 0;
     377                 :           0 :     memset(vchFingerprint, 0, sizeof(vchFingerprint));
     378                 :           0 : }
     379                 :             : 
     380                 :      184272 : CExtPubKey CExtKey::Neuter() const {
     381                 :      184272 :     CExtPubKey ret;
     382                 :      184272 :     ret.nDepth = nDepth;
     383                 :      184272 :     memcpy(ret.vchFingerprint, vchFingerprint, 4);
     384                 :      184272 :     ret.nChild = nChild;
     385                 :      184272 :     ret.pubkey = key.GetPubKey();
     386                 :      184272 :     ret.chaincode = chaincode;
     387                 :      184272 :     return ret;
     388                 :             : }
     389                 :             : 
     390                 :       14988 : void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
     391                 :       14988 :     code[0] = nDepth;
     392                 :       14988 :     memcpy(code+1, vchFingerprint, 4);
     393                 :       14988 :     WriteBE32(code+5, nChild);
     394                 :       14988 :     memcpy(code+9, chaincode.begin(), 32);
     395                 :       14988 :     code[41] = 0;
     396         [ +  - ]:       14988 :     assert(key.size() == 32);
     397                 :       14988 :     memcpy(code+42, key.begin(), 32);
     398                 :       14988 : }
     399                 :             : 
     400                 :      131222 : void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
     401                 :      131222 :     nDepth = code[0];
     402                 :      131222 :     memcpy(vchFingerprint, code+1, 4);
     403                 :      131222 :     nChild = ReadBE32(code+5);
     404                 :      131222 :     memcpy(chaincode.begin(), code+9, 32);
     405                 :      131222 :     key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
     406   [ +  +  +  -  :      131222 :     if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || code[41] != 0) key = CKey();
                   +  + ]
     407                 :      117980 : }
     408                 :             : 
     409                 :           0 : KeyPair::KeyPair(const CKey& key, const uint256* merkle_root)
     410                 :             : {
     411                 :             :     static_assert(std::tuple_size<KeyType>() == sizeof(secp256k1_keypair));
     412         [ #  # ]:           0 :     MakeKeyPairData();
     413                 :           0 :     auto keypair = reinterpret_cast<secp256k1_keypair*>(m_keypair->data());
     414   [ #  #  #  #  :           0 :     bool success = secp256k1_keypair_create(secp256k1_context_sign, keypair, UCharCast(key.data()));
                   #  # ]
     415   [ #  #  #  # ]:           0 :     if (success && merkle_root) {
     416                 :           0 :         secp256k1_xonly_pubkey pubkey;
     417                 :           0 :         unsigned char pubkey_bytes[32];
     418   [ #  #  #  # ]:           0 :         assert(secp256k1_keypair_xonly_pub(secp256k1_context_sign, &pubkey, nullptr, keypair));
     419   [ #  #  #  # ]:           0 :         assert(secp256k1_xonly_pubkey_serialize(secp256k1_context_sign, pubkey_bytes, &pubkey));
     420   [ #  #  #  #  :           0 :         uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
             #  #  #  # ]
     421   [ #  #  #  # ]:           0 :         success = secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, keypair, tweak.data());
     422                 :           0 :     }
     423   [ #  #  #  # ]:           0 :     if (!success) ClearKeyPairData();
     424                 :           0 : }
     425                 :             : 
     426                 :           0 : bool KeyPair::SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256& aux) const
     427                 :             : {
     428         [ #  # ]:           0 :     assert(sig.size() == 64);
     429         [ #  # ]:           0 :     if (!IsValid()) return false;
     430                 :           0 :     auto keypair = reinterpret_cast<const secp256k1_keypair*>(m_keypair->data());
     431                 :           0 :     bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), keypair, aux.data());
     432         [ #  # ]:           0 :     if (ret) {
     433                 :             :         // Additional verification step to prevent using a potentially corrupted signature
     434                 :           0 :         secp256k1_xonly_pubkey pubkey_verify;
     435                 :           0 :         ret = secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey_verify, nullptr, keypair);
     436                 :           0 :         ret &= secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), hash.begin(), 32, &pubkey_verify);
     437                 :           0 :     }
     438         [ #  # ]:           0 :     if (!ret) memory_cleanse(sig.data(), sig.size());
     439                 :           0 :     return ret;
     440                 :           0 : }
     441                 :             : 
     442                 :           0 : bool ECC_InitSanityCheck() {
     443                 :           0 :     CKey key = GenerateRandomKey();
     444         [ #  # ]:           0 :     CPubKey pubkey = key.GetPubKey();
     445         [ #  # ]:           0 :     return key.VerifyPubKey(pubkey);
     446                 :           0 : }
     447                 :             : 
     448                 :             : /** Initialize the elliptic curve support. May not be called twice without calling ECC_Stop first. */
     449                 :        1923 : static void ECC_Start() {
     450         [ +  - ]:        1923 :     assert(secp256k1_context_sign == nullptr);
     451                 :             : 
     452                 :        1923 :     secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
     453         [ +  - ]:        1923 :     assert(ctx != nullptr);
     454                 :             : 
     455                 :             :     {
     456                 :             :         // Pass in a random blinding seed to the secp256k1 context.
     457                 :        1923 :         std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
     458         [ +  - ]:        1923 :         GetRandBytes(vseed);
     459         [ +  - ]:        1923 :         bool ret = secp256k1_context_randomize(ctx, vseed.data());
     460         [ +  - ]:        1923 :         assert(ret);
     461                 :        1923 :     }
     462                 :             : 
     463                 :        1923 :     secp256k1_context_sign = ctx;
     464                 :        1923 : }
     465                 :             : 
     466                 :             : /** Deinitialize the elliptic curve support. No-op if ECC_Start wasn't called first. */
     467                 :        2018 : static void ECC_Stop() {
     468                 :        2018 :     secp256k1_context *ctx = secp256k1_context_sign;
     469                 :        2018 :     secp256k1_context_sign = nullptr;
     470                 :             : 
     471         [ -  + ]:        2018 :     if (ctx) {
     472                 :        2018 :         secp256k1_context_destroy(ctx);
     473                 :        2018 :     }
     474                 :        2018 : }
     475                 :             : 
     476                 :        1923 : ECC_Context::ECC_Context()
     477                 :             : {
     478                 :        1923 :     ECC_Start();
     479                 :        1923 : }
     480                 :             : 
     481                 :        2018 : ECC_Context::~ECC_Context()
     482                 :             : {
     483         [ +  - ]:        2018 :     ECC_Stop();
     484                 :        2018 : }
        

Generated by: LCOV version 2.0-1