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