LCOV - code coverage report
Current view: top level - src - key_io.cpp (source / functions) Coverage Total Hit
Test: test_bitcoin_coverage.info Lines: 94.2 % 191 180
Test Date: 2024-08-28 04:44:32 Functions: 88.9 % 18 16
Branches: 61.9 % 268 166

             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                 :        6347 :     explicit DestinationEncoder(const CChainParams& params) : m_params(params) {}
      29                 :             : 
      30                 :          68 :     std::string operator()(const PKHash& id) const
      31                 :             :     {
      32                 :          68 :         std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
      33         [ +  - ]:          68 :         data.insert(data.end(), id.begin(), id.end());
      34         [ +  - ]:          68 :         return EncodeBase58Check(data);
      35                 :          68 :     }
      36                 :             : 
      37                 :          48 :     std::string operator()(const ScriptHash& id) const
      38                 :             :     {
      39                 :          48 :         std::vector<unsigned char> data = m_params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
      40         [ +  - ]:          48 :         data.insert(data.end(), id.begin(), id.end());
      41         [ +  - ]:          48 :         return EncodeBase58Check(data);
      42                 :          48 :     }
      43                 :             : 
      44                 :        6191 :     std::string operator()(const WitnessV0KeyHash& id) const
      45                 :             :     {
      46                 :        6191 :         std::vector<unsigned char> data = {0};
      47         [ +  - ]:        6191 :         data.reserve(33);
      48         [ +  - ]:      204303 :         ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
      49         [ +  - ]:        6191 :         return bech32::Encode(bech32::Encoding::BECH32, m_params.Bech32HRP(), data);
      50                 :        6191 :     }
      51                 :             : 
      52                 :          13 :     std::string operator()(const WitnessV0ScriptHash& id) const
      53                 :             :     {
      54                 :          13 :         std::vector<unsigned char> data = {0};
      55         [ +  - ]:          13 :         data.reserve(53);
      56         [ +  - ]:         689 :         ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, id.begin(), id.end());
      57         [ +  - ]:          13 :         return bech32::Encode(bech32::Encoding::BECH32, m_params.Bech32HRP(), data);
      58                 :          13 :     }
      59                 :             : 
      60                 :          19 :     std::string operator()(const WitnessV1Taproot& tap) const
      61                 :             :     {
      62                 :          19 :         std::vector<unsigned char> data = {1};
      63         [ +  - ]:          19 :         data.reserve(53);
      64         [ +  - ]:        1007 :         ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, tap.begin(), tap.end());
      65         [ +  - ]:          19 :         return bech32::Encode(bech32::Encoding::BECH32M, m_params.Bech32HRP(), data);
      66                 :          19 :     }
      67                 :             : 
      68                 :           8 :     std::string operator()(const WitnessUnknown& id) const
      69                 :             :     {
      70         [ +  - ]:           8 :         const std::vector<unsigned char>& program = id.GetWitnessProgram();
      71   [ +  -  +  -  :           8 :         if (id.GetWitnessVersion() < 1 || id.GetWitnessVersion() > 16 || program.size() < 2 || program.size() > 40) {
             +  -  -  + ]
      72                 :           0 :             return {};
      73                 :             :         }
      74                 :           8 :         std::vector<unsigned char> data = {(unsigned char)id.GetWitnessVersion()};
      75         [ +  - ]:           8 :         data.reserve(1 + (program.size() * 8 + 4) / 5);
      76         [ +  - ]:         300 :         ConvertBits<8, 5, true>([&](unsigned char c) { data.push_back(c); }, program.begin(), program.end());
      77         [ +  - ]:           8 :         return bech32::Encode(bech32::Encoding::BECH32M, m_params.Bech32HRP(), data);
      78                 :           8 :     }
      79                 :             : 
      80                 :           0 :     std::string operator()(const CNoDestination& no) const { return {}; }
      81                 :           0 :     std::string operator()(const PubKeyDestination& pk) const { return {}; }
      82                 :             : };
      83                 :             : 
      84                 :         455 : CTxDestination DecodeDestination(const std::string& str, const CChainParams& params, std::string& error_str, std::vector<int>* error_locations)
      85                 :             : {
      86                 :         455 :     std::vector<unsigned char> data;
      87                 :         455 :     uint160 hash;
      88         [ +  - ]:         455 :     error_str = "";
      89                 :             : 
      90                 :             :     // Note this will be false if it is a valid Bech32 address for a different network
      91   [ +  -  +  - ]:         455 :     bool is_bech32 = (ToLower(str.substr(0, params.Bech32HRP().size())) == params.Bech32HRP());
      92                 :             : 
      93   [ +  +  +  -  :         455 :     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         [ +  - ]:          78 :         const std::vector<unsigned char>& pubkey_prefix = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS);
      98   [ +  -  +  + ]:          78 :         if (data.size() == hash.size() + pubkey_prefix.size() && std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin())) {
      99                 :          45 :             std::copy(data.begin() + pubkey_prefix.size(), data.end(), hash.begin());
     100                 :          45 :             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         [ +  - ]:          33 :         const std::vector<unsigned char>& script_prefix = params.Base58Prefix(CChainParams::SCRIPT_ADDRESS);
     105   [ +  -  +  + ]:          33 :         if (data.size() == hash.size() + script_prefix.size() && std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) {
     106                 :          21 :             std::copy(data.begin() + script_prefix.size(), data.end(), hash.begin());
     107                 :          21 :             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         [ +  - ]:          12 :         if ((data.size() >= script_prefix.size() &&
     112   [ +  -  +  - ]:          12 :                 std::equal(script_prefix.begin(), script_prefix.end(), data.begin())) ||
     113   [ +  -  -  + ]:          12 :             (data.size() >= pubkey_prefix.size() &&
     114         [ -  + ]:          12 :                 std::equal(pubkey_prefix.begin(), pubkey_prefix.end(), data.begin()))) {
     115         [ #  # ]:           0 :             error_str = "Invalid length for Base58 address (P2PKH or P2SH)";
     116                 :             :         } else {
     117         [ +  - ]:          12 :             error_str = "Invalid or unsupported Base58-encoded address.";
     118                 :             :         }
     119                 :          12 :         return CNoDestination();
     120         [ +  + ]:         377 :     } else if (!is_bech32) {
     121                 :             :         // Try Base58 decoding without the checksum, using a much larger max length
     122   [ +  -  +  + ]:         249 :         if (!DecodeBase58(str, data, 100)) {
     123         [ +  - ]:         110 :             error_str = "Invalid or unsupported Segwit (Bech32) or Base58 encoding.";
     124                 :             :         } else {
     125         [ +  - ]:         139 :             error_str = "Invalid checksum or length of Base58 address (P2PKH or P2SH)";
     126                 :             :         }
     127                 :         249 :         return CNoDestination();
     128                 :             :     }
     129                 :             : 
     130         [ -  + ]:         128 :     data.clear();
     131         [ +  - ]:         128 :     const auto dec = bech32::Decode(str);
     132         [ +  + ]:         128 :     if (dec.encoding == bech32::Encoding::BECH32 || dec.encoding == bech32::Encoding::BECH32M) {
     133         [ +  + ]:         118 :         if (dec.data.empty()) {
     134         [ +  - ]:           3 :             error_str = "Empty Bech32 data section";
     135                 :           3 :             return CNoDestination();
     136                 :             :         }
     137                 :             :         // Bech32 decoding
     138         [ +  + ]:         115 :         if (dec.hrp != params.Bech32HRP()) {
     139         [ +  - ]:          10 :             error_str = strprintf("Invalid or unsupported prefix for Segwit (Bech32) address (expected %s, got %s).", params.Bech32HRP(), dec.hrp);
     140                 :          10 :             return CNoDestination();
     141                 :             :         }
     142         [ +  + ]:         105 :         int version = dec.data[0]; // The first 5 bit symbol is the witness version (0-16)
     143   [ +  +  +  + ]:         105 :         if (version == 0 && dec.encoding != bech32::Encoding::BECH32) {
     144         [ +  - ]:           6 :             error_str = "Version 0 witness address must use Bech32 checksum";
     145                 :           6 :             return CNoDestination();
     146                 :             :         }
     147         [ +  + ]:          52 :         if (version != 0 && dec.encoding != bech32::Encoding::BECH32M) {
     148         [ +  - ]:           8 :             error_str = "Version 1+ witness address must use Bech32m checksum";
     149                 :           8 :             return CNoDestination();
     150                 :             :         }
     151                 :             :         // The rest of the symbols are converted witness program bytes.
     152         [ +  - ]:          91 :         data.reserve(((dec.data.size() - 1) * 5) / 8);
     153   [ +  -  +  + ]:        2417 :         if (ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, dec.data.begin() + 1, dec.data.end())) {
     154                 :             : 
     155         [ +  + ]:          86 :             std::string_view byte_str{data.size() == 1 ? "byte" : "bytes"};
     156                 :             : 
     157         [ +  + ]:          86 :             if (version == 0) {
     158                 :          42 :                 {
     159         [ +  + ]:          42 :                     WitnessV0KeyHash keyid;
     160         [ +  + ]:          42 :                     if (data.size() == keyid.size()) {
     161                 :          20 :                         std::copy(data.begin(), data.end(), keyid.begin());
     162                 :          20 :                         return keyid;
     163                 :             :                     }
     164                 :             :                 }
     165                 :          22 :                 {
     166         [ +  + ]:          22 :                     WitnessV0ScriptHash scriptid;
     167         [ +  + ]:          22 :                     if (data.size() == scriptid.size()) {
     168                 :          16 :                         std::copy(data.begin(), data.end(), scriptid.begin());
     169                 :          16 :                         return scriptid;
     170                 :             :                     }
     171                 :             :                 }
     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   [ +  +  -  + ]:          44 :             if (version == 1 && data.size() == WITNESS_V1_TAPROOT_SIZE) {
     178                 :          16 :                 static_assert(WITNESS_V1_TAPROOT_SIZE == WitnessV1Taproot::size());
     179                 :          16 :                 WitnessV1Taproot tap;
     180                 :          16 :                 std::copy(data.begin(), data.end(), tap.begin());
     181                 :          16 :                 return tap;
     182                 :             :             }
     183                 :             : 
     184   [ +  -  -  + ]:          28 :             if (CScript::IsPayToAnchor(version, data)) {
     185         [ #  # ]:           0 :                 return PayToAnchor();
     186                 :             :             }
     187                 :             : 
     188         [ +  + ]:          28 :             if (version > 16) {
     189         [ +  - ]:           6 :                 error_str = "Invalid Bech32 address witness version";
     190                 :           6 :                 return CNoDestination();
     191                 :             :             }
     192                 :             : 
     193   [ +  +  +  + ]:          22 :             if (data.size() < 2 || data.size() > BECH32_WITNESS_PROG_MAX_LEN) {
     194         [ +  - ]:           6 :                 error_str = strprintf("Invalid Bech32 address program size (%d %s)", data.size(), byte_str);
     195                 :           6 :                 return CNoDestination();
     196                 :             :             }
     197                 :             : 
     198         [ +  - ]:          16 :             return WitnessUnknown{version, data};
     199                 :             :         } else {
     200         [ +  - ]:           5 :             error_str = strprintf("Invalid padding in Bech32 data section");
     201                 :           5 :             return CNoDestination();
     202                 :             :         }
     203                 :             :     }
     204                 :             : 
     205                 :             :     // Perform Bech32 error location
     206         [ +  - ]:          10 :     auto res = bech32::LocateErrors(str);
     207         [ +  - ]:          10 :     error_str = res.first;
     208         [ -  + ]:          10 :     if (error_locations) *error_locations = std::move(res.second);
     209                 :          10 :     return CNoDestination();
     210                 :         593 : }
     211                 :             : } // namespace
     212                 :             : 
     213                 :         604 : CKey DecodeSecret(const std::string& str)
     214                 :             : {
     215                 :         604 :     CKey key;
     216                 :         604 :     std::vector<unsigned char> data;
     217   [ +  -  +  + ]:         604 :     if (DecodeBase58Check(str, data, 34)) {
     218   [ +  -  +  + ]:         264 :         const std::vector<unsigned char>& privkey_prefix = Params().Base58Prefix(CChainParams::SECRET_KEY);
     219   [ +  +  +  +  :         264 :         if ((data.size() == 32 + privkey_prefix.size() || (data.size() == 33 + privkey_prefix.size() && data.back() == 1)) &&
             +  +  +  + ]
     220         [ +  + ]:         239 :             std::equal(privkey_prefix.begin(), privkey_prefix.end(), data.begin())) {
     221                 :         223 :             bool compressed = data.size() == 33 + privkey_prefix.size();
     222         [ +  - ]:         223 :             key.Set(data.begin() + privkey_prefix.size(), data.begin() + privkey_prefix.size() + 32, compressed);
     223                 :             :         }
     224                 :             :     }
     225         [ +  + ]:         604 :     if (!data.empty()) {
     226         [ +  - ]:         264 :         memory_cleanse(data.data(), data.size());
     227                 :             :     }
     228                 :         604 :     return key;
     229                 :         604 : }
     230                 :             : 
     231                 :         225 : std::string EncodeSecret(const CKey& key)
     232                 :             : {
     233         [ -  + ]:         225 :     assert(key.IsValid());
     234                 :         225 :     std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::SECRET_KEY);
     235   [ +  -  +  -  :         675 :     data.insert(data.end(), UCharCast(key.begin()), UCharCast(key.end()));
                   +  - ]
     236         [ +  + ]:         225 :     if (key.IsCompressed()) {
     237         [ +  - ]:         199 :         data.push_back(1);
     238                 :             :     }
     239         [ +  - ]:         225 :     std::string ret = EncodeBase58Check(data);
     240         [ +  - ]:         225 :     memory_cleanse(data.data(), data.size());
     241                 :         225 :     return ret;
     242                 :         225 : }
     243                 :             : 
     244                 :         453 : CExtPubKey DecodeExtPubKey(const std::string& str)
     245                 :             : {
     246         [ +  - ]:         453 :     CExtPubKey key;
     247                 :         453 :     std::vector<unsigned char> data;
     248   [ +  -  +  + ]:         453 :     if (DecodeBase58Check(str, data, 78)) {
     249   [ +  -  +  - ]:         449 :         const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
     250   [ +  -  +  + ]:         449 :         if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
     251         [ +  - ]:         375 :             key.Decode(data.data() + prefix.size());
     252                 :             :         }
     253                 :             :     }
     254                 :         453 :     return key;
     255                 :         453 : }
     256                 :             : 
     257                 :       13916 : std::string EncodeExtPubKey(const CExtPubKey& key)
     258                 :             : {
     259                 :       13916 :     std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_PUBLIC_KEY);
     260         [ +  - ]:       13916 :     size_t size = data.size();
     261         [ +  - ]:       13916 :     data.resize(size + BIP32_EXTKEY_SIZE);
     262         [ +  - ]:       13916 :     key.Encode(data.data() + size);
     263         [ +  - ]:       13916 :     std::string ret = EncodeBase58Check(data);
     264                 :       13916 :     return ret;
     265                 :       13916 : }
     266                 :             : 
     267                 :         453 : CExtKey DecodeExtKey(const std::string& str)
     268                 :             : {
     269         [ +  - ]:         453 :     CExtKey key;
     270                 :         453 :     std::vector<unsigned char> data;
     271   [ +  -  +  + ]:         453 :     if (DecodeBase58Check(str, data, 78)) {
     272   [ +  -  +  - ]:         449 :         const std::vector<unsigned char>& prefix = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
     273   [ +  -  +  + ]:         449 :         if (data.size() == BIP32_EXTKEY_SIZE + prefix.size() && std::equal(prefix.begin(), prefix.end(), data.begin())) {
     274         [ +  - ]:          90 :             key.Decode(data.data() + prefix.size());
     275                 :             :         }
     276                 :             :     }
     277                 :         453 :     return key;
     278                 :         453 : }
     279                 :             : 
     280                 :         151 : std::string EncodeExtKey(const CExtKey& key)
     281                 :             : {
     282                 :         151 :     std::vector<unsigned char> data = Params().Base58Prefix(CChainParams::EXT_SECRET_KEY);
     283         [ +  - ]:         151 :     size_t size = data.size();
     284         [ +  - ]:         151 :     data.resize(size + BIP32_EXTKEY_SIZE);
     285         [ +  - ]:         151 :     key.Encode(data.data() + size);
     286         [ +  - ]:         151 :     std::string ret = EncodeBase58Check(data);
     287         [ +  - ]:         151 :     memory_cleanse(data.data(), data.size());
     288                 :         151 :     return ret;
     289                 :         151 : }
     290                 :             : 
     291                 :        6347 : std::string EncodeDestination(const CTxDestination& dest)
     292                 :             : {
     293                 :        6347 :     return std::visit(DestinationEncoder(Params()), dest);
     294                 :             : }
     295                 :             : 
     296                 :         455 : CTxDestination DecodeDestination(const std::string& str, std::string& error_msg, std::vector<int>* error_locations)
     297                 :             : {
     298                 :         455 :     return DecodeDestination(str, Params(), error_msg, error_locations);
     299                 :             : }
     300                 :             : 
     301                 :         455 : CTxDestination DecodeDestination(const std::string& str)
     302                 :             : {
     303         [ +  - ]:         455 :     std::string error_msg;
     304         [ +  - ]:         455 :     return DecodeDestination(str, error_msg);
     305                 :         455 : }
     306                 :             : 
     307                 :           0 : bool IsValidDestinationString(const std::string& str, const CChainParams& params)
     308                 :             : {
     309         [ #  # ]:           0 :     std::string error_msg;
     310   [ #  #  #  # ]:           0 :     return IsValidDestination(DecodeDestination(str, params, error_msg, nullptr));
     311                 :           0 : }
     312                 :             : 
     313                 :           0 : bool IsValidDestinationString(const std::string& str)
     314                 :             : {
     315                 :           0 :     return IsValidDestinationString(str, Params());
     316                 :             : }
        

Generated by: LCOV version 2.0-1