LCOV - code coverage report
Current view: top level - src/common - bip352.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 0.0 % 320 0
Test Date: 2026-11-21 05:38:30 Functions: 0.0 % 30 0
Branches: 0.0 % 454 0

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2023 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 <common/bip352.h>
       6                 :             : 
       7                 :             : #include <addresstype.h>
       8                 :             : #include <bech32.h>
       9                 :             : #include <chainparams.h>
      10                 :             : #include <coins.h>
      11                 :             : #include <hash.h>
      12                 :             : #include <key.h>
      13                 :             : #include <primitives/transaction.h>
      14                 :             : #include <pubkey.h>
      15                 :             : #include <script/interpreter.h>
      16                 :             : #include <script/script.h>
      17                 :             : #include <script/sign.h>
      18                 :             : #include <script/solver.h>
      19                 :             : #include <script/verify_flags.h>
      20                 :             : #include <secp256k1.h>
      21                 :             : #include <secp256k1_extrakeys.h>
      22                 :             : #include <secp256k1_silentpayments.h>
      23                 :             : #include <span.h>
      24                 :             : #include <streams.h>
      25                 :             : #include <tinyformat.h>
      26                 :             : #include <uint256.h>
      27                 :             : #include <util/strencodings.h>
      28                 :             : 
      29                 :             : #include <algorithm>
      30                 :             : #include <cassert>
      31                 :             : #include <cstddef>
      32                 :             : #include <optional>
      33                 :             : #include <span>
      34                 :             : #include <type_traits>
      35                 :             : #include <utility>
      36                 :             : 
      37                 :             : namespace bip352 {
      38                 :             : 
      39                 :           0 : PrevoutsSummary::PrevoutsSummary(const secp256k1_silentpayments_prevouts_summary& prevouts_summary)
      40                 :           0 :   : m_prevouts_summary{std::make_unique<secp256k1_silentpayments_prevouts_summary>(prevouts_summary)} {}
      41                 :             : 
      42                 :           0 : PrevoutsSummary::PrevoutsSummary(PrevoutsSummary&&) noexcept = default;
      43                 :           0 : PrevoutsSummary& PrevoutsSummary::operator=(PrevoutsSummary&&) noexcept = default;
      44                 :             : 
      45                 :           0 : PrevoutsSummary::~PrevoutsSummary() = default;
      46                 :             : 
      47                 :           0 : const secp256k1_silentpayments_prevouts_summary* PrevoutsSummary::Get() const
      48                 :             : {
      49                 :           0 :     return m_prevouts_summary.get();
      50                 :             : }
      51                 :             : 
      52                 :           0 : std::optional<SilentPaymentsDestination> SilentPaymentsDestination::From(
      53                 :             :     const CPubKey& scan_pubkey,
      54                 :             :     const CPubKey& spend_pubkey,
      55                 :             :     uint8_t version,
      56                 :             :     std::span<const unsigned char> extension_data
      57                 :             : ) {
      58         [ #  # ]:           0 :     if (version >= 31) return std::nullopt;
      59   [ #  #  #  # ]:           0 :     if (version == 0 && !extension_data.empty()) {
      60                 :             :         // V0 address has no extension data
      61                 :           0 :         return std::nullopt;
      62                 :             :     }
      63   [ #  #  #  # ]:           0 :     if (!scan_pubkey.IsFullyValid() || !scan_pubkey.IsCompressed()) return std::nullopt;
      64   [ #  #  #  # ]:           0 :     if (!spend_pubkey.IsFullyValid() || !spend_pubkey.IsCompressed()) return std::nullopt;
      65                 :           0 :     return SilentPaymentsDestination(version, scan_pubkey, spend_pubkey, extension_data);
      66                 :             : }
      67                 :             : 
      68                 :           0 : util::Expected<SilentPaymentsDestination, std::string> DecodeSilentPaymentsAddress(
      69                 :             :     const std::string& str, const CChainParams& params)
      70                 :             : {
      71                 :           0 :     static constexpr size_t SILENT_PAYMENTS_V0_DATA_SIZE = 66;
      72                 :           0 :     static constexpr size_t SP_PUBKEYS_SIZE = 2 * CPubKey::COMPRESSED_SIZE;
      73                 :             : 
      74                 :           0 :     const auto dec = bech32::Decode(str, bech32::CharLimit::SILENT_PAYMENTS);
      75         [ #  # ]:           0 :     if (dec.encoding != bech32::Encoding::BECH32M) {
      76         [ #  # ]:           0 :         return util::Unexpected{"Silent Payments address must use Bech32m checksum"};
      77                 :             :     }
      78         [ #  # ]:           0 :     if (dec.hrp != params.SilentPaymentsHRP()) {
      79         [ #  # ]:           0 :         return util::Unexpected{strprintf("Invalid or unsupported prefix for Silent Payments address (expected %s, got %s).", params.SilentPaymentsHRP(), dec.hrp)};
      80                 :             :     }
      81         [ #  # ]:           0 :     if (dec.data.empty()) {
      82         [ #  # ]:           0 :         return util::Unexpected{"Empty Bech32 data section"};
      83                 :             :     }
      84                 :           0 :     std::vector<unsigned char> data;
      85   [ #  #  #  # ]:           0 :     if (!ConvertBits<5, 8, false>([&](unsigned char c) { data.push_back(c); }, dec.data.begin() + 1, dec.data.end())) {
      86         [ #  # ]:           0 :         return util::Unexpected{"Invalid padding in Silent payments address (Bech32m data section)"};
      87                 :             :     }
      88   [ #  #  #  # ]:           0 :     if (data.size() < SILENT_PAYMENTS_V0_DATA_SIZE) {
      89         [ #  # ]:           0 :         return util::Unexpected{strprintf("Silent payments data payload is too small (expected at least %d, got %d).", SILENT_PAYMENTS_V0_DATA_SIZE, data.size())};
      90                 :             :     }
      91         [ #  # ]:           0 :     const uint8_t version = dec.data[0];
      92         [ #  # ]:           0 :     if (version >= 31) {
      93         [ #  # ]:           0 :         return util::Unexpected{strprintf("This implementation only supports Silent payments addresses v0 through v30 (got %d).", version)};
      94                 :             :     }
      95   [ #  #  #  # ]:           0 :     if (version == 0 && data.size() != SILENT_PAYMENTS_V0_DATA_SIZE) {
      96         [ #  # ]:           0 :         return util::Unexpected{strprintf("Silent payments version is v0 but data is not the correct size (expected %d, got %d).", SILENT_PAYMENTS_V0_DATA_SIZE, data.size())};
      97                 :             :     }
      98                 :           0 :     CPubKey scan_pubkey{data.begin(), data.begin() + CPubKey::COMPRESSED_SIZE};
      99                 :           0 :     CPubKey spend_pubkey{data.begin() + CPubKey::COMPRESSED_SIZE, data.begin() + 2 * CPubKey::COMPRESSED_SIZE};
     100   [ #  #  #  # ]:           0 :     std::span<unsigned char> extension_data{data.data() + SP_PUBKEYS_SIZE, data.size() - SP_PUBKEYS_SIZE};
     101         [ #  # ]:           0 :     auto sp_dest = SilentPaymentsDestination::From(scan_pubkey, spend_pubkey, version, extension_data);
     102         [ #  # ]:           0 :     if (!sp_dest) {
     103         [ #  # ]:           0 :         return util::Unexpected{"Invalid Silent payments address"};
     104                 :             :     }
     105         [ #  # ]:           0 :     return *sp_dest;
     106                 :           0 : }
     107                 :             : 
     108         [ #  # ]:           0 : SilentPaymentsLabel::SilentPaymentsLabel(const secp256k1_silentpayments_label& label) {
     109         [ #  # ]:           0 :     m_label = std::make_unique<secp256k1_silentpayments_label>(label);
     110         [ #  # ]:           0 :     int ret = secp256k1_silentpayments_recipient_label_serialize(secp256k1_context_static, m_vch, m_label.get());
     111         [ #  # ]:           0 :     assert(ret);
     112                 :           0 : }
     113                 :             : 
     114                 :           0 : std::optional<SilentPaymentsLabel> SilentPaymentsLabel::FromBytes(std::span<const unsigned char, CPubKey::COMPRESSED_SIZE> vch)
     115                 :             : {
     116                 :           0 :     secp256k1_silentpayments_label label_obj;
     117         [ #  # ]:           0 :     if (!secp256k1_silentpayments_recipient_label_parse(secp256k1_context_static, &label_obj, vch.data())) {
     118                 :           0 :         return std::nullopt;
     119                 :             :     }
     120                 :           0 :     return SilentPaymentsLabel(label_obj);
     121                 :             : }
     122                 :             : 
     123                 :           0 : SilentPaymentsLabel::SilentPaymentsLabel(SilentPaymentsLabel&&) noexcept = default;
     124         [ #  # ]:           0 : SilentPaymentsLabel& SilentPaymentsLabel::operator=(SilentPaymentsLabel&&) noexcept = default;
     125                 :           0 : SilentPaymentsLabel::~SilentPaymentsLabel() = default;
     126                 :             : 
     127                 :           0 : SilentPaymentsLabel::SilentPaymentsLabel(const SilentPaymentsLabel& label)
     128                 :           0 :     : m_label{std::make_unique<secp256k1_silentpayments_label>(*label.m_label)}
     129                 :             : {
     130                 :           0 :     memcpy(m_vch, label.m_vch, CPubKey::COMPRESSED_SIZE);
     131                 :           0 : }
     132                 :           0 : SilentPaymentsLabel& SilentPaymentsLabel::operator=(const SilentPaymentsLabel& label) {
     133         [ #  # ]:           0 :     if (this != &label) {
     134                 :           0 :         m_label = std::make_unique<secp256k1_silentpayments_label>(*label.m_label);
     135                 :           0 :         memcpy(m_vch, label.m_vch, CPubKey::COMPRESSED_SIZE);
     136                 :             :     }
     137                 :           0 :     return *this;
     138                 :             : }
     139                 :             : 
     140                 :           0 : const secp256k1_silentpayments_label* SilentPaymentsLabel::Get() const {
     141                 :           0 :     return m_label.get();
     142                 :             : }
     143                 :             : 
     144                 :           0 : std::optional<PubKey> GetPubKeyFromInput(const CTxIn& txin, const CScript& spk)
     145                 :             : {
     146                 :           0 :     std::vector<std::vector<unsigned char>> solutions;
     147         [ #  # ]:           0 :     const TxoutType type = Solver(spk, solutions);
     148                 :             : 
     149         [ #  # ]:           0 :     if (type == TxoutType::WITNESS_V1_TAPROOT) {
     150                 :           0 :         const auto& stack = txin.scriptWitness.stack;
     151         [ #  # ]:           0 :         if (stack.empty()) return std::nullopt;
     152   [ #  #  #  # ]:           0 :         const bool has_annex = !stack.back().empty() && stack.back()[0] == ANNEX_TAG;
     153   [ #  #  #  # ]:           0 :         const size_t effective_size = stack.size() - (has_annex ? 1 : 0);
     154                 :             : 
     155         [ #  # ]:           0 :         if (effective_size > 1) {
     156                 :             :             // BIP-352: skip script-path spends using NUMS-H internal key.
     157                 :             :             // Validate control block size before checking internal key.
     158         [ #  # ]:           0 :             const auto& control = stack[effective_size - 1];
     159         [ #  # ]:           0 :             if (control.size() < TAPROOT_CONTROL_BASE_SIZE ||
     160   [ #  #  #  # ]:           0 :                 control.size() > TAPROOT_CONTROL_MAX_SIZE ||
     161         [ #  # ]:           0 :                 (control.size() - TAPROOT_CONTROL_BASE_SIZE) % TAPROOT_CONTROL_NODE_SIZE != 0) {
     162                 :           0 :                 return std::nullopt;
     163                 :             :             }
     164         [ #  # ]:           0 :             if (std::equal(WitnessV1Taproot::NUMS_H.begin(), WitnessV1Taproot::NUMS_H.end(), control.begin() + 1)) {
     165                 :           0 :                 return std::nullopt;
     166                 :             :             }
     167                 :             :         }
     168                 :             : 
     169         [ #  # ]:           0 :         XOnlyPubKey key{solutions[0]};
     170   [ #  #  #  # ]:           0 :         if (!key.IsFullyValid()) return std::nullopt;
     171                 :           0 :         return PubKey{key};
     172                 :             :     }
     173                 :             : 
     174         [ #  # ]:           0 :     if (type == TxoutType::WITNESS_V0_KEYHASH) {
     175                 :           0 :         const auto& stack = txin.scriptWitness.stack;
     176         [ #  # ]:           0 :         if (stack.empty()) return std::nullopt;
     177         [ #  # ]:           0 :         CPubKey key{stack.back()};
     178   [ #  #  #  #  :           0 :         if (!key.IsCompressed() || !key.IsFullyValid()) return std::nullopt;
                   #  # ]
     179                 :           0 :         return PubKey{key};
     180                 :             :     }
     181                 :             : 
     182         [ #  # ]:           0 :     if (type == TxoutType::PUBKEYHASH) {
     183                 :             :         // For P2PKH public key extraction, BIP-352 states: "The receiver MUST parse the scriptSig
     184                 :             :         // for the public key, even if the scriptSig does not match the template specified. This is
     185                 :             :         // to address the third-party malleability of P2PKH scriptSigs."
     186                 :             :         //
     187                 :             :         // Find the preimage of the pubkey hash by iterating through the scriptSig data pushes and
     188                 :             :         // comparing the Hash160 of each 33-byte (compressed) push against the output script. In
     189                 :             :         // standard spends the pubkey is the last push, but due to malleability we can't rely on
     190                 :             :         // that (e.g. `<dummy> OP_DROP` inserted anywhere). Evaluating the scriptSig with a dummy
     191                 :             :         // signature checker isn't safe either, as a malleated scriptSig could then leave a
     192                 :             :         // different pubkey on top of the stack than real validation would.
     193         [ #  # ]:           0 :         const uint160 pubkey_hash{solutions[0]};
     194         [ #  # ]:           0 :         auto pc = txin.scriptSig.begin();
     195   [ #  #  #  # ]:           0 :         while (pc < txin.scriptSig.end()) {
     196                 :           0 :             opcodetype opcode;
     197                 :           0 :             std::vector<unsigned char> pubkey_candidate;
     198   [ #  #  #  # ]:           0 :             if (!txin.scriptSig.GetOp(pc, opcode, pubkey_candidate)) {
     199                 :           0 :                 return std::nullopt;
     200                 :             :             }
     201   [ #  #  #  #  :           0 :             if (pubkey_candidate.size() == 33 && Hash160(pubkey_candidate) == pubkey_hash) {
                   #  # ]
     202         [ #  # ]:           0 :                 CPubKey key{pubkey_candidate};
     203   [ #  #  #  # ]:           0 :                 if (key.IsFullyValid()) return PubKey{key};
     204                 :             :             }
     205                 :           0 :         }
     206                 :           0 :         return std::nullopt;
     207                 :             :     }
     208                 :             : 
     209         [ #  # ]:           0 :     if (type == TxoutType::SCRIPTHASH) {
     210                 :             :         // P2SH-P2WPKH only: eval scriptSig, verify redeem script is P2WPKH. Unlike P2PKH above,
     211                 :             :         // evaluating is safe here, as consensus (BIP-141) requires the scriptSig to be a single
     212                 :             :         // push of the redeem script.
     213                 :           0 :         std::vector<std::vector<unsigned char>> stack;
     214   [ #  #  #  # ]:           0 :         if (!EvalScript(stack, txin.scriptSig, SCRIPT_VERIFY_NONE, DUMMY_CHECKER, SigVersion::BASE)) {
     215                 :           0 :             return std::nullopt;
     216                 :             :         }
     217         [ #  # ]:           0 :         if (stack.empty()) return std::nullopt;
     218                 :           0 :         CScript redeem{stack.back().begin(), stack.back().end()};
     219   [ #  #  #  # ]:           0 :         if (Solver(redeem, solutions) != TxoutType::WITNESS_V0_KEYHASH) return std::nullopt;
     220         [ #  # ]:           0 :         if (txin.scriptWitness.stack.empty()) return std::nullopt;
     221         [ #  # ]:           0 :         CPubKey key{txin.scriptWitness.stack.back()};
     222   [ #  #  #  #  :           0 :         if (!key.IsCompressed() || !key.IsFullyValid()) return std::nullopt;
                   #  # ]
     223                 :           0 :         return PubKey{key};
     224                 :           0 :     }
     225                 :             : 
     226                 :           0 :     return std::nullopt;
     227                 :           0 : }
     228                 :             : 
     229                 :           0 : static std::optional<PrevoutsSummary> CreateInputPubkeysTweak(
     230                 :             :     const std::vector<CPubKey>& plain_pubkeys,
     231                 :             :     const std::vector<XOnlyPubKey>& taproot_pubkeys,
     232                 :             :     const COutPoint& smallest_outpoint)
     233                 :             : {
     234                 :           0 :     secp256k1_silentpayments_prevouts_summary prevouts_summary;
     235                 :           0 :     std::vector<secp256k1_pubkey> plain_pubkey_objs;
     236                 :           0 :     std::vector<secp256k1_pubkey*> plain_pubkey_ptrs;
     237   [ #  #  #  # ]:           0 :     plain_pubkey_objs.reserve(plain_pubkeys.size());
     238   [ #  #  #  # ]:           0 :     plain_pubkey_ptrs.reserve(plain_pubkeys.size());
     239         [ #  # ]:           0 :     for (const CPubKey& pubkey : plain_pubkeys) {
     240   [ #  #  #  # ]:           0 :         bool ret = secp256k1_ec_pubkey_parse(secp256k1_context_static,
     241         [ #  # ]:           0 :             &plain_pubkey_objs.emplace_back(), pubkey.data(), pubkey.size());
     242                 :             :         // This pubkey is expected to be valid because GetPubKeyFromInput()
     243                 :             :         // already called IsFullyValid() before including it here
     244         [ #  # ]:           0 :         assert(ret);
     245         [ #  # ]:           0 :         plain_pubkey_ptrs.push_back(&plain_pubkey_objs.back());
     246                 :             :     }
     247                 :             : 
     248                 :           0 :     std::vector<secp256k1_xonly_pubkey> taproot_pubkey_objs;
     249                 :           0 :     std::vector<secp256k1_xonly_pubkey*> taproot_pubkey_ptrs;
     250   [ #  #  #  # ]:           0 :     taproot_pubkey_objs.reserve(taproot_pubkeys.size());
     251   [ #  #  #  # ]:           0 :     taproot_pubkey_ptrs.reserve(taproot_pubkeys.size());
     252         [ #  # ]:           0 :     for (const XOnlyPubKey& pubkey : taproot_pubkeys) {
     253   [ #  #  #  # ]:           0 :         bool ret = secp256k1_xonly_pubkey_parse(secp256k1_context_static,
     254         [ #  # ]:           0 :             &taproot_pubkey_objs.emplace_back(), pubkey.data());
     255                 :             :         // This xonlypubkey is expected to be valid because
     256                 :             :         // GetPubKeyFromInput() already called IsFullyValid()
     257                 :             :         // before including it here
     258         [ #  # ]:           0 :         assert(ret);
     259         [ #  # ]:           0 :         taproot_pubkey_ptrs.push_back(&taproot_pubkey_objs.back());
     260                 :             :     }
     261                 :             : 
     262                 :           0 :     std::array<std::byte, 36> smallest_outpoint_ser;
     263         [ #  # ]:           0 :     SpanWriter{smallest_outpoint_ser} << smallest_outpoint;
     264         [ #  # ]:           0 :     bool ret = secp256k1_silentpayments_recipient_prevouts_summary_create(secp256k1_context_static,
     265                 :             :         &prevouts_summary,
     266         [ #  # ]:           0 :         UCharCast(smallest_outpoint_ser.data()),
     267         [ #  # ]:           0 :         taproot_pubkey_ptrs.data(), taproot_pubkey_ptrs.size(),
     268         [ #  # ]:           0 :         plain_pubkey_ptrs.data(), plain_pubkey_ptrs.size()
     269                 :           0 :     );
     270         [ #  # ]:           0 :     if (!ret) return std::nullopt;
     271         [ #  # ]:           0 :     return PrevoutsSummary(prevouts_summary);
     272                 :           0 : }
     273                 :             : 
     274                 :           0 : util::Expected<PrevoutsSummary, PrevoutsSummaryError> GetSilentPaymentsPrevoutsSummary(const std::vector<CTxIn>& vin, const std::map<COutPoint, Coin>& coins)
     275                 :             : {
     276                 :             :     // Extract the keys from the inputs
     277                 :             :     // or skip if no valid inputs
     278                 :           0 :     std::vector<CPubKey> pubkeys;
     279                 :           0 :     std::vector<XOnlyPubKey> xonly_pubkeys;
     280                 :           0 :     std::vector<COutPoint> tx_outpoints;
     281         [ #  # ]:           0 :     for (const CTxIn& txin : vin) {
     282                 :           0 :         const auto coin_it = coins.find(txin.prevout);
     283         [ #  # ]:           0 :         if (coin_it == coins.end()) return util::Unexpected(PrevoutsSummaryError::MISSING_COIN);
     284         [ #  # ]:           0 :         const Coin& coin = coin_it->second;
     285                 :           0 :         int witness_version{0};
     286                 :           0 :         std::vector<unsigned char> witness_program;
     287                 :             :         // BIP352 v0 skips transactions spending future witness versions.
     288   [ #  #  #  #  :           0 :         if (coin.out.scriptPubKey.IsWitnessProgram(witness_version, witness_program) && witness_version > 1) {
                   #  # ]
     289                 :           0 :             return util::Unexpected(PrevoutsSummaryError::NOT_ELIGIBLE);
     290                 :             :         }
     291         [ #  # ]:           0 :         tx_outpoints.emplace_back(txin.prevout);
     292         [ #  # ]:           0 :         auto pubkey = GetPubKeyFromInput(txin, coin.out.scriptPubKey);
     293         [ #  # ]:           0 :         if (pubkey.has_value()) {
     294         [ #  # ]:           0 :             std::visit([&pubkeys, &xonly_pubkeys](auto&& pubkey) {
     295                 :             :                 using T = std::decay_t<decltype(pubkey)>;
     296                 :             :                 if constexpr (std::is_same_v<T, CPubKey>) {
     297                 :           0 :                     pubkeys.push_back(pubkey);
     298                 :             :                 } else if constexpr (std::is_same_v<T, XOnlyPubKey>) {
     299                 :           0 :                     xonly_pubkeys.push_back(pubkey);
     300                 :             :                 }
     301                 :             :             }, *pubkey);
     302                 :             :         }
     303                 :           0 :     }
     304   [ #  #  #  #  :           0 :     if (pubkeys.size() + xonly_pubkeys.size() == 0) return util::Unexpected(PrevoutsSummaryError::NOT_ELIGIBLE);
                   #  # ]
     305                 :           0 :     auto smallest_outpoint = std::min_element(tx_outpoints.begin(), tx_outpoints.end(), BIP352Comparator());
     306         [ #  # ]:           0 :     auto tweak = CreateInputPubkeysTweak(pubkeys, xonly_pubkeys, *smallest_outpoint);
     307         [ #  # ]:           0 :     if (!tweak.has_value()) return util::Unexpected(PrevoutsSummaryError::NOT_ELIGIBLE);
     308                 :           0 :     return std::move(*tweak);
     309                 :           0 : }
     310                 :             : 
     311                 :           0 : static std::optional<std::vector<secp256k1_xonly_pubkey>> CreateOutputs(
     312                 :             :     const std::vector<SilentPaymentsDestination>& recipients,
     313                 :             :     const std::vector<CKey>& plain_keys,
     314                 :             :     const std::vector<KeyPair>& taproot_keypairs,
     315                 :             :     const COutPoint& smallest_outpoint
     316                 :             : ) {
     317                 :           0 :     bool ret;
     318                 :           0 :     std::vector<const secp256k1_keypair *> taproot_keypair_ptrs;
     319                 :           0 :     std::vector<const unsigned char *> plain_key_ptrs;
     320   [ #  #  #  # ]:           0 :     taproot_keypair_ptrs.reserve(taproot_keypairs.size());
     321   [ #  #  #  # ]:           0 :     plain_key_ptrs.reserve(plain_keys.size());
     322                 :             : 
     323                 :           0 :     std::vector<secp256k1_silentpayments_recipient> recipient_objs;
     324                 :           0 :     std::vector<const secp256k1_silentpayments_recipient *> recipient_ptrs;
     325   [ #  #  #  # ]:           0 :     recipient_objs.reserve(recipients.size());
     326   [ #  #  #  # ]:           0 :     recipient_ptrs.reserve(recipients.size());
     327                 :             : 
     328                 :           0 :     std::vector<secp256k1_xonly_pubkey> generated_outputs;
     329                 :           0 :     std::vector<secp256k1_xonly_pubkey *> generated_output_ptrs;
     330   [ #  #  #  # ]:           0 :     generated_outputs.reserve(recipients.size());
     331   [ #  #  #  # ]:           0 :     generated_output_ptrs.reserve(recipients.size());
     332                 :             : 
     333   [ #  #  #  # ]:           0 :     for (size_t i = 0; i < recipients.size(); i++) {
     334                 :           0 :         secp256k1_silentpayments_recipient recipient_obj;
     335         [ #  # ]:           0 :         ret = secp256k1_ec_pubkey_parse(secp256k1_context_static, &recipient_obj.scan_pubkey, recipients[i].GetScanPubKey().data(), recipients[i].GetScanPubKey().size());
     336         [ #  # ]:           0 :         assert(ret);
     337         [ #  # ]:           0 :         ret = secp256k1_ec_pubkey_parse(secp256k1_context_static, &recipient_obj.spend_pubkey, recipients[i].GetSpendPubKey().data(), recipients[i].GetSpendPubKey().size());
     338         [ #  # ]:           0 :         assert(ret);
     339                 :           0 :         recipient_obj.index = i;
     340         [ #  # ]:           0 :         recipient_objs.push_back(recipient_obj);
     341         [ #  # ]:           0 :         recipient_ptrs.push_back(&recipient_objs[i]);
     342                 :             : 
     343                 :           0 :         secp256k1_xonly_pubkey generated_output{};
     344         [ #  # ]:           0 :         generated_outputs.push_back(generated_output);
     345         [ #  # ]:           0 :         generated_output_ptrs.push_back(&generated_outputs[i]);
     346                 :             :     }
     347                 :             : 
     348         [ #  # ]:           0 :     for (const auto& key : plain_keys) {
     349         [ #  # ]:           0 :         if (!key.IsValid()) return std::nullopt;
     350         [ #  # ]:           0 :         plain_key_ptrs.push_back(UCharCast(key.begin()));
     351                 :             :     }
     352         [ #  # ]:           0 :     for (const auto& keypair : taproot_keypairs) {
     353         [ #  # ]:           0 :         if (!keypair.IsValid()) return std::nullopt;
     354         [ #  # ]:           0 :         taproot_keypair_ptrs.push_back(keypair.GetSecpKeypair());
     355                 :             :     }
     356                 :             : 
     357                 :             :     // Serialize the outpoint
     358                 :           0 :     std::array<std::byte, 36> smallest_outpoint_ser;
     359         [ #  # ]:           0 :     SpanWriter{smallest_outpoint_ser} << smallest_outpoint;
     360                 :             : 
     361   [ #  #  #  #  :           0 :     ret = secp256k1_silentpayments_sender_create_outputs(GetSecp256k1SignContext(),
                   #  # ]
     362                 :             :         generated_output_ptrs.data(),
     363                 :             :         recipient_ptrs.data(), recipient_ptrs.size(),
     364         [ #  # ]:           0 :         UCharCast(smallest_outpoint_ser.data()),
     365         [ #  # ]:           0 :         taproot_keypair_ptrs.data(), taproot_keypair_ptrs.size(),
     366         [ #  # ]:           0 :         plain_key_ptrs.data(), plain_key_ptrs.size()
     367                 :             :     );
     368         [ #  # ]:           0 :     if (!ret) return std::nullopt;
     369                 :           0 :     return generated_outputs;
     370                 :           0 : }
     371                 :             : 
     372                 :           0 : std::optional<std::map<size_t, WitnessV1Taproot>> GenerateSilentPaymentsTaprootDestinations(const std::map<size_t, SilentPaymentsDestination>& sp_dests, const std::vector<CKey>& plain_keys, const std::vector<KeyPair>& taproot_keys, const COutPoint& smallest_outpoint)
     373                 :             : {
     374         [ #  # ]:           0 :     if (sp_dests.empty()) return std::map<size_t, WitnessV1Taproot>();
     375                 :             : 
     376         [ #  # ]:           0 :     assert(!smallest_outpoint.IsNull());
     377   [ #  #  #  # ]:           0 :     assert(!plain_keys.empty() || !taproot_keys.empty());
     378                 :             : 
     379                 :           0 :     bool ret;
     380         [ #  # ]:           0 :     std::map<size_t, WitnessV1Taproot> tr_dests;
     381                 :           0 :     std::vector<SilentPaymentsDestination> recipients;
     382         [ #  # ]:           0 :     recipients.reserve(sp_dests.size());
     383   [ #  #  #  # ]:           0 :     for (const auto& [_, addr] : sp_dests) {
     384         [ #  # ]:           0 :         recipients.push_back(addr);
     385                 :             :     }
     386         [ #  # ]:           0 :     auto outputs = CreateOutputs(recipients, plain_keys, taproot_keys, smallest_outpoint);
     387                 :             :     // This will fail if any input pubkey is null or
     388                 :             :     // inputs were maliciously crafted to sum to zero
     389         [ #  # ]:           0 :     if (!outputs) return std::nullopt;
     390   [ #  #  #  # ]:           0 :     assert(sp_dests.size() == outputs->size());
     391                 :           0 :     size_t output_i{0};
     392   [ #  #  #  # ]:           0 :     for (const auto& [i, _] : sp_dests) {
     393                 :           0 :         unsigned char xonly_pubkey_bytes[32];
     394   [ #  #  #  # ]:           0 :         ret = secp256k1_xonly_pubkey_serialize(secp256k1_context_static, xonly_pubkey_bytes, &outputs.value()[output_i]);
     395         [ #  # ]:           0 :         assert(ret);
     396         [ #  # ]:           0 :         tr_dests[i] = WitnessV1Taproot{XOnlyPubKey{xonly_pubkey_bytes}};
     397                 :           0 :         output_i++;
     398                 :             :     }
     399                 :           0 :     return tr_dests;
     400                 :           0 : }
     401                 :             : 
     402                 :           0 : static const unsigned char* LabelLookupCallback(const unsigned char* key, const void* context) {
     403                 :           0 :     auto label_context = static_cast<const LabelTweakMap*>(context);
     404                 :           0 :     auto it = label_context->find(std::span<const unsigned char, CPubKey::COMPRESSED_SIZE>{key, CPubKey::COMPRESSED_SIZE});
     405         [ #  # ]:           0 :     if (it != label_context->end()) {
     406                 :           0 :         return it->second.begin();
     407                 :             :     }
     408                 :             :     return nullptr;
     409                 :             : }
     410                 :             : 
     411                 :           0 : static std::pair<SilentPaymentsLabel, uint256> CreateLabel(const CKey& scan_key, const uint32_t m) {
     412                 :           0 :     secp256k1_silentpayments_label label_obj;
     413                 :           0 :     unsigned char label_tweak[32];
     414         [ #  # ]:           0 :     bool ret = secp256k1_silentpayments_recipient_label_create(GetSecp256k1SignContext(), &label_obj, label_tweak, UCharCast(scan_key.data()), m);
     415         [ #  # ]:           0 :     assert(ret);
     416                 :           0 :     return {SilentPaymentsLabel(label_obj), uint256{label_tweak}};
     417                 :             : }
     418                 :             : 
     419                 :           0 : static CPubKey CreateLabeledSpendPubKey(const CPubKey& spend_pubkey, const SilentPaymentsLabel& label) {
     420                 :           0 :     secp256k1_pubkey spend_obj, labeled_spend_obj;
     421                 :           0 :     bool ret = secp256k1_ec_pubkey_parse(secp256k1_context_static, &spend_obj, spend_pubkey.data(), spend_pubkey.size());
     422         [ #  # ]:           0 :     assert(ret);
     423                 :           0 :     ret = secp256k1_silentpayments_recipient_create_labeled_spend_pubkey(secp256k1_context_static, &labeled_spend_obj, &spend_obj, label.Get());
     424         [ #  # ]:           0 :     assert(ret);
     425                 :           0 :     size_t pubkeylen = CPubKey::COMPRESSED_SIZE;
     426                 :           0 :     CPubKey labeled_spend_pubkey;
     427                 :           0 :     ret = secp256k1_ec_pubkey_serialize(secp256k1_context_static, (unsigned char*)labeled_spend_pubkey.begin(), &pubkeylen, &labeled_spend_obj, SECP256K1_EC_COMPRESSED);
     428         [ #  # ]:           0 :     assert(ret);
     429                 :           0 :     return labeled_spend_pubkey;
     430                 :             : }
     431                 :             : 
     432                 :           0 : SilentPaymentsReceiver::SilentPaymentsReceiver(const CKey& scan_key, const CPubKey& spend_pubkey,
     433   [ #  #  #  # ]:           0 :     const LabelTweakMap& labels) : m_scan_key(scan_key), m_spend_pubkey(spend_pubkey), m_labels(labels)
     434                 :             : {
     435         [ #  # ]:           0 :     m_change_it = m_labels.emplace(CreateLabel(scan_key, 0)).first;
     436         [ #  # ]:           0 :     m_spend_pubkey_obj = std::make_unique<secp256k1_pubkey>();
     437         [ #  # ]:           0 :     int ret = secp256k1_ec_pubkey_parse(secp256k1_context_static, m_spend_pubkey_obj.get(), m_spend_pubkey.data(), m_spend_pubkey.size());
     438         [ #  # ]:           0 :     assert(ret);
     439                 :           0 : }
     440                 :             : 
     441                 :           0 : SilentPaymentsReceiver::~SilentPaymentsReceiver() = default;
     442                 :             : 
     443                 :           0 : const LabelTweakMap& SilentPaymentsReceiver::GetLabels() const {
     444                 :           0 :     return m_labels;
     445                 :             : }
     446                 :             : 
     447                 :           0 : SilentPaymentsDestination SilentPaymentsReceiver::BuildLabeledDestination(const SilentPaymentsLabel& label) const {
     448                 :           0 :     CPubKey labeled_spend_pubkey = CreateLabeledSpendPubKey(m_spend_pubkey, label);
     449                 :           0 :     auto dest{SilentPaymentsDestination::From(m_scan_key.GetPubKey(), labeled_spend_pubkey)};
     450         [ #  # ]:           0 :     assert(dest);
     451         [ #  # ]:           0 :     return *dest;
     452                 :           0 : }
     453                 :             : 
     454                 :           0 : SilentPaymentsDestination SilentPaymentsReceiver::GenerateLabeledAddress(uint32_t m) {
     455         [ #  # ]:           0 :     assert(m >= 1);
     456         [ #  # ]:           0 :     auto it = m_labels.emplace(CreateLabel(m_scan_key, m)).first;
     457                 :           0 :     return BuildLabeledDestination(it->first);
     458                 :             : }
     459                 :             : 
     460                 :           0 : SilentPaymentsDestination SilentPaymentsReceiver::GetChangeDestination() const {
     461                 :           0 :     return BuildLabeledDestination(m_change_it->first);
     462                 :             : }
     463                 :             : 
     464                 :           0 : std::optional<std::vector<SilentPaymentsOutput>> SilentPaymentsReceiver::Scan(
     465                 :             :     const PrevoutsSummary& prevouts_summary,
     466                 :             :     const std::vector<XOnlyPubKey>& tx_outputs
     467                 :             : ) const {
     468                 :           0 :     bool ret;
     469                 :           0 :     std::vector<secp256k1_silentpayments_found_output> found_output_objs;
     470                 :           0 :     std::vector<secp256k1_silentpayments_found_output *> found_output_ptrs;
     471                 :           0 :     std::vector<secp256k1_xonly_pubkey> tx_output_objs;
     472                 :           0 :     std::vector<const secp256k1_xonly_pubkey *> tx_output_ptrs;
     473   [ #  #  #  # ]:           0 :     found_output_objs.reserve(tx_outputs.size());
     474   [ #  #  #  # ]:           0 :     found_output_ptrs.reserve(tx_outputs.size());
     475   [ #  #  #  # ]:           0 :     tx_output_objs.reserve(tx_outputs.size());
     476   [ #  #  #  # ]:           0 :     tx_output_ptrs.reserve(tx_outputs.size());
     477                 :             : 
     478         [ #  # ]:           0 :     assert(m_scan_key.IsValid());
     479         [ #  # ]:           0 :     assert(m_spend_pubkey_obj);
     480                 :             : 
     481         [ #  # ]:           0 :     for (const XOnlyPubKey& tx_output : tx_outputs) {
     482                 :           0 :         secp256k1_xonly_pubkey tx_output_obj;
     483         [ #  # ]:           0 :         ret = secp256k1_xonly_pubkey_parse(secp256k1_context_static, &tx_output_obj, tx_output.data());
     484         [ #  # ]:           0 :         if (!ret) {
     485                 :             :             // It is possible that a P2TR output encodes an invalid x-only pubkey.
     486                 :           0 :             continue;
     487                 :             :         }
     488         [ #  # ]:           0 :         tx_output_objs.push_back(tx_output_obj);
     489         [ #  # ]:           0 :         tx_output_ptrs.push_back(&tx_output_objs.back());
     490         [ #  # ]:           0 :         found_output_objs.emplace_back();
     491         [ #  # ]:           0 :         found_output_ptrs.push_back(&found_output_objs.back());
     492                 :             :     }
     493         [ #  # ]:           0 :     if (tx_output_ptrs.empty()) return std::vector<SilentPaymentsOutput>{};
     494                 :             : 
     495                 :             :     // Scan the outputs!
     496                 :           0 :     uint32_t n_found_outputs = 0;
     497   [ #  #  #  # ]:           0 :     ret = secp256k1_silentpayments_recipient_scan_outputs(secp256k1_context_static,
     498                 :             :         found_output_ptrs.data(), &n_found_outputs,
     499         [ #  # ]:           0 :         tx_output_ptrs.data(), tx_output_ptrs.size(),
     500                 :             :         UCharCast(m_scan_key.begin()),
     501                 :             :         prevouts_summary.Get(),
     502                 :           0 :         m_spend_pubkey_obj.get(),
     503                 :             :         LabelLookupCallback,
     504         [ #  # ]:           0 :         &m_labels
     505                 :             :     );
     506         [ #  # ]:           0 :     if (!ret) return std::nullopt;
     507                 :             : 
     508                 :           0 :     std::vector<SilentPaymentsOutput> outputs;
     509         [ #  # ]:           0 :     for (size_t i = 0; i < n_found_outputs; i++) {
     510                 :           0 :         SilentPaymentsOutput sp_output;
     511         [ #  # ]:           0 :         ret = secp256k1_xonly_pubkey_serialize(secp256k1_context_static, sp_output.output.begin(), &found_output_objs[i].output);
     512         [ #  # ]:           0 :         assert(ret);
     513                 :           0 :         sp_output.tweak = uint256{found_output_objs[i].tweak};
     514         [ #  # ]:           0 :         if (found_output_objs[i].found_with_label) {
     515         [ #  # ]:           0 :             sp_output.label = SilentPaymentsLabel(found_output_objs[i].label);
     516                 :             :         }
     517         [ #  # ]:           0 :         outputs.emplace_back(std::move(sp_output));
     518                 :           0 :     }
     519                 :           0 :     return outputs;
     520                 :           0 : }
     521                 :             : }; // namespace bip352
        

Generated by: LCOV version 2.5.0-full