LCOV - code coverage report
Current view: top level - src - key_io.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 98.5 % 202 199
Test Date: 2024-09-01 05:20:30 Functions: 100.0 % 26 26
Branches: 62.9 % 348 219

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2014-2021 The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #include <key_io.h>
       6                 :             : 
       7                 :             : #include <base58.h>
       8                 :             : #include <bech32.h>
       9                 :             : #include <script/interpreter.h>
      10                 :             : #include <script/solver.h>
      11                 :             : #include <tinyformat.h>
      12                 :             : #include <util/strencodings.h>
      13                 :             : 
      14                 :             : #include <algorithm>
      15                 :             : #include <assert.h>
      16                 :             : #include <string.h>
      17                 :             : 
      18                 :             : /// Maximum witness length for Bech32 addresses.
      19                 :             : static constexpr std::size_t BECH32_WITNESS_PROG_MAX_LEN = 40;
      20                 :             : 
      21                 :             : namespace {
      22                 :             : class DestinationEncoder
      23                 :             : {
      24                 :             : private:
      25                 :             :     const CChainParams& m_params;
      26                 :             : 
      27                 :             : public:
      28                 :     1041659 :     explicit DestinationEncoder(const CChainParams& params) : m_params(params) {}
      29                 :             : 
      30                 :      136513 :     std::string operator()(const PKHash& id) const
      31                 :             :     {
      32                 :      136513 :         std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
      33   [ +  -  +  -  :      136513 :         data.insert(data.end(), id.begin(), id.end());
                   +  - ]
      34   [ +  -  +  - ]:      136513 :         return EncodeBase58Check(data);
      35                 :      136513 :     }
      36                 :             : 
      37                 :      532986 :     std::string operator()(const ScriptHash& id) const
      38                 :             :     {
      39                 :      532986 :         std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
      40   [ +  -  +  -  :      532986 :         data.insert(data.end(), id.begin(), id.end());
                   +  - ]
      41   [ +  -  +  - ]:      532986 :         return EncodeBase58Check(data);
      42                 :      532986 :     }
      43                 :             : 
      44                 :      130703 :     std::string operator()(const WitnessV0KeyHash& id) const
      45                 :             :     {
      46         [ +  - ]:      130703 :         std::vector<unsigned char> data = {0};
      47         [ +  - ]:      130703 :         data.reserve(33);
      48   [ +  -  +  -  :     4313199 :         ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
                   +  - ]
      49         [ +  - ]:      130703 :         return bech32::Encode(bech32::Encoding::BECH32, m_params.Bech32HRP(), data);
      50                 :      130703 :     }
      51                 :             : 
      52                 :      107297 :     std::string operator()(const WitnessV0ScriptHash& id) const
      53                 :             :     {
      54         [ +  - ]:      107297 :         std::vector<unsigned char> data = {0};
      55         [ +  - ]:      107297 :         data.reserve(53);
      56   [ +  -  +  -  :     5686741 :         ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
                   +  - ]
      57   [ +  -  +  - ]:      107297 :         return bech32::Encode(bech32::Encoding::BECH32, m_params.Bech32HRP(), data);
      58                 :      107297 :     }
      59                 :             : 
      60                 :       79464 :     std::string operator()(const WitnessV1Taproot& tap) const
      61                 :             :     {
      62         [ +  - ]:       79464 :         std::vector<unsigned char> data = {1};
      63         [ +  - ]:       79464 :         data.reserve(53);
      64   [ +  -  +  -  :     4211592 :         ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, tap.begin(), tap.end());
                   +  - ]
      65         [ +  - ]:       79464 :         return bech32::Encode(bech32::Encoding::BECH32M, m_params.Bech32HRP(), data);
      66                 :       79464 :     }
      67                 :             : 
      68                 :       49111 :     std::string operator()(const WitnessUnknown& id) const
      69                 :             :     {
      70                 :       49111 :         const std::vector<unsigned char>& program = id.GetWitnessProgram();
      71   [ +  -  +  -  :       49111 :         if (id.GetWitnessVersion() < 1 || id.GetWitnessVersion() > 16 || program.size() < 2 || program.size() > 40) {
             +  -  -  + ]
      72                 :           0 :             return {};
      73                 :             :         }
      74         [ +  - ]:       49111 :         std::vector<unsigned char> data = {(unsigned char)id.GetWitnessVersion()};
      75         [ +  - ]:       49111 :         data.reserve(1 + (program.size() * 8 + 4) / 5);
      76         [ +  - ]:     1290966 :         ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, program.begin(), program.end());
      77         [ +  - ]:       49111 :         return bech32::Encode(bech32::Encoding::BECH32M, m_params.Bech32HRP(), data);
      78                 :       49111 :     }
      79                 :             : 
      80                 :        3276 :     std::string operator()(const CNoDestination& no) const { return {}; }
      81                 :        2309 :     std::string operator()(const PubKeyDestination& pk) const { return {}; }
      82                 :             : };
      83                 :             : 
      84                 :        8003 : CTxDestination DecodeDestination(const std::string& str, const CChainParams& params, std::string& error_str, std::vector<int>* error_locations)
      85                 :             : {
      86                 :        8003 :     std::vector<unsigned char> data;
      87         [ +  + ]:        8003 :     uint160 hash;
      88         [ +  + ]:        7943 :     error_str = "";
      89                 :             : 
      90                 :             :     // Note this will be false if it is a valid Bech32 address for a different network
      91   [ +  -  +  - ]:        8003 :     bool is_bech32 = (ToLower(str.substr(0, params.Bech32HRP().size())) == params.Bech32HRP());
      92                 :             : 
      93   [ +  +  +  -  :        8003 :     if (!is_bech32 && DecodeBase58Check(str, data, 21)) {
                   +  + ]
      94                 :             :         // base58-encoded Bitcoin addresses.
      95                 :             :         // Public-key-hash-addresses have version 0 (or 111 testnet).
      96                 :             :         // The data vector contains RIPEMD160(SHA256(pubkey)), where pubkey is the serialized public key.
      97                 :        2165 :         const std::vector<unsigned char>& pubkey_prefix = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
      98   [ +  -  +  +  :        2165 :         if (data.size() == hash.size() + pubkey_prefix.size() && std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {
             +  -  +  + ]
      99   [ +  -  +  - ]:        1952 :             std::copy(data.begin() + pubkey_prefix.size(), data.end(), hash.begin());
     100         [ +  - ]:        1952 :             return PKHash(hash);
     101                 :             :         }
     102                 :             :         // Script-hash-addresses have version 5 (or 196 testnet).
     103                 :             :         // The data vector contains RIPEMD160(SHA256(cscript)), where cscript is the serialized redemption script.
     104                 :         213 :         const std::vector<unsigned char>& script_prefix = params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
     105   [ +  +  +  +  :         213 :         if (data.size() == hash.size() + script_prefix.size() && std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {
             +  -  +  + ]
     106   [ +  -  +  - ]:         120 :             std::copy(data.begin() + script_prefix.size(), data.end(), hash.begin());
     107         [ +  - ]:         120 :             return ScriptHash(hash);
     108                 :             :         }
     109                 :             : 
     110                 :             :         // If the prefix of data matches either the script or pubkey prefix, the length must have been wrong
     111         [ +  + ]:          64 :         if ((data.size() >= script_prefix.size() &&
     112         [ +  - ]:          32 :                 std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) ||
     113         [ +  + ]:           1 :             (data.size() >= pubkey_prefix.size() &&
     114         [ +  - ]:          31 :                 std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin()))) {
     115         [ +  + ]:          63 :             error_str = "Invalid length for Base58 address (P2PKH or P2SH)";
     116                 :           3 :         } else {
     117         [ +  - ]:          30 :             error_str = "Invalid or unsupported Base58-encoded address.";
     118                 :             :         }
     119                 :          33 :         return CNoDestination();
     120         [ +  + ]:        7943 :     } else if (!is_bech32) {
     121                 :             :         // Try Base58 decoding without the checksum, using a much larger max length
     122   [ +  -  +  + ]:        3796 :         if (!DecodeBase58(str, data, 100)) {
     123         [ +  - ]:         427 :             error_str = "Invalid or unsupported Segwit (Bech32) or Base58 encoding.";
     124                 :         427 :         } else {
     125         [ +  - ]:        3369 :             error_str = "Invalid checksum or length of Base58 address (P2PKH or P2SH)";
     126                 :             :         }
     127                 :        3796 :         return CNoDestination();
     128                 :             :     }
     129                 :             : 
     130                 :        2042 :     data.clear();
     131         [ +  - ]:        2042 :     const auto dec = bech32::Decode(str);
     132   [ +  +  +  + ]:        2042 :     if (dec.encoding == bech32::Encoding::BECH32 || dec.encoding == bech32::Encoding::BECH32M) {
     133         [ +  + ]:         530 :         if (dec.data.empty()) {
     134         [ +  - ]:           6 :             error_str = "Empty Bech32 data section";
     135                 :           6 :             return CNoDestination();
     136                 :             :         }
     137                 :             :         // Bech32 decoding
     138         [ +  + ]:         524 :         if (dec.hrp != params.Bech32HRP()) {
     139         [ +  - ]:          16 :             error_str = strprintf("Invalid or unsupported prefix for Segwit (Bech32) address (expected %s, got %s).", params.Bech32HRP(), dec.hrp);
     140                 :          16 :             return CNoDestination();
     141                 :             :         }
     142                 :         508 :         int version = dec.data[0]; // The first 5 bit symbol is the witness version (0-16)
     143   [ +  +  +  + ]:         508 :         if (version == 0 && dec.encoding != bech32::Encoding::BECH32) {
     144         [ +  - ]:           3 :             error_str = "Version 0 witness address must use Bech32 checksum";
     145                 :           3 :             return CNoDestination();
     146                 :             :         }
     147   [ +  +  +  + ]:         505 :         if (version != 0 && dec.encoding != bech32::Encoding::BECH32M) {
     148         [ +  - ]:           5 :             error_str = "Version 1+ witness address must use Bech32m checksum";
     149                 :           5 :             return CNoDestination();
     150                 :             :         }
     151                 :             :         // The rest of the symbols are converted witness program bytes.
     152         [ +  - ]:         500 :         data.reserve(((dec.data.size() - 1) * 5) / 8);
     153   [ +  -  +  + ]:       11237 :         if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, dec.data.begin() + 1, dec.data.end())) {
     154                 :             : 
     155                 :         487 :             std::string_view byte_str{data.size() == 1 ? "byte" : "bytes"};
     156                 :             : 
     157         [ +  + ]:         487 :             if (version == 0) {
     158                 :             :                 {
     159         [ +  - ]:         123 :                     WitnessV0KeyHash keyid;
     160   [ +  -  +  + ]:         123 :                     if (data.size() == keyid.size()) {
     161   [ +  -  +  - ]:          53 :                         std::copy(data.begin(), data.end(), keyid.begin());
     162                 :          53 :                         return keyid;
     163                 :             :                     }
     164         [ +  + ]:         123 :                 }
     165                 :             :                 {
     166         [ +  - ]:          70 :                     WitnessV0ScriptHash scriptid;
     167   [ +  -  +  + ]:          70 :                     if (data.size() == scriptid.size()) {
     168   [ +  -  +  - ]:          64 :                         std::copy(data.begin(), data.end(), scriptid.begin());
     169                 :          64 :                         return scriptid;
     170                 :             :                     }
     171         [ +  + ]:          70 :                 }
     172                 :             : 
     173         [ +  - ]:           6 :                 error_str = strprintf("Invalid Bech32 v0 address program size (%d %s), per BIP141", data.size(), byte_str);
     174                 :           6 :                 return CNoDestination();
     175                 :             :             }
     176                 :             : 
     177   [ +  +  +  + ]:         364 :             if (version == 1 && data.size() == WITNESS_V1_TAPROOT_SIZE) {
     178                 :             :                 static_assert(WITNESS_V1_TAPROOT_SIZE == WitnessV1Taproot::size());
     179         [ +  - ]:         174 :                 WitnessV1Taproot tap;
     180   [ +  -  +  - ]:         174 :                 std::copy(data.begin(), data.end(), tap.begin());
     181                 :         174 :                 return tap;
     182                 :         174 :             }
     183                 :             : 
     184   [ +  -  +  + ]:         190 :             if (CScript::IsPayToAnchor(version, data)) {
     185         [ +  - ]:          67 :                 return PayToAnchor();
     186                 :             :             }
     187                 :             : 
     188         [ -  + ]:         123 :             if (version > 16) {
     189         [ #  # ]:           0 :                 error_str = "Invalid Bech32 address witness version";
     190                 :           0 :                 return CNoDestination();
     191                 :             :             }
     192                 :             : 
     193   [ +  -  +  + ]:         123 :             if (data.size() < 2 || data.size() > BECH32_WITNESS_PROG_MAX_LEN) {
     194         [ +  - ]:           2 :                 error_str = strprintf("Invalid Bech32 address program size (%d %s)", data.size(), byte_str);
     195                 :           2 :                 return CNoDestination();
     196                 :             :             }
     197                 :             : 
     198         [ +  - ]:         121 :             return WitnessUnknown{version, data};
     199                 :         487 :         } else {
     200         [ +  - ]:          13 :             error_str = strprintf("Invalid padding in Bech32 data section");
     201                 :          13 :             return CNoDestination();
     202                 :             :         }
     203                 :         508 :     }
     204                 :             : 
     205                 :             :     // Perform Bech32 error location
     206         [ +  - ]:        1512 :     auto res = bech32::LocateErrors(str);
     207         [ +  - ]:        1512 :     error_str = res.first;
     208         [ +  + ]:        1512 :     if (error_locations) *error_locations = std::move(res.second);
     209                 :        1512 :     return CNoDestination();
     210                 :        8183 : }
     211                 :             : } // namespace
     212                 :             : 
     213                 :       79599 : CKey DecodeSecret(const std::string& str)
     214                 :             : {
     215                 :       79599 :     CKey key;
     216                 :       79599 :     std::vector<unsigned char> data;
     217   [ +  -  +  + ]:       79599 :     if (DecodeBase58Check(str, data, 34)) {
     218   [ +  -  +  - ]:       45894 :         const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);
     219   [ +  +  +  +  :       91779 :         if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
             +  +  +  + ]
     220         [ +  - ]:       45885 :             std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {
     221                 :       45884 :             bool compressed = data.size() == 33 + privkey_prefix.size();
     222         [ +  - ]:       45884 :             key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);
     223                 :       45884 :         }
     224                 :       45894 :     }
     225         [ +  + ]:       79599 :     if (!data.empty()) {
     226         [ +  - ]:       45893 :         memory_cleanse(data.data(), data.size());
     227                 :       45893 :     }
     228                 :       79599 :     return key;
     229         [ +  - ]:       79599 : }
     230                 :             : 
     231                 :       14267 : std::string EncodeSecret(const CKey& key)
     232                 :             : {
     233         [ +  - ]:       14267 :     assert(key.IsValid());
     234                 :       14267 :     std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
     235   [ +  -  +  -  :       14267 :     data.insert(data.end(), UCharCast(key.begin()), UCharCast(key.end()));
          +  -  +  -  +  
                      - ]
     236   [ +  -  +  + ]:       14267 :     if (key.IsCompressed()) {
     237         [ +  - ]:       10445 :         data.push_back(1);
     238                 :       10445 :     }
     239   [ +  -  +  - ]:       14267 :     std::string ret = EncodeBase58Check(data);
     240         [ +  - ]:       14267 :     memory_cleanse(data.data(), data.size());
     241                 :       14267 :     return ret;
     242         [ +  - ]:       14267 : }
     243                 :             : 
     244                 :      155342 : CExtPubKey DecodeExtPubKey(const std::string& str)
     245                 :             : {
     246                 :      155342 :     CExtPubKey key;
     247                 :      155342 :     std::vector<unsigned char> data;
     248   [ +  -  +  + ]:      155342 :     if (DecodeBase58Check(str, data, 78)) {
     249   [ +  -  +  - ]:      154747 :         const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
     250   [ +  +  +  -  :      154747 :         if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
                   +  + ]
     251         [ +  - ]:       23512 :             key.Decode(data.data() + prefix.size());
     252                 :       23512 :         }
     253                 :      154747 :     }
     254                 :             :     return key;
     255                 :      155342 : }
     256                 :             : 
     257                 :     2425884 : std::string EncodeExtPubKey(const CExtPubKey& key)
     258                 :             : {
     259                 :     2425884 :     std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
     260                 :     2425884 :     size_t size = data.size();
     261         [ +  - ]:     2425884 :     data.resize(size + BIP32_EXTKEY_SIZE);
     262         [ +  - ]:     2425884 :     key.Encode(data.data() + size);
     263   [ +  -  +  - ]:     2425884 :     std::string ret = EncodeBase58Check(data);
     264                 :     2425884 :     return ret;
     265         [ +  - ]:     2425884 : }
     266                 :             : 
     267                 :      155342 : CExtKey DecodeExtKey(const std::string& str)
     268                 :             : {
     269                 :      155342 :     CExtKey key;
     270                 :      155342 :     std::vector<unsigned char> data;
     271   [ +  -  +  + ]:      155342 :     if (DecodeBase58Check(str, data, 78)) {
     272   [ +  -  +  - ]:      154747 :         const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
     273   [ +  +  +  -  :      154747 :         if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
                   +  + ]
     274         [ +  - ]:      131222 :             key.Decode(data.data() + prefix.size());
     275                 :      131222 :         }
     276                 :      154747 :     }
     277                 :      155342 :     return key;
     278         [ +  - ]:      155342 : }
     279                 :             : 
     280                 :       14988 : std::string EncodeExtKey(const CExtKey& key)
     281                 :             : {
     282                 :       14988 :     std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
     283                 :       14988 :     size_t size = data.size();
     284         [ +  - ]:       14988 :     data.resize(size + BIP32_EXTKEY_SIZE);
     285         [ +  - ]:       14988 :     key.Encode(data.data() + size);
     286   [ +  -  +  - ]:       14988 :     std::string ret = EncodeBase58Check(data);
     287         [ +  - ]:       14988 :     memory_cleanse(data.data(), data.size());
     288                 :       14988 :     return ret;
     289         [ +  - ]:       14988 : }
     290                 :             : 
     291                 :     1041659 : std::string EncodeDestination(const CTxDestination& dest)
     292                 :             : {
     293                 :     1041659 :     return std::visit(DestinationEncoder(Params()), dest);
     294                 :             : }
     295                 :             : 
     296                 :        6283 : CTxDestination DecodeDestination(const std::string& str, std::string& error_msg, std::vector<int>* error_locations)
     297                 :             : {
     298                 :        6283 :     return DecodeDestination(str, Params(), error_msg, error_locations);
     299                 :             : }
     300                 :             : 
     301                 :        6081 : CTxDestination DecodeDestination(const std::string& str)
     302                 :             : {
     303                 :        6081 :     std::string error_msg;
     304         [ +  - ]:        6081 :     return DecodeDestination(str, error_msg);
     305                 :        6081 : }
     306                 :             : 
     307                 :        1660 : bool IsValidDestinationString(const std::string& str, const CChainParams& params)
     308                 :             : {
     309                 :        1660 :     std::string error_msg;
     310   [ +  -  +  - ]:        1660 :     return IsValidDestination(DecodeDestination(str, params, error_msg, nullptr));
     311                 :        1660 : }
     312                 :             : 
     313                 :        1660 : bool IsValidDestinationString(const std::string& str)
     314                 :             : {
     315                 :        1660 :     return IsValidDestinationString(str, Params());
     316                 :             : }
        

Generated by: LCOV version 2.0-1