LCOV - code coverage report
Current view: top level - src - key.cpp (source / functions) Hit Total Coverage
Test: fuzz_coverage.info Lines: 247 276 89.5 %
Date: 2023-10-05 15:40:34 Functions: 22 24 91.7 %
Branches: 127 232 54.7 %

           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                 :        103 : int ec_seckey_import_der(const secp256k1_context* ctx, unsigned char *out32, const unsigned char *seckey, size_t seckeylen) {
      39                 :        103 :     const unsigned char *end = seckey + seckeylen;
      40                 :        103 :     memset(out32, 0, 32);
      41                 :            :     /* sequence header */
      42   [ +  -  +  + ]:        103 :     if (end - seckey < 1 || *seckey != 0x30u) {
      43                 :          1 :         return 0;
      44                 :            :     }
      45                 :        102 :     seckey++;
      46                 :            :     /* sequence length constructor */
      47   [ +  -  +  + ]:        102 :     if (end - seckey < 1 || !(*seckey & 0x80u)) {
      48                 :          1 :         return 0;
      49                 :            :     }
      50                 :        101 :     ptrdiff_t lenb = *seckey & ~0x80u; seckey++;
      51   [ +  -  +  + ]:        101 :     if (lenb < 1 || lenb > 2) {
      52                 :          1 :         return 0;
      53                 :            :     }
      54         [ -  + ]:        100 :     if (end - seckey < lenb) {
      55                 :          0 :         return 0;
      56                 :            :     }
      57                 :            :     /* sequence length */
      58         [ +  + ]:        100 :     ptrdiff_t len = seckey[lenb-1] | (lenb > 1 ? seckey[lenb-2] << 8 : 0u);
      59                 :        100 :     seckey += lenb;
      60         [ +  + ]:        100 :     if (end - seckey < len) {
      61                 :          1 :         return 0;
      62                 :            :     }
      63                 :            :     /* sequence element 0: version number (=1) */
      64   [ +  -  +  +  :         99 :     if (end - seckey < 3 || seckey[0] != 0x02u || seckey[1] != 0x01u || seckey[2] != 0x01u) {
             +  +  +  + ]
      65                 :          4 :         return 0;
      66                 :            :     }
      67                 :         95 :     seckey += 3;
      68                 :            :     /* sequence element 1: octet string, up to 32 bytes */
      69   [ +  -  +  + ]:         95 :     if (end - seckey < 2 || seckey[0] != 0x04u) {
      70                 :          1 :         return 0;
      71                 :            :     }
      72                 :         94 :     ptrdiff_t oslen = seckey[1];
      73                 :         94 :     seckey += 2;
      74   [ +  +  -  + ]:         94 :     if (oslen > 32 || end - seckey < oslen) {
      75                 :          1 :         return 0;
      76                 :            :     }
      77                 :         93 :     memcpy(out32 + (32 - oslen), seckey, oslen);
      78         [ +  + ]:         93 :     if (!secp256k1_ec_seckey_verify(ctx, out32)) {
      79                 :          1 :         memset(out32, 0, 32);
      80                 :          1 :         return 0;
      81                 :            :     }
      82                 :         92 :     return 1;
      83                 :        103 : }
      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                 :         56 : int ec_seckey_export_der(const secp256k1_context *ctx, unsigned char *seckey, size_t *seckeylen, const unsigned char *key32, bool compressed) {
      96         [ +  - ]:         56 :     assert(*seckeylen >= CKey::SIZE);
      97                 :            :     secp256k1_pubkey pubkey;
      98                 :         56 :     size_t pubkeylen = 0;
      99         [ +  + ]:         56 :     if (!secp256k1_ec_pubkey_create(ctx, &pubkey, key32)) {
     100                 :          9 :         *seckeylen = 0;
     101                 :          9 :         return 0;
     102                 :            :     }
     103         [ +  + ]:         47 :     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                 :         46 :         unsigned char *ptr = seckey;
     119                 :         46 :         memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
     120                 :         46 :         memcpy(ptr, key32, 32); ptr += 32;
     121                 :         46 :         memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
     122                 :         46 :         pubkeylen = CPubKey::COMPRESSED_SIZE;
     123                 :         46 :         secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_COMPRESSED);
     124                 :         46 :         ptr += pubkeylen;
     125                 :         46 :         *seckeylen = ptr - seckey;
     126         [ -  + ]:         46 :         assert(*seckeylen == CKey::COMPRESSED_SIZE);
     127                 :         46 :     } 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                 :          1 :         unsigned char *ptr = seckey;
     145                 :          1 :         memcpy(ptr, begin, sizeof(begin)); ptr += sizeof(begin);
     146                 :          1 :         memcpy(ptr, key32, 32); ptr += 32;
     147                 :          1 :         memcpy(ptr, middle, sizeof(middle)); ptr += sizeof(middle);
     148                 :          1 :         pubkeylen = CPubKey::SIZE;
     149                 :          1 :         secp256k1_ec_pubkey_serialize(ctx, ptr, &pubkeylen, &pubkey, SECP256K1_EC_UNCOMPRESSED);
     150                 :          1 :         ptr += pubkeylen;
     151                 :          1 :         *seckeylen = ptr - seckey;
     152         [ -  + ]:          1 :         assert(*seckeylen == CKey::SIZE);
     153                 :            :     }
     154                 :         47 :     return 1;
     155                 :         56 : }
     156                 :            : 
     157                 :     105652 : bool CKey::Check(const unsigned char *vch) {
     158                 :     105652 :     return secp256k1_ec_seckey_verify(secp256k1_context_sign, vch);
     159                 :            : }
     160                 :            : 
     161                 :          1 : void CKey::MakeNewKey(bool fCompressedIn) {
     162                 :          1 :     MakeKeyData();
     163                 :          1 :     do {
     164                 :          1 :         GetStrongRandBytes(*keydata);
     165         [ -  + ]:          1 :     } while (!Check(keydata->data()));
     166                 :          1 :     fCompressed = fCompressedIn;
     167                 :          1 : }
     168                 :            : 
     169                 :         88 : bool CKey::Negate()
     170                 :            : {
     171         [ +  - ]:         88 :     assert(keydata);
     172                 :         88 :     return secp256k1_ec_seckey_negate(secp256k1_context_sign, keydata->data());
     173                 :            : }
     174                 :            : 
     175                 :         44 : CPrivKey CKey::GetPrivKey() const {
     176         [ +  - ]:         44 :     assert(keydata);
     177                 :         44 :     CPrivKey seckey;
     178                 :            :     int ret;
     179                 :            :     size_t seckeylen;
     180         [ +  - ]:         44 :     seckey.resize(SIZE);
     181                 :         44 :     seckeylen = SIZE;
     182   [ +  -  +  - ]:         44 :     ret = ec_seckey_export_der(secp256k1_context_sign, seckey.data(), &seckeylen, begin(), fCompressed);
     183         [ -  + ]:         44 :     assert(ret);
     184         [ +  - ]:         44 :     seckey.resize(seckeylen);
     185                 :         44 :     return seckey;
     186         [ +  - ]:         44 : }
     187                 :            : 
     188                 :     167631 : CPubKey CKey::GetPubKey() const {
     189         [ +  - ]:     167631 :     assert(keydata);
     190                 :            :     secp256k1_pubkey pubkey;
     191                 :     167631 :     size_t clen = CPubKey::SIZE;
     192                 :     167631 :     CPubKey result;
     193                 :     167631 :     int ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pubkey, begin());
     194         [ +  - ]:     167631 :     assert(ret);
     195                 :     167631 :     secp256k1_ec_pubkey_serialize(secp256k1_context_sign, (unsigned char*)result.begin(), &clen, &pubkey, fCompressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
     196         [ +  - ]:     167631 :     assert(result.size() == clen);
     197         [ +  - ]:     167631 :     assert(result.IsValid());
     198                 :     167631 :     return result;
     199                 :            : }
     200                 :            : 
     201                 :            : // Check that the sig has a low R value and will be less than 71 bytes
     202                 :       2058 : bool SigHasLowR(const secp256k1_ecdsa_signature* sig)
     203                 :            : {
     204                 :            :     unsigned char compact_sig[64];
     205                 :       2058 :     secp256k1_ecdsa_signature_serialize_compact(secp256k1_context_sign, compact_sig, sig);
     206                 :            : 
     207                 :            :     // In DER serialization, all values are interpreted as big-endian, signed integers. The highest bit in the integer indicates
     208                 :            :     // its signed-ness; 0 is positive, 1 is negative. When the value is interpreted as a negative integer, it must be converted
     209                 :            :     // to a positive value by prepending a 0x00 byte so that the highest bit is 0. We can avoid this prepending by ensuring that
     210                 :            :     // our highest bit is always 0, and thus we must check that the first byte is less than 0x80.
     211                 :       2058 :     return compact_sig[0] < 0x80;
     212                 :            : }
     213                 :            : 
     214                 :       1029 : bool CKey::Sign(const uint256 &hash, std::vector<unsigned char>& vchSig, bool grind, uint32_t test_case) const {
     215         [ -  + ]:       1029 :     if (!keydata)
     216                 :          0 :         return false;
     217                 :       1029 :     vchSig.resize(CPubKey::SIGNATURE_SIZE);
     218                 :       1029 :     size_t nSigLen = CPubKey::SIGNATURE_SIZE;
     219                 :       1029 :     unsigned char extra_entropy[32] = {0};
     220                 :       1029 :     WriteLE32(extra_entropy, test_case);
     221                 :            :     secp256k1_ecdsa_signature sig;
     222                 :       1029 :     uint32_t counter = 0;
     223   [ +  +  +  - ]:       1029 :     int ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, (!grind && test_case) ? extra_entropy : nullptr);
     224                 :            : 
     225                 :            :     // Grind for low R
     226   [ +  -  +  +  :       2042 :     while (ret && !SigHasLowR(&sig) && grind) {
                   +  + ]
     227                 :       1013 :         WriteLE32(extra_entropy, ++counter);
     228                 :       1013 :         ret = secp256k1_ecdsa_sign(secp256k1_context_sign, &sig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, extra_entropy);
     229                 :            :     }
     230         [ +  - ]:       1029 :     assert(ret);
     231                 :       1029 :     secp256k1_ecdsa_signature_serialize_der(secp256k1_context_sign, vchSig.data(), &nSigLen, &sig);
     232                 :       1029 :     vchSig.resize(nSigLen);
     233                 :            :     // Additional verification step to prevent using a potentially corrupted signature
     234                 :            :     secp256k1_pubkey pk;
     235                 :       1029 :     ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &pk, begin());
     236         [ +  - ]:       1029 :     assert(ret);
     237                 :       1029 :     ret = secp256k1_ecdsa_verify(secp256k1_context_static, &sig, hash.begin(), &pk);
     238         [ -  + ]:       1029 :     assert(ret);
     239                 :       1029 :     return true;
     240                 :       1029 : }
     241                 :            : 
     242                 :        168 : bool CKey::VerifyPubKey(const CPubKey& pubkey) const {
     243         [ -  + ]:        168 :     if (pubkey.IsCompressed() != fCompressed) {
     244                 :          0 :         return false;
     245                 :            :     }
     246                 :            :     unsigned char rnd[8];
     247         [ +  - ]:        168 :     std::string str = "Bitcoin key verification\n";
     248                 :        168 :     GetRandBytes(rnd);
     249         [ -  + ]:        168 :     uint256 hash{Hash(str, rnd)};
     250                 :        168 :     std::vector<unsigned char> vchSig;
     251         [ +  - ]:        168 :     Sign(hash, vchSig);
     252         [ +  - ]:        168 :     return pubkey.Verify(hash, vchSig);
     253                 :        168 : }
     254                 :            : 
     255                 :        135 : bool CKey::SignCompact(const uint256 &hash, std::vector<unsigned char>& vchSig) const {
     256         [ +  + ]:        135 :     if (!keydata)
     257                 :         15 :         return false;
     258                 :        120 :     vchSig.resize(CPubKey::COMPACT_SIGNATURE_SIZE);
     259                 :        120 :     int rec = -1;
     260                 :            :     secp256k1_ecdsa_recoverable_signature rsig;
     261                 :        120 :     int ret = secp256k1_ecdsa_sign_recoverable(secp256k1_context_sign, &rsig, hash.begin(), begin(), secp256k1_nonce_function_rfc6979, nullptr);
     262         [ +  - ]:        120 :     assert(ret);
     263                 :        120 :     ret = secp256k1_ecdsa_recoverable_signature_serialize_compact(secp256k1_context_sign, &vchSig[1], &rec, &rsig);
     264         [ +  - ]:        120 :     assert(ret);
     265         [ +  - ]:        120 :     assert(rec != -1);
     266                 :        120 :     vchSig[0] = 27 + rec + (fCompressed ? 4 : 0);
     267                 :            :     // Additional verification step to prevent using a potentially corrupted signature
     268                 :            :     secp256k1_pubkey epk, rpk;
     269                 :        120 :     ret = secp256k1_ec_pubkey_create(secp256k1_context_sign, &epk, begin());
     270         [ +  - ]:        120 :     assert(ret);
     271                 :        120 :     ret = secp256k1_ecdsa_recover(secp256k1_context_static, &rpk, &rsig, hash.begin());
     272         [ +  - ]:        120 :     assert(ret);
     273                 :        120 :     ret = secp256k1_ec_pubkey_cmp(secp256k1_context_static, &epk, &rpk);
     274         [ -  + ]:        120 :     assert(ret == 0);
     275                 :        120 :     return true;
     276                 :        135 : }
     277                 :            : 
     278                 :          0 : bool CKey::SignSchnorr(const uint256& hash, Span<unsigned char> sig, const uint256* merkle_root, const uint256& aux) const
     279                 :            : {
     280         [ #  # ]:          0 :     assert(sig.size() == 64);
     281                 :            :     secp256k1_keypair keypair;
     282         [ #  # ]:          0 :     if (!secp256k1_keypair_create(secp256k1_context_sign, &keypair, begin())) return false;
     283         [ #  # ]:          0 :     if (merkle_root) {
     284                 :            :         secp256k1_xonly_pubkey pubkey;
     285         [ #  # ]:          0 :         if (!secp256k1_keypair_xonly_pub(secp256k1_context_sign, &pubkey, nullptr, &keypair)) return false;
     286                 :            :         unsigned char pubkey_bytes[32];
     287         [ #  # ]:          0 :         if (!secp256k1_xonly_pubkey_serialize(secp256k1_context_sign, pubkey_bytes, &pubkey)) return false;
     288         [ #  # ]:          0 :         uint256 tweak = XOnlyPubKey(pubkey_bytes).ComputeTapTweakHash(merkle_root->IsNull() ? nullptr : merkle_root);
     289         [ #  # ]:          0 :         if (!secp256k1_keypair_xonly_tweak_add(secp256k1_context_static, &keypair, tweak.data())) return false;
     290                 :          0 :     }
     291                 :          0 :     bool ret = secp256k1_schnorrsig_sign32(secp256k1_context_sign, sig.data(), hash.data(), &keypair, aux.data());
     292         [ #  # ]:          0 :     if (ret) {
     293                 :            :         // Additional verification step to prevent using a potentially corrupted signature
     294                 :            :         secp256k1_xonly_pubkey pubkey_verify;
     295                 :          0 :         ret = secp256k1_keypair_xonly_pub(secp256k1_context_static, &pubkey_verify, nullptr, &keypair);
     296                 :          0 :         ret &= secp256k1_schnorrsig_verify(secp256k1_context_static, sig.data(), hash.begin(), 32, &pubkey_verify);
     297                 :          0 :     }
     298         [ #  # ]:          0 :     if (!ret) memory_cleanse(sig.data(), sig.size());
     299                 :          0 :     memory_cleanse(&keypair, sizeof(keypair));
     300                 :          0 :     return ret;
     301                 :          0 : }
     302                 :            : 
     303                 :         88 : bool CKey::Load(const CPrivKey &seckey, const CPubKey &vchPubKey, bool fSkipCheck=false) {
     304                 :         88 :     MakeKeyData();
     305         [ +  - ]:         88 :     if (!ec_seckey_import_der(secp256k1_context_sign, (unsigned char*)begin(), seckey.data(), seckey.size())) {
     306                 :          0 :         ClearKeyData();
     307                 :          0 :         return false;
     308                 :            :     }
     309                 :         88 :     fCompressed = vchPubKey.IsCompressed();
     310                 :            : 
     311         [ +  + ]:         88 :     if (fSkipCheck)
     312                 :         44 :         return true;
     313                 :            : 
     314                 :         44 :     return VerifyPubKey(vchPubKey);
     315                 :         88 : }
     316                 :            : 
     317                 :      78435 : bool CKey::Derive(CKey& keyChild, ChainCode &ccChild, unsigned int nChild, const ChainCode& cc) const {
     318         [ +  - ]:      78435 :     assert(IsValid());
     319         [ +  - ]:      78435 :     assert(IsCompressed());
     320                 :      78435 :     std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
     321         [ +  + ]:      78435 :     if ((nChild >> 31) == 0) {
     322         [ +  - ]:      67972 :         CPubKey pubkey = GetPubKey();
     323   [ +  -  -  + ]:      67972 :         assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
     324   [ +  -  +  -  :      67972 :         BIP32Hash(cc, nChild, *pubkey.begin(), pubkey.begin()+1, vout.data());
                   +  - ]
     325                 :      67972 :     } else {
     326   [ +  -  +  - ]:      10463 :         assert(size() == 32);
     327   [ +  -  +  - ]:      10463 :         BIP32Hash(cc, nChild, 0, begin(), vout.data());
     328                 :            :     }
     329         [ +  - ]:      78435 :     memcpy(ccChild.begin(), vout.data()+32, 32);
     330   [ +  -  +  -  :      78435 :     keyChild.Set(begin(), begin() + 32, true);
                   +  - ]
     331   [ +  -  +  - ]:      78435 :     bool ret = secp256k1_ec_seckey_tweak_add(secp256k1_context_sign, (unsigned char*)keyChild.begin(), vout.data());
     332   [ -  +  #  # ]:      78435 :     if (!ret) keyChild.ClearKeyData();
     333                 :      78435 :     return ret;
     334                 :      78435 : }
     335                 :            : 
     336                 :       1411 : EllSwiftPubKey CKey::EllSwiftCreate(Span<const std::byte> ent32) const
     337                 :            : {
     338         [ +  - ]:       1411 :     assert(keydata);
     339         [ +  - ]:       1411 :     assert(ent32.size() == 32);
     340                 :            :     std::array<std::byte, EllSwiftPubKey::size()> encoded_pubkey;
     341                 :            : 
     342                 :       2822 :     auto success = secp256k1_ellswift_create(secp256k1_context_sign,
     343                 :       1411 :                                              UCharCast(encoded_pubkey.data()),
     344                 :       1411 :                                              keydata->data(),
     345                 :       1411 :                                              UCharCast(ent32.data()));
     346                 :            : 
     347                 :            :     // Should always succeed for valid keys (asserted above).
     348         [ +  - ]:       1411 :     assert(success);
     349                 :       1411 :     return {encoded_pubkey};
     350                 :            : }
     351                 :            : 
     352                 :       1112 : ECDHSecret CKey::ComputeBIP324ECDHSecret(const EllSwiftPubKey& their_ellswift, const EllSwiftPubKey& our_ellswift, bool initiating) const
     353                 :            : {
     354         [ +  - ]:       1112 :     assert(keydata);
     355                 :            : 
     356                 :            :     ECDHSecret output;
     357                 :            :     // BIP324 uses the initiator as party A, and the responder as party B. Remap the inputs
     358                 :            :     // accordingly:
     359                 :       2224 :     bool success = secp256k1_ellswift_xdh(secp256k1_context_sign,
     360                 :       1112 :                                           UCharCast(output.data()),
     361         [ +  + ]:       1112 :                                           UCharCast(initiating ? our_ellswift.data() : their_ellswift.data()),
     362         [ +  + ]:       1112 :                                           UCharCast(initiating ? their_ellswift.data() : our_ellswift.data()),
     363                 :       1112 :                                           keydata->data(),
     364                 :       1112 :                                           initiating ? 0 : 1,
     365                 :       1112 :                                           secp256k1_ellswift_xdh_hash_function_bip324,
     366                 :            :                                           nullptr);
     367                 :            :     // Should always succeed for valid keys (assert above).
     368         [ -  + ]:       1112 :     assert(success);
     369                 :       1112 :     return output;
     370                 :            : }
     371                 :            : 
     372                 :      78437 : bool CExtKey::Derive(CExtKey &out, unsigned int _nChild) const {
     373         [ +  + ]:      78437 :     if (nDepth == std::numeric_limits<unsigned char>::max()) return false;
     374                 :      78391 :     out.nDepth = nDepth + 1;
     375                 :      78391 :     CKeyID id = key.GetPubKey().GetID();
     376                 :      78391 :     memcpy(out.vchFingerprint, &id, 4);
     377                 :      78391 :     out.nChild = _nChild;
     378                 :      78391 :     return key.Derive(out.key, out.chaincode, _nChild, chaincode);
     379                 :      78437 : }
     380                 :            : 
     381                 :         84 : void CExtKey::SetSeed(Span<const std::byte> seed)
     382                 :            : {
     383                 :            :     static const unsigned char hashkey[] = {'B','i','t','c','o','i','n',' ','s','e','e','d'};
     384                 :         84 :     std::vector<unsigned char, secure_allocator<unsigned char>> vout(64);
     385   [ +  -  +  -  :         84 :     CHMAC_SHA512{hashkey, sizeof(hashkey)}.Write(UCharCast(seed.data()), seed.size()).Finalize(vout.data());
             +  -  +  - ]
     386         [ +  - ]:         84 :     key.Set(vout.data(), vout.data() + 32, true);
     387         [ +  - ]:         84 :     memcpy(chaincode.begin(), vout.data() + 32, 32);
     388                 :         84 :     nDepth = 0;
     389                 :         84 :     nChild = 0;
     390                 :         84 :     memset(vchFingerprint, 0, sizeof(vchFingerprint));
     391                 :         84 : }
     392                 :            : 
     393                 :       9614 : CExtPubKey CExtKey::Neuter() const {
     394                 :       9614 :     CExtPubKey ret;
     395                 :       9614 :     ret.nDepth = nDepth;
     396                 :       9614 :     memcpy(ret.vchFingerprint, vchFingerprint, 4);
     397                 :       9614 :     ret.nChild = nChild;
     398                 :       9614 :     ret.pubkey = key.GetPubKey();
     399                 :       9614 :     ret.chaincode = chaincode;
     400                 :       9614 :     return ret;
     401                 :            : }
     402                 :            : 
     403                 :       1174 : void CExtKey::Encode(unsigned char code[BIP32_EXTKEY_SIZE]) const {
     404                 :       1174 :     code[0] = nDepth;
     405                 :       1174 :     memcpy(code+1, vchFingerprint, 4);
     406                 :       1174 :     WriteBE32(code+5, nChild);
     407                 :       1174 :     memcpy(code+9, chaincode.begin(), 32);
     408                 :       1174 :     code[41] = 0;
     409         [ +  - ]:       1174 :     assert(key.size() == 32);
     410                 :       1174 :     memcpy(code+42, key.begin(), 32);
     411                 :       1174 : }
     412                 :            : 
     413                 :       7095 : void CExtKey::Decode(const unsigned char code[BIP32_EXTKEY_SIZE]) {
     414                 :       7095 :     nDepth = code[0];
     415                 :       7095 :     memcpy(vchFingerprint, code+1, 4);
     416                 :       7095 :     nChild = ReadBE32(code+5);
     417                 :       7095 :     memcpy(chaincode.begin(), code+9, 32);
     418                 :       7095 :     key.Set(code+42, code+BIP32_EXTKEY_SIZE, true);
     419   [ +  +  +  -  :       7095 :     if ((nDepth == 0 && (nChild != 0 || ReadLE32(vchFingerprint) != 0)) || code[41] != 0) key = CKey();
                   +  + ]
     420                 :       2175 : }
     421                 :            : 
     422                 :          0 : bool ECC_InitSanityCheck() {
     423                 :          0 :     CKey key;
     424         [ #  # ]:          0 :     key.MakeNewKey(true);
     425         [ #  # ]:          0 :     CPubKey pubkey = key.GetPubKey();
     426         [ #  # ]:          0 :     return key.VerifyPubKey(pubkey);
     427                 :          0 : }
     428                 :            : 
     429                 :        921 : void ECC_Start() {
     430         [ +  - ]:        921 :     assert(secp256k1_context_sign == nullptr);
     431                 :            : 
     432                 :        921 :     secp256k1_context *ctx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
     433         [ +  - ]:        921 :     assert(ctx != nullptr);
     434                 :            : 
     435                 :            :     {
     436                 :            :         // Pass in a random blinding seed to the secp256k1 context.
     437                 :        921 :         std::vector<unsigned char, secure_allocator<unsigned char>> vseed(32);
     438         [ +  - ]:        921 :         GetRandBytes(vseed);
     439         [ +  - ]:        921 :         bool ret = secp256k1_context_randomize(ctx, vseed.data());
     440         [ +  - ]:        921 :         assert(ret);
     441                 :        921 :     }
     442                 :            : 
     443                 :        921 :     secp256k1_context_sign = ctx;
     444                 :        921 : }
     445                 :            : 
     446                 :        905 : void ECC_Stop() {
     447                 :        905 :     secp256k1_context *ctx = secp256k1_context_sign;
     448                 :        905 :     secp256k1_context_sign = nullptr;
     449                 :            : 
     450         [ +  - ]:        905 :     if (ctx) {
     451                 :        905 :         secp256k1_context_destroy(ctx);
     452                 :        905 :     }
     453                 :        905 : }

Generated by: LCOV version 1.14