Branch data Line data Source code
1 : : // Copyright (c) 2009-present 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 : : #ifndef BITCOIN_PSBT_H
6 : : #define BITCOIN_PSBT_H
7 : :
8 : : #include <common/types.h>
9 : : #include <musig.h>
10 : : #include <node/transaction.h>
11 : : #include <policy/feerate.h>
12 : : #include <primitives/transaction.h>
13 : : #include <pubkey.h>
14 : : #include <script/keyorigin.h>
15 : : #include <script/sign.h>
16 : : #include <script/signingprovider.h>
17 : : #include <span.h>
18 : : #include <streams.h>
19 : : #include <uint256.h>
20 : : #include <util/result.h>
21 : : #include <util/expected.h>
22 : :
23 : : #include <optional>
24 : : #include <bitset>
25 : :
26 : : namespace node {
27 : : enum class TransactionError;
28 : : } // namespace node
29 : :
30 : : using common::PSBTError;
31 : :
32 : : // Magic bytes
33 : : inline constexpr uint8_t PSBT_MAGIC_BYTES[5] = {'p', 's', 'b', 't', 0xff};
34 : :
35 : : // Global types
36 : : inline constexpr uint8_t PSBT_GLOBAL_UNSIGNED_TX = 0x00;
37 : : inline constexpr uint8_t PSBT_GLOBAL_XPUB = 0x01;
38 : : inline constexpr uint8_t PSBT_GLOBAL_TX_VERSION = 0x02;
39 : : inline constexpr uint8_t PSBT_GLOBAL_FALLBACK_LOCKTIME = 0x03;
40 : : inline constexpr uint8_t PSBT_GLOBAL_INPUT_COUNT = 0x04;
41 : : inline constexpr uint8_t PSBT_GLOBAL_OUTPUT_COUNT = 0x05;
42 : : inline constexpr uint8_t PSBT_GLOBAL_TX_MODIFIABLE = 0x06;
43 : : inline constexpr uint8_t PSBT_GLOBAL_VERSION = 0xFB;
44 : : inline constexpr uint8_t PSBT_GLOBAL_PROPRIETARY = 0xFC;
45 : :
46 : : // Input types
47 : : inline constexpr uint8_t PSBT_IN_NON_WITNESS_UTXO = 0x00;
48 : : inline constexpr uint8_t PSBT_IN_WITNESS_UTXO = 0x01;
49 : : inline constexpr uint8_t PSBT_IN_PARTIAL_SIG = 0x02;
50 : : inline constexpr uint8_t PSBT_IN_SIGHASH = 0x03;
51 : : inline constexpr uint8_t PSBT_IN_REDEEMSCRIPT = 0x04;
52 : : inline constexpr uint8_t PSBT_IN_WITNESSSCRIPT = 0x05;
53 : : inline constexpr uint8_t PSBT_IN_BIP32_DERIVATION = 0x06;
54 : : inline constexpr uint8_t PSBT_IN_SCRIPTSIG = 0x07;
55 : : inline constexpr uint8_t PSBT_IN_SCRIPTWITNESS = 0x08;
56 : : inline constexpr uint8_t PSBT_IN_RIPEMD160 = 0x0A;
57 : : inline constexpr uint8_t PSBT_IN_SHA256 = 0x0B;
58 : : inline constexpr uint8_t PSBT_IN_HASH160 = 0x0C;
59 : : inline constexpr uint8_t PSBT_IN_HASH256 = 0x0D;
60 : : inline constexpr uint8_t PSBT_IN_PREVIOUS_TXID = 0x0e;
61 : : inline constexpr uint8_t PSBT_IN_OUTPUT_INDEX = 0x0f;
62 : : inline constexpr uint8_t PSBT_IN_SEQUENCE = 0x10;
63 : : inline constexpr uint8_t PSBT_IN_REQUIRED_TIME_LOCKTIME = 0x11;
64 : : inline constexpr uint8_t PSBT_IN_REQUIRED_HEIGHT_LOCKTIME = 0x12;
65 : : inline constexpr uint8_t PSBT_IN_TAP_KEY_SIG = 0x13;
66 : : inline constexpr uint8_t PSBT_IN_TAP_SCRIPT_SIG = 0x14;
67 : : inline constexpr uint8_t PSBT_IN_TAP_LEAF_SCRIPT = 0x15;
68 : : inline constexpr uint8_t PSBT_IN_TAP_BIP32_DERIVATION = 0x16;
69 : : inline constexpr uint8_t PSBT_IN_TAP_INTERNAL_KEY = 0x17;
70 : : inline constexpr uint8_t PSBT_IN_TAP_MERKLE_ROOT = 0x18;
71 : : inline constexpr uint8_t PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS = 0x1a;
72 : : inline constexpr uint8_t PSBT_IN_MUSIG2_PUB_NONCE = 0x1b;
73 : : inline constexpr uint8_t PSBT_IN_MUSIG2_PARTIAL_SIG = 0x1c;
74 : : inline constexpr uint8_t PSBT_IN_PROPRIETARY = 0xFC;
75 : :
76 : : // Output types
77 : : inline constexpr uint8_t PSBT_OUT_REDEEMSCRIPT = 0x00;
78 : : inline constexpr uint8_t PSBT_OUT_WITNESSSCRIPT = 0x01;
79 : : inline constexpr uint8_t PSBT_OUT_BIP32_DERIVATION = 0x02;
80 : : inline constexpr uint8_t PSBT_OUT_AMOUNT = 0x03;
81 : : inline constexpr uint8_t PSBT_OUT_SCRIPT = 0x04;
82 : : inline constexpr uint8_t PSBT_OUT_TAP_INTERNAL_KEY = 0x05;
83 : : inline constexpr uint8_t PSBT_OUT_TAP_TREE = 0x06;
84 : : inline constexpr uint8_t PSBT_OUT_TAP_BIP32_DERIVATION = 0x07;
85 : : inline constexpr uint8_t PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS = 0x08;
86 : : inline constexpr uint8_t PSBT_OUT_PROPRIETARY = 0xFC;
87 : :
88 : : // The separator is 0x00. Reading this in means that the unserializer can interpret it
89 : : // as a 0 length key which indicates that this is the separator. The separator has no value.
90 : : inline constexpr uint8_t PSBT_SEPARATOR = 0x00;
91 : :
92 : : // BIP 174 does not specify a maximum file size, but we set a limit anyway
93 : : // to prevent reading a stream indefinitely and running out of memory.
94 : : inline constexpr std::streamsize MAX_FILE_SIZE_PSBT{100'000'000}; // 100 MB
95 : :
96 : : // PSBT version number
97 : : inline constexpr uint32_t PSBT_HIGHEST_VERSION = 2;
98 : :
99 : : /** A structure for PSBT proprietary types */
100 : 32669 : struct PSBTProprietary
101 : : {
102 : : uint64_t subtype;
103 : : std::vector<unsigned char> identifier;
104 : : std::vector<unsigned char> key;
105 : : std::vector<unsigned char> value;
106 : :
107 : 183493 : bool operator<(const PSBTProprietary &b) const {
108 : 183493 : return key < b.key;
109 : : }
110 : 0 : bool operator==(const PSBTProprietary &b) const {
111 [ # # ]: 0 : return key == b.key;
112 : : }
113 : : };
114 : :
115 : : // Takes a stream and multiple arguments and serializes them as if first serialized into a vector and then into the stream
116 : : // The resulting output into the stream has the total serialized length of all of the objects followed by all objects concatenated with each other.
117 : : template<typename Stream, typename... X>
118 : 181868 : void SerializeToVector(Stream& s, const X&... args)
119 : : {
120 : 181868 : SizeComputer sizecomp;
121 : 181868 : SerializeMany(sizecomp, args...);
122 : 181868 : WriteCompactSize(s, sizecomp.size());
123 : 181868 : SerializeMany(s, args...);
124 : 181868 : }
125 : :
126 : : // Takes a stream and multiple arguments and unserializes them first as a vector then each object individually in the order provided in the arguments
127 : : template<typename Stream, typename... X>
128 : 72301 : void UnserializeFromVector(Stream& s, X&&... args)
129 : : {
130 : 72301 : size_t expected_size = ReadCompactSize(s);
131 : 72289 : size_t remaining_before = s.size();
132 [ + + ]: 71806 : UnserializeMany(s, args...);
133 : 71806 : size_t remaining_after = s.size();
134 [ + + ]: 71806 : if (remaining_after + expected_size != remaining_before) {
135 [ + - ]: 890 : throw std::ios_base::failure("Size of value was not the stated size");
136 : : }
137 : 71361 : }
138 : :
139 : : // Deserialize bytes of given length from the stream as a KeyOriginInfo
140 : : template<typename Stream>
141 : 43918 : KeyOriginInfo DeserializeKeyOrigin(Stream& s, uint64_t length)
142 : : {
143 : : // Read in key path
144 [ + + + + ]: 43918 : if (length % 4 || length == 0) {
145 [ + - ]: 150 : throw std::ios_base::failure("Invalid length for HD key path");
146 : : }
147 : :
148 : 43843 : KeyOriginInfo hd_keypath;
149 [ + + ]: 43843 : s >> hd_keypath.fingerprint;
150 [ + + ]: 902788 : for (unsigned int i = 4; i < length; i += sizeof(uint32_t)) {
151 : : uint32_t index;
152 : 858972 : s >> index;
153 [ + - ]: 858972 : hd_keypath.path.push_back(index);
154 : : }
155 : 43776 : return hd_keypath;
156 : 67 : }
157 : :
158 : : // Deserialize a length prefixed KeyOriginInfo from a stream
159 : : template<typename Stream>
160 : 33634 : void DeserializeHDKeypath(Stream& s, KeyOriginInfo& hd_keypath)
161 : : {
162 : 33634 : hd_keypath = DeserializeKeyOrigin(s, ReadCompactSize(s));
163 : 33476 : }
164 : :
165 : : // Deserialize HD keypaths into a map
166 : : template<typename Stream>
167 [ - + ]: 25535 : void DeserializeHDKeypaths(Stream& s, const std::vector<unsigned char>& key, std::map<CPubKey, KeyOriginInfo>& hd_keypaths)
168 : : {
169 : : // Make sure that the key is the size of pubkey + 1
170 [ + + + + ]: 25535 : if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
171 [ + - ]: 14188 : throw std::ios_base::failure("Size of key was not the expected size for the type BIP32 keypath");
172 : : }
173 : : // Read in the pubkey from key
174 : 18441 : CPubKey pubkey(key.begin() + 1, key.end());
175 [ + + ]: 18441 : if (!pubkey.IsFullyValid()) {
176 [ + - ]: 206 : throw std::ios_base::failure("Invalid pubkey");
177 : : }
178 : :
179 : 18338 : KeyOriginInfo keypath;
180 [ + + ]: 18338 : DeserializeHDKeypath(s, keypath);
181 : :
182 : : // Add to map
183 [ + - ]: 18225 : hd_keypaths.emplace(pubkey, std::move(keypath));
184 : 18225 : }
185 : :
186 : : // Serialize a KeyOriginInfo to a stream
187 : : template<typename Stream>
188 : 24856 : void SerializeKeyOrigin(Stream& s, KeyOriginInfo hd_keypath)
189 : : {
190 : 24856 : s << hd_keypath.fingerprint;
191 [ + + ]: 668555 : for (const auto& path : hd_keypath.path) {
192 : 643699 : s << path;
193 : : }
194 : 24856 : }
195 : :
196 : : // Serialize a length prefixed KeyOriginInfo to a stream
197 : : template<typename Stream>
198 : 19393 : void SerializeHDKeypath(Stream& s, KeyOriginInfo hd_keypath)
199 : : {
200 [ - + ]: 19393 : WriteCompactSize(s, (hd_keypath.path.size() + 1) * sizeof(uint32_t));
201 [ + - ]: 19393 : SerializeKeyOrigin(s, hd_keypath);
202 : 19393 : }
203 : :
204 : : // Serialize HD keypaths to a stream from a map
205 : : template<typename Stream>
206 : 55972 : void SerializeHDKeypaths(Stream& s, const std::map<CPubKey, KeyOriginInfo>& hd_keypaths, CompactSizeWriter type)
207 : : {
208 [ + + ]: 68414 : for (const auto& keypath_pair : hd_keypaths) {
209 [ + + ]: 12546 : if (!keypath_pair.first.IsValid()) {
210 [ + - ]: 208 : throw std::ios_base::failure("Invalid CPubKey being serialized");
211 : : }
212 : 12442 : SerializeToVector(s, type, std::span{keypath_pair.first});
213 [ + - ]: 24884 : SerializeHDKeypath(s, keypath_pair.second);
214 : : }
215 : 55868 : }
216 : :
217 : : // Deserialize a PSBT_{IN/OUT}_MUSIG2_PARTICIPANT_PUBKEYS field
218 : : template<typename Stream>
219 : 9600 : void DeserializeMuSig2ParticipantPubkeys(Stream& s, SpanReader& skey, std::map<CPubKey, std::vector<CPubKey>>& out, std::string context)
220 : : {
221 : : std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
222 : 9600 : skey >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
223 : 9600 : CPubKey agg_pubkey(agg_pubkey_bytes);
224 [ + + ]: 9600 : if (!agg_pubkey.IsFullyValid()) {
225 [ + - + - ]: 60 : throw std::ios_base::failure(context + " musig2 aggregate pubkey is invalid");
226 : : }
227 : :
228 : 9570 : std::vector<CPubKey> participants;
229 [ + + ]: 9570 : std::vector<unsigned char> val;
230 [ - + ]: 9543 : s >> val;
231 : 9543 : SpanReader s_val{val};
232 [ + + ]: 14095 : while (s_val.size() >= CPubKey::COMPRESSED_SIZE) {
233 : : std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
234 [ + - ]: 9206 : s_val >> std::as_writable_bytes(std::span{part_pubkey_bytes});
235 : 4603 : CPubKey participant(part_pubkey_bytes);
236 [ + - + + ]: 4603 : if (!participant.IsFullyValid()) {
237 [ + - + - ]: 102 : throw std::ios_base::failure(context + " musig2 participant pubkey is invalid");
238 : : }
239 [ + - ]: 4552 : participants.push_back(participant);
240 : : }
241 [ + + ]: 9492 : if (!s_val.empty()) {
242 [ + - + - ]: 58 : throw std::ios_base::failure(context + " musig2 participants pubkeys value size is not a multiple of 33");
243 : : }
244 : :
245 [ + - ]: 9463 : out.emplace(agg_pubkey, participants);
246 : 9570 : }
247 : :
248 : : // Deserialize the MuSig2 participant identifiers from PSBT_MUSIG2_{PUBNONCE/PARTIAL_SIG} fields
249 : : // Both fields contain the same data after the type byte - aggregate pubkey | participant pubkey | leaf script hash
250 : : template<typename Stream>
251 : 13013 : void DeserializeMuSig2ParticipantDataIdentifier(Stream& skey, CPubKey& agg_pub, CPubKey& part_pub, uint256& leaf_hash)
252 : : {
253 : 13013 : leaf_hash.SetNull();
254 : :
255 : : std::array<unsigned char, CPubKey::COMPRESSED_SIZE> part_pubkey_bytes;
256 : : std::array<unsigned char, CPubKey::COMPRESSED_SIZE> agg_pubkey_bytes;
257 : :
258 : 13013 : skey >> std::as_writable_bytes(std::span{part_pubkey_bytes}) >> std::as_writable_bytes(std::span{agg_pubkey_bytes});
259 : 13013 : agg_pub.Set(agg_pubkey_bytes.begin(), agg_pubkey_bytes.end());
260 [ + + ]: 13013 : if (!agg_pub.IsFullyValid()) {
261 [ + - ]: 52 : throw std::ios_base::failure("musig2 aggregate pubkey is invalid");
262 : : }
263 : :
264 : 12987 : part_pub.Set(part_pubkey_bytes.begin(), part_pubkey_bytes.end());
265 [ + + ]: 12987 : if (!part_pub.IsFullyValid()) {
266 [ + - ]: 24 : throw std::ios_base::failure("musig2 participant pubkey is invalid");
267 : : }
268 : :
269 [ + + ]: 12975 : if (!skey.empty()) {
270 : 6298 : skey >> leaf_hash;
271 : : }
272 : 12975 : }
273 : :
274 : 170575 : static inline void ExpectedKeySize(const std::string& key_name, const std::vector<unsigned char>& key, uint64_t expected_size) {
275 [ - + + + ]: 170575 : if (key.size() != expected_size) {
276 [ + - + - ]: 2764 : throw std::ios_base::failure(tfm::format("Size of key was not %d for the type %s", expected_size, key_name));
277 : : }
278 : 169193 : }
279 : :
280 : : /** A structure for PSBTs which contain per-input information */
281 : : class PSBTInput
282 : : {
283 : : private:
284 : 5800 : uint32_t m_psbt_version;
285 : :
286 : : public:
287 [ + - ]: 5800 : CTransactionRef non_witness_utxo;
288 : 5800 : CTxOut witness_utxo;
289 : : CScript redeem_script;
290 : : CScript witness_script;
291 : : CScript final_script_sig;
292 : : CScriptWitness final_script_witness;
293 : 5800 : std::map<CPubKey, KeyOriginInfo> hd_keypaths;
294 : 5800 : std::map<CKeyID, SigPair> partial_sigs;
295 : 5800 : std::map<uint160, std::vector<unsigned char>> ripemd160_preimages;
296 : 5800 : std::map<uint256, std::vector<unsigned char>> sha256_preimages;
297 : 5800 : std::map<uint160, std::vector<unsigned char>> hash160_preimages;
298 : 5800 : std::map<uint256, std::vector<unsigned char>> hash256_preimages;
299 : :
300 : : Txid prev_txid;
301 : 5800 : uint32_t prev_out;
302 [ + - ]: 5800 : std::optional<uint32_t> sequence;
303 : 5800 : std::optional<uint32_t> time_locktime;
304 : 5800 : std::optional<uint32_t> height_locktime;
305 : :
306 : : // Taproot fields
307 : 5800 : std::vector<unsigned char> m_tap_key_sig;
308 : 5800 : std::map<std::pair<XOnlyPubKey, uint256>, std::vector<unsigned char>> m_tap_script_sigs;
309 : 5800 : std::map<std::pair<std::vector<unsigned char>, int>, std::set<std::vector<unsigned char>, ShortestVectorFirstComparator>> m_tap_scripts;
310 : 5800 : std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
311 : : XOnlyPubKey m_tap_internal_key;
312 : : uint256 m_tap_merkle_root;
313 : :
314 : : // MuSig2 fields
315 : 5800 : std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
316 : : // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to pubnonce
317 : 5800 : std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, std::vector<uint8_t>>> m_musig2_pubnonces;
318 : : // Key is the aggregate pubkey and the script leaf hash, value is a map of participant pubkey to partial_sig
319 : 5800 : std::map<std::pair<CPubKey, uint256>, std::map<CPubKey, uint256>> m_musig2_partial_sigs;
320 : :
321 : 5800 : std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
322 : 5800 : std::set<PSBTProprietary> m_proprietary;
323 [ + - ]: 5800 : std::optional<int> sighash_type;
324 : :
325 : : void FillSignatureData(SignatureData& sigdata) const;
326 : : void FromSignatureData(const SignatureData& sigdata);
327 : : [[nodiscard]] bool Merge(const PSBTInput& input);
328 : 7535 : uint32_t GetVersion() const { return m_psbt_version; }
329 : : COutPoint GetOutPoint() const;
330 : : /**
331 : : * Retrieves the UTXO for this input
332 : : *
333 : : * @param[out] utxo The UTXO of this input
334 : : * @return Whether the UTXO could be retrieved
335 : : */
336 : : bool GetUTXO(CTxOut& utxo) const;
337 : : bool HasSignatures() const;
338 : :
339 : 53236 : explicit PSBTInput(uint32_t psbt_version, const Txid& prev_txid, uint32_t prev_out, std::optional<uint32_t> sequence = std::nullopt)
340 : 53236 : : m_psbt_version(psbt_version),
341 : 53236 : prev_txid(prev_txid),
342 [ - + ]: 53236 : prev_out(prev_out),
343 [ - + ]: 53236 : sequence(sequence)
344 : : {
345 [ - + ]: 53236 : assert(m_psbt_version == 0 || m_psbt_version == 2);
346 : 53236 : }
347 : :
348 : : // Construct a PSBTInput when the previous txid and output index are expected to be serialized
349 : : template <typename Stream>
350 : 0 : explicit PSBTInput(deserialize_type, Stream& s, uint32_t psbt_version)
351 [ # # ]: 0 : : m_psbt_version(psbt_version)
352 : : {
353 [ # # ]: 0 : assert(m_psbt_version == 2);
354 [ # # ]: 0 : Unserialize(s);
355 [ # # ]: 0 : }
356 : :
357 : 104400 : bool operator==(const PSBTInput&) const = default;
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - + -
+ - + - +
- + - +
- ]
358 : :
359 : : template <typename Stream>
360 : 27998 : inline void Serialize(Stream& s) const {
361 : : // Write the utxo
362 [ + + ]: 27998 : if (non_witness_utxo) {
363 : 412 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_NON_WITNESS_UTXO));
364 : 412 : SerializeToVector(s, TX_NO_WITNESS(non_witness_utxo));
365 : : }
366 [ + + ]: 27998 : if (!witness_utxo.IsNull()) {
367 : 10505 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESS_UTXO));
368 : 10505 : SerializeToVector(s, witness_utxo);
369 : : }
370 : :
371 [ + + + + : 30952 : if (final_script_sig.empty() && final_script_witness.IsNull()) {
+ + ]
372 : : // Write any partial signatures
373 [ + + ]: 25638 : for (const auto& sig_pair : partial_sigs) {
374 : 1797 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_PARTIAL_SIG), std::span{sig_pair.second.first});
375 : 1797 : s << sig_pair.second.second;
376 : : }
377 : :
378 : : // Write the sighash type
379 [ + + ]: 23841 : if (sighash_type != std::nullopt) {
380 : 76 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SIGHASH));
381 : 76 : SerializeToVector(s, *sighash_type);
382 : : }
383 : :
384 : : // Write the redeem script
385 [ + + + + ]: 24538 : if (!redeem_script.empty()) {
386 : 1013 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_REDEEMSCRIPT));
387 : 1013 : s << redeem_script;
388 : : }
389 : :
390 : : // Write the witness script
391 [ + + + + ]: 31106 : if (!witness_script.empty()) {
392 : 7435 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_WITNESSSCRIPT));
393 : 7435 : s << witness_script;
394 : : }
395 : :
396 : : // Write any hd keypaths
397 : 23841 : SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_IN_BIP32_DERIVATION));
398 : :
399 : : // Write any ripemd160 preimage
400 [ + + ]: 26932 : for (const auto& [hash, preimage] : ripemd160_preimages) {
401 : 3091 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_RIPEMD160), std::span{hash});
402 : 3091 : s << preimage;
403 : : }
404 : :
405 : : // Write any sha256 preimage
406 [ + + ]: 28762 : for (const auto& [hash, preimage] : sha256_preimages) {
407 : 4921 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SHA256), std::span{hash});
408 : 4921 : s << preimage;
409 : : }
410 : :
411 : : // Write any hash160 preimage
412 [ + + ]: 30132 : for (const auto& [hash, preimage] : hash160_preimages) {
413 : 6291 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH160), std::span{hash});
414 : 6291 : s << preimage;
415 : : }
416 : :
417 : : // Write any hash256 preimage
418 [ + + ]: 29208 : for (const auto& [hash, preimage] : hash256_preimages) {
419 : 5367 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_HASH256), std::span{hash});
420 : 5367 : s << preimage;
421 : : }
422 : :
423 : : // Write taproot key sig
424 [ + + ]: 23841 : if (!m_tap_key_sig.empty()) {
425 : 523 : SerializeToVector(s, PSBT_IN_TAP_KEY_SIG);
426 : 523 : s << m_tap_key_sig;
427 : : }
428 : :
429 : : // Write taproot script sigs
430 [ + + ]: 27542 : for (const auto& [pubkey_leaf, sig] : m_tap_script_sigs) {
431 : 3701 : const auto& [xonly, leaf_hash] = pubkey_leaf;
432 : 3701 : SerializeToVector(s, PSBT_IN_TAP_SCRIPT_SIG, xonly, leaf_hash);
433 : 3701 : s << sig;
434 : : }
435 : :
436 : : // Write taproot leaf scripts
437 [ + + ]: 35778 : for (const auto& [leaf, control_blocks] : m_tap_scripts) {
438 : 11937 : const auto& [script, leaf_ver] = leaf;
439 [ - + + + ]: 25595 : for (const auto& control_block : control_blocks) {
440 : 13658 : SerializeToVector(s, PSBT_IN_TAP_LEAF_SCRIPT, std::span{control_block});
441 : 13658 : std::vector<unsigned char> value_v(script.begin(), script.end());
442 [ + - + - ]: 13658 : value_v.push_back((uint8_t)leaf_ver);
443 : 13658 : s << value_v;
444 : : }
445 : : }
446 : :
447 : : // Write taproot bip32 keypaths
448 [ + + ]: 26620 : for (const auto& [xonly, leaf_origin] : m_tap_bip32_paths) {
449 : 2779 : const auto& [leaf_hashes, origin] = leaf_origin;
450 : 2779 : SerializeToVector(s, PSBT_IN_TAP_BIP32_DERIVATION, xonly);
451 : 2779 : std::vector<unsigned char> value;
452 [ + - ]: 2779 : VectorWriter s_value{value, 0};
453 [ + - ]: 2779 : s_value << leaf_hashes;
454 [ + - + - ]: 5558 : SerializeKeyOrigin(s_value, origin);
455 : 2779 : s << value;
456 : : }
457 : :
458 : : // Write taproot internal key
459 [ + + ]: 47682 : if (!m_tap_internal_key.IsNull()) {
460 : 192 : SerializeToVector(s, PSBT_IN_TAP_INTERNAL_KEY);
461 [ + - ]: 384 : s << ToByteVector(m_tap_internal_key);
462 : : }
463 : :
464 : : // Write taproot merkle root
465 [ + + ]: 47682 : if (!m_tap_merkle_root.IsNull()) {
466 : 2055 : SerializeToVector(s, PSBT_IN_TAP_MERKLE_ROOT);
467 : 2055 : SerializeToVector(s, m_tap_merkle_root);
468 : : }
469 : :
470 : : // Write MuSig2 Participants
471 [ + + ]: 24756 : for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
472 : 915 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
473 : 915 : std::vector<unsigned char> value;
474 [ + - ]: 915 : VectorWriter s_value{value, 0};
475 [ + - + + ]: 1751 : for (auto& pk : part_pubs) {
476 [ + - ]: 1672 : s_value << std::span{pk};
477 : : }
478 : 915 : s << value;
479 : : }
480 : :
481 : : // Write MuSig2 pubnonces
482 [ + + ]: 26188 : for (const auto& [agg_pubkey_leaf_hash, pubnonces] : m_musig2_pubnonces) {
483 : 2347 : const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
484 [ + + ]: 5478 : for (const auto& [part_pubkey, pubnonce] : pubnonces) {
485 [ + + ]: 6262 : if (leaf_hash.IsNull()) {
486 : 1565 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey});
487 : : } else {
488 : 1566 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PUB_NONCE), std::span{part_pubkey}, std::span{agg_pubkey}, leaf_hash);
489 : : }
490 : 3131 : s << pubnonce;
491 : : }
492 : : }
493 : :
494 : : // Write MuSig2 partial signatures
495 [ + + ]: 27818 : for (const auto& [agg_pubkey_leaf_hash, psigs] : m_musig2_partial_sigs) {
496 : 3977 : const auto& [agg_pubkey, leaf_hash] = agg_pubkey_leaf_hash;
497 [ + + ]: 8499 : for (const auto& [pubkey, psig] : psigs) {
498 [ + + ]: 9044 : if (leaf_hash.IsNull()) {
499 : 2186 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey});
500 : : } else {
501 : 2336 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_MUSIG2_PARTIAL_SIG), std::span{pubkey}, std::span{agg_pubkey}, leaf_hash);
502 : : }
503 : 4522 : SerializeToVector(s, psig);
504 : : }
505 : : }
506 : : }
507 : :
508 : : // Write script sig
509 [ + + + + ]: 30952 : if (!final_script_sig.empty()) {
510 : 3611 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTSIG));
511 : 3611 : s << final_script_sig;
512 : : }
513 : : // write script witness
514 [ + + ]: 27998 : if (!final_script_witness.IsNull()) {
515 : 561 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SCRIPTWITNESS));
516 : 561 : SerializeToVector(s, final_script_witness.stack);
517 : : }
518 : :
519 : : // Write PSBTv2 fields
520 [ + + ]: 27998 : if (m_psbt_version >= 2) {
521 : : // Write prev txid, vout, sequence, and lock times
522 : 760 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_PREVIOUS_TXID));
523 : 760 : SerializeToVector(s, prev_txid);
524 : :
525 : 760 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_OUTPUT_INDEX));
526 : 760 : SerializeToVector(s, prev_out);
527 : :
528 [ + - ]: 760 : if (sequence != std::nullopt) {
529 : 760 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_SEQUENCE));
530 : 760 : SerializeToVector(s, *sequence);
531 : : }
532 [ - + ]: 760 : if (time_locktime != std::nullopt) {
533 : 0 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_REQUIRED_TIME_LOCKTIME));
534 : 0 : SerializeToVector(s, *time_locktime);
535 : : }
536 [ - + ]: 760 : if (height_locktime != std::nullopt) {
537 : 0 : SerializeToVector(s, CompactSizeWriter(PSBT_IN_REQUIRED_HEIGHT_LOCKTIME));
538 : 0 : SerializeToVector(s, *height_locktime);
539 : : }
540 : : }
541 : :
542 : : // Write proprietary things
543 [ + + ]: 31407 : for (const auto& entry : m_proprietary) {
544 : 3409 : s << entry.key;
545 : 3409 : s << entry.value;
546 : : }
547 : :
548 : : // Write unknown things
549 [ + + ]: 69685 : for (auto& entry : unknown) {
550 : 41687 : s << entry.first;
551 : 41687 : s << entry.second;
552 : : }
553 : :
554 : 27998 : s << PSBT_SEPARATOR;
555 : 27998 : }
556 : :
557 : :
558 : : template <typename Stream>
559 : 44248 : inline void Unserialize(Stream& s) {
560 : : // Used for duplicate key detection
561 : 44248 : std::set<std::vector<unsigned char>> key_lookup;
562 : : // Cache whether PSBTv2 required fields were seen
563 : 44248 : bool found_prev_txid = false;
564 : 44248 : bool found_prev_out = false;
565 : :
566 : : // Read loop
567 : 44248 : bool found_sep = false;
568 [ + + ]: 262745 : while(!s.empty()) {
569 : : // Read the key of format "<keylen><keytype><keydata>" after which
570 : : // "key" will contain "<keytype><keydata>"
571 [ + + ]: 259661 : std::vector<unsigned char> key;
572 : 259349 : s >> key;
573 : :
574 : : // the key is empty if that was actually a separator byte
575 : : // This is a special case for key lengths 0 as those are not allowed (except for separator)
576 [ + + ]: 259349 : if (key.empty()) {
577 : 41164 : found_sep = true;
578 : : break;
579 : : }
580 : :
581 : : // Duplicate keys are not permitted
582 [ + - + + ]: 218185 : if (!key_lookup.emplace(key).second) {
583 [ - + + - : 344 : throw std::ios_base::failure(tfm::format("Duplicate Key, input key \"%s\" already provided", HexStr(key)));
+ - + - ]
584 : : }
585 : :
586 : : // "skey" is used so that "key" is unchanged after reading keytype below
587 : 218013 : SpanReader skey{key};
588 : : // keytype is of the format compact size uint at the beginning of "key"
589 [ + + ]: 218013 : uint64_t type = ReadCompactSize(skey);
590 : :
591 : : // Do stuff based on keytype "type", i.e., key checks, reading values of the
592 : : // format "<valuelen><valuedata>" from the stream "s", and value checks
593 : 218006 : switch(type) {
[ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + + +
+ + + +
+ ]
594 : 988 : case PSBT_IN_NON_WITNESS_UTXO:
595 : : {
596 [ + - + + ]: 1012 : ExpectedKeySize("Input Non-witness UTXO", key, 1);
597 : : // Set the stream to unserialize with witness since this is always a valid network transaction
598 [ + + ]: 964 : UnserializeFromVector(s, TX_WITH_WITNESS(non_witness_utxo));
599 : : break;
600 : : }
601 : 12374 : case PSBT_IN_WITNESS_UTXO:
602 [ + - + + ]: 12393 : ExpectedKeySize("Input Witness UTXO", key, 1);
603 [ + + ]: 12355 : UnserializeFromVector(s, witness_utxo);
604 : : break;
605 [ - + ]: 5094 : case PSBT_IN_PARTIAL_SIG:
606 : : {
607 : : // Make sure that the key is the size of pubkey + 1
608 [ + + + + ]: 5094 : if (key.size() != CPubKey::SIZE + 1 && key.size() != CPubKey::COMPRESSED_SIZE + 1) {
609 [ + - ]: 30 : throw std::ios_base::failure("Size of key was not the expected size for the type partial signature pubkey");
610 : : }
611 : : // Read in the pubkey from key
612 : 5079 : CPubKey pubkey(key.begin() + 1, key.end());
613 [ + - + + ]: 5079 : if (!pubkey.IsFullyValid()) {
614 [ + - ]: 82 : throw std::ios_base::failure("Invalid pubkey");
615 : : }
616 : :
617 : : // Read in the signature from value
618 [ + + ]: 5038 : std::vector<unsigned char> sig;
619 : 4760 : s >> sig;
620 : :
621 : : // Check that the signature is validly encoded
622 [ + + + - : 4760 : if (sig.empty() || !CheckSignatureEncoding(sig, SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_STRICTENC, nullptr)) {
+ + ]
623 [ + - ]: 614 : throw std::ios_base::failure("Signature is not a valid encoding");
624 : : }
625 : :
626 : : // Add to list
627 [ + - + - ]: 8906 : partial_sigs.emplace(pubkey.GetID(), SigPair(pubkey, std::move(sig)));
628 : : break;
629 : 5038 : }
630 : 222 : case PSBT_IN_SIGHASH:
631 [ + - + + ]: 233 : ExpectedKeySize("Input Sighash Type", key, 1);
632 : : int sighash;
633 [ + + ]: 211 : UnserializeFromVector(s, sighash);
634 : 199 : sighash_type = sighash;
635 : 199 : break;
636 : 1981 : case PSBT_IN_REDEEMSCRIPT:
637 : : {
638 [ + - + + ]: 1993 : ExpectedKeySize("Input redeemScript", key, 1);
639 [ + + ]: 1969 : s >> redeem_script;
640 : : break;
641 : : }
642 : 14255 : case PSBT_IN_WITNESSSCRIPT:
643 : : {
644 [ + - + + ]: 14266 : ExpectedKeySize("Input witnessScript", key, 1);
645 [ + + ]: 14244 : s >> witness_script;
646 : : break;
647 : : }
648 : 4736 : case PSBT_IN_BIP32_DERIVATION:
649 : : {
650 [ + + ]: 4736 : DeserializeHDKeypaths(s, key, hd_keypaths);
651 : : break;
652 : : }
653 : 4231 : case PSBT_IN_SCRIPTSIG:
654 : : {
655 [ + - + + ]: 4246 : ExpectedKeySize("Input Final scriptSig", key, 1);
656 [ + + ]: 219761 : s >> final_script_sig;
657 : : break;
658 : : }
659 : 942 : case PSBT_IN_SCRIPTWITNESS:
660 : : {
661 [ + - + + ]: 957 : ExpectedKeySize("Input Final scriptWitness", key, 1);
662 [ + + ]: 927 : UnserializeFromVector(s, final_script_witness.stack);
663 : : break;
664 : : }
665 : 5772 : case PSBT_IN_RIPEMD160:
666 : : {
667 [ + - + + : 11544 : ExpectedKeySize("Input RIPEMD160 Preimage", key, CRIPEMD160::OUTPUT_SIZE + 1);
+ - ]
668 : : // Read in the hash from key
669 [ + - ]: 5760 : std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
670 : 5760 : uint160 hash(hash_vec);
671 : :
672 : : // Read in the preimage from value
673 [ + + ]: 5760 : std::vector<unsigned char> preimage;
674 : 5737 : s >> preimage;
675 : :
676 : : // Add to preimages list
677 [ + - ]: 5737 : ripemd160_preimages.emplace(hash, std::move(preimage));
678 : : break;
679 : 5783 : }
680 : 7664 : case PSBT_IN_SHA256:
681 : : {
682 [ + - + + : 15328 : ExpectedKeySize("Input SHA256 Preimage", key, CSHA256::OUTPUT_SIZE + 1);
+ - ]
683 : : // Read in the hash from key
684 [ + - ]: 7652 : std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
685 : 7652 : uint256 hash(hash_vec);
686 : :
687 : : // Read in the preimage from value
688 [ + + ]: 7652 : std::vector<unsigned char> preimage;
689 : 7633 : s >> preimage;
690 : :
691 : : // Add to preimages list
692 [ + - ]: 7633 : sha256_preimages.emplace(hash, std::move(preimage));
693 : : break;
694 : 7671 : }
695 : 10074 : case PSBT_IN_HASH160:
696 : : {
697 [ + - + + : 20148 : ExpectedKeySize("Input Hash160 Preimage", key, CHash160::OUTPUT_SIZE + 1);
+ - ]
698 : : // Read in the hash from key
699 [ + - ]: 10061 : std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
700 : 10061 : uint160 hash(hash_vec);
701 : :
702 : : // Read in the preimage from value
703 [ + + ]: 10061 : std::vector<unsigned char> preimage;
704 : 10038 : s >> preimage;
705 : :
706 : : // Add to preimages list
707 [ + - ]: 10038 : hash160_preimages.emplace(hash, std::move(preimage));
708 : : break;
709 : 10084 : }
710 : 10055 : case PSBT_IN_HASH256:
711 : : {
712 [ + - + + : 20110 : ExpectedKeySize("Input Hash256 Preimage", key, CHash256::OUTPUT_SIZE + 1);
+ - ]
713 : : // Read in the hash from key
714 [ + - ]: 10043 : std::vector<unsigned char> hash_vec(key.begin() + 1, key.end());
715 : 10043 : uint256 hash(hash_vec);
716 : :
717 : : // Read in the preimage from value
718 [ + + ]: 10043 : std::vector<unsigned char> preimage;
719 : 10024 : s >> preimage;
720 : :
721 : : // Add to preimages list
722 [ + - ]: 10024 : hash256_preimages.emplace(hash, std::move(preimage));
723 : : break;
724 : 10062 : }
725 : 40 : case PSBT_IN_PREVIOUS_TXID:
726 : : {
727 [ + - + + ]: 67 : ExpectedKeySize("Input Previous TXID", key, 1);
728 [ + - ]: 13 : if (m_psbt_version < 2) {
729 [ + - ]: 26 : throw std::ios_base::failure("Previous txid is not allowed in PSBTv0");
730 : : }
731 [ # # ]: 0 : UnserializeFromVector(s, prev_txid);
732 : : found_prev_txid = true;
733 : : break;
734 : : }
735 : 29 : case PSBT_IN_OUTPUT_INDEX:
736 : : {
737 [ + - + + ]: 45 : ExpectedKeySize("Input Previous Output's Index", key, 1);
738 [ + - ]: 13 : if (m_psbt_version < 2) {
739 [ + - ]: 26 : throw std::ios_base::failure("Previous output's index is not allowed in PSBTv0");
740 : : }
741 [ # # ]: 0 : UnserializeFromVector(s, prev_out);
742 : : found_prev_out = true;
743 : : break;
744 : : }
745 : 112 : case PSBT_IN_SEQUENCE:
746 : : {
747 [ + - + + ]: 212 : ExpectedKeySize("Input Sequence", key, 1);
748 [ + - ]: 12 : if (m_psbt_version < 2) {
749 [ + - ]: 24 : throw std::ios_base::failure("Sequence is not allowed in PSBTv0");
750 : : }
751 [ # # ]: 0 : sequence.emplace();
752 [ # # ]: 0 : UnserializeFromVector(s, *sequence);
753 : : break;
754 : : }
755 : 179 : case PSBT_IN_REQUIRED_TIME_LOCKTIME:
756 : : {
757 [ + - + + ]: 346 : ExpectedKeySize("Input Required Time Based Locktime", key, 1);
758 [ + - ]: 12 : if (m_psbt_version < 2) {
759 [ + - ]: 24 : throw std::ios_base::failure("Required time based locktime is not allowed in PSBTv0");
760 : : }
761 [ # # ]: 0 : time_locktime.emplace();
762 [ # # ]: 0 : UnserializeFromVector(s, *time_locktime);
763 [ # # ]: 0 : if (*time_locktime < LOCKTIME_THRESHOLD) {
764 [ # # ]: 0 : throw std::ios_base::failure("Required time based locktime is invalid (less than 500000000)");
765 : : }
766 : : break;
767 : : }
768 : 32 : case PSBT_IN_REQUIRED_HEIGHT_LOCKTIME:
769 : : {
770 [ + - + + ]: 52 : ExpectedKeySize("Input Required Height Based Locktime", key, 1);
771 [ + - ]: 12 : if (m_psbt_version < 2) {
772 [ + - ]: 24 : throw std::ios_base::failure("Required height based locktime is not allowed in PSBTv0");
773 : : }
774 [ # # ]: 0 : height_locktime.emplace();
775 [ # # ]: 0 : UnserializeFromVector(s, *height_locktime);
776 [ # # ]: 0 : if (*height_locktime >= LOCKTIME_THRESHOLD) {
777 [ # # ]: 0 : throw std::ios_base::failure("Required height based locktime is invalid (greater than or equal to 500000000)");
778 [ # # ]: 0 : } else if (*height_locktime == 0) {
779 [ # # ]: 0 : throw std::ios_base::failure("Required height based locktime is invalid (0)");
780 : : }
781 : : break;
782 : : }
783 : 773 : case PSBT_IN_TAP_KEY_SIG:
784 : : {
785 [ + - + + ]: 782 : ExpectedKeySize("Input Taproot Key Path Signature", key, 1);
786 [ + + ]: 764 : s >> m_tap_key_sig;
787 [ - + + + ]: 750 : if (m_tap_key_sig.size() < 64) {
788 [ + - ]: 24 : throw std::ios_base::failure("Input Taproot key path signature is shorter than 64 bytes");
789 [ + + ]: 738 : } else if (m_tap_key_sig.size() > 65) {
790 [ + - ]: 16 : throw std::ios_base::failure("Input Taproot key path signature is longer than 65 bytes");
791 : : }
792 : : break;
793 : : }
794 : 6996 : case PSBT_IN_TAP_SCRIPT_SIG:
795 : : {
796 [ + - + + : 13992 : ExpectedKeySize("Input Taproot Script Path Signature", key, 65);
- + ]
797 : 6983 : SpanReader s_key{std::span{key}.subspan(1)};
798 : 6983 : XOnlyPubKey xonly;
799 [ + - ]: 6983 : uint256 hash;
800 [ + - ]: 6983 : s_key >> xonly;
801 : 6983 : s_key >> hash;
802 [ + + ]: 6983 : std::vector<unsigned char> sig;
803 [ - + ]: 6967 : s >> sig;
804 [ + + ]: 6967 : if (sig.size() < 64) {
805 [ + - ]: 36 : throw std::ios_base::failure("Input Taproot script path signature is shorter than 64 bytes");
806 [ + + ]: 6949 : } else if (sig.size() > 65) {
807 [ + - ]: 22 : throw std::ios_base::failure("Input Taproot script path signature is longer than 65 bytes");
808 : : }
809 [ + - ]: 6938 : m_tap_script_sigs.emplace(std::make_pair(xonly, hash), sig);
810 : : break;
811 : 6983 : }
812 [ - + ]: 24206 : case PSBT_IN_TAP_LEAF_SCRIPT:
813 : : {
814 [ + + ]: 24206 : if (key.size() < 34) {
815 [ + - ]: 38 : throw std::ios_base::failure("Input Taproot leaf script key is not at least 34 bytes");
816 [ + + ]: 24187 : } else if ((key.size() - 2) % 32 != 0) {
817 [ + - ]: 42 : throw std::ios_base::failure("Input Taproot leaf script key's control block size is not valid");
818 : : }
819 [ + + ]: 24166 : std::vector<unsigned char> script_v;
820 : 24135 : s >> script_v;
821 [ + + ]: 24135 : if (script_v.empty()) {
822 [ + - ]: 32 : throw std::ios_base::failure("Input Taproot leaf script must be at least 1 byte");
823 : : }
824 [ + - ]: 24119 : uint8_t leaf_ver = script_v.back();
825 : 24119 : script_v.pop_back();
826 [ + - ]: 24119 : const auto leaf_script = std::make_pair(script_v, (int)leaf_ver);
827 [ + - + - : 48238 : m_tap_scripts[leaf_script].insert(std::vector<unsigned char>(key.begin() + 1, key.end()));
+ - ]
828 : : break;
829 : 24166 : }
830 : 5464 : case PSBT_IN_TAP_BIP32_DERIVATION:
831 : : {
832 [ + - + + : 10928 : ExpectedKeySize("Input Taproot BIP32 Keypath", key, 33);
- + ]
833 : 5453 : SpanReader s_key{std::span{key}.subspan(1)};
834 [ + - ]: 5453 : XOnlyPubKey xonly;
835 [ + + ]: 5453 : s_key >> xonly;
836 : 5453 : std::set<uint256> leaf_hashes;
837 [ + + + + ]: 5453 : uint64_t value_len = ReadCompactSize(s);
838 [ + + ]: 5445 : size_t before_hashes = s.size();
839 [ + + ]: 5371 : s >> leaf_hashes;
840 : 5371 : size_t after_hashes = s.size();
841 : 5371 : size_t hashes_len = before_hashes - after_hashes;
842 [ + + ]: 5371 : if (hashes_len > value_len) {
843 [ + - ]: 30 : throw std::ios_base::failure("Input Taproot BIP32 keypath has an invalid length");
844 : : }
845 : 5356 : size_t origin_len = value_len - hashes_len;
846 [ + + + - ]: 10701 : m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
847 : : break;
848 : 5453 : }
849 : 307 : case PSBT_IN_TAP_INTERNAL_KEY:
850 : : {
851 [ + - + + ]: 319 : ExpectedKeySize("Input Taproot Internal Key", key, 1);
852 [ + + ]: 295 : UnserializeFromVector(s, m_tap_internal_key);
853 : : break;
854 : : }
855 : 3765 : case PSBT_IN_TAP_MERKLE_ROOT:
856 : : {
857 [ + - + + ]: 3777 : ExpectedKeySize("Input Taproot Merkle Root", key, 1);
858 [ + + ]: 3753 : UnserializeFromVector(s, m_tap_merkle_root);
859 : : break;
860 : : }
861 : 1558 : case PSBT_IN_MUSIG2_PARTICIPANT_PUBKEYS:
862 : : {
863 [ + - + + ]: 1567 : ExpectedKeySize("Input MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
864 [ + - + + ]: 3098 : DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Input"});
865 : : break;
866 : : }
867 [ - + ]: 5504 : case PSBT_IN_MUSIG2_PUB_NONCE:
868 : : {
869 [ + + + + ]: 5504 : if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
870 [ + - ]: 26 : throw std::ios_base::failure("Input musig2 pubnonce key is not expected size of 67 or 99 bytes");
871 : : }
872 : 5491 : CPubKey agg_pub, part_pub;
873 : 5491 : uint256 leaf_hash;
874 [ + + ]: 5491 : DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
875 : :
876 [ + + ]: 5476 : std::vector<uint8_t> pubnonce;
877 [ - + ]: 5455 : s >> pubnonce;
878 [ + + ]: 5455 : if (pubnonce.size() != MUSIG2_PUBNONCE_SIZE) {
879 [ + - ]: 32 : throw std::ios_base::failure("Input musig2 pubnonce value is not 66 bytes");
880 : : }
881 : :
882 [ + - + - ]: 5439 : m_musig2_pubnonces[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, pubnonce);
883 : : break;
884 : 5476 : }
885 [ - + ]: 7537 : case PSBT_IN_MUSIG2_PARTIAL_SIG:
886 : : {
887 [ + + + + ]: 7537 : if (key.size() != 2 * CPubKey::COMPRESSED_SIZE + 1 && key.size() != 2 * CPubKey::COMPRESSED_SIZE + CSHA256::OUTPUT_SIZE + 1) {
888 [ + - ]: 30 : throw std::ios_base::failure("Input musig2 partial sig key is not expected size of 67 or 99 bytes");
889 : : }
890 : 7522 : CPubKey agg_pub, part_pub;
891 : 7522 : uint256 leaf_hash;
892 [ + + ]: 7522 : DeserializeMuSig2ParticipantDataIdentifier(skey, agg_pub, part_pub, leaf_hash);
893 : :
894 : 7499 : uint256 partial_sig;
895 [ + + ]: 7499 : UnserializeFromVector(s, partial_sig);
896 : :
897 [ + - + - ]: 7485 : m_musig2_partial_sigs[std::make_pair(agg_pub, leaf_hash)].emplace(part_pub, partial_sig);
898 : : break;
899 : : }
900 [ + + ]: 7236 : case PSBT_IN_PROPRIETARY:
901 : : {
902 [ + + ]: 7236 : PSBTProprietary this_prop;
903 : 7218 : skey >> this_prop.identifier;
904 [ + - ]: 7218 : this_prop.subtype = ReadCompactSize(skey);
905 [ + - ]: 7218 : this_prop.key = key;
906 : :
907 : 7189 : s >> this_prop.value;
908 [ + - ]: 7189 : m_proprietary.insert(this_prop);
909 : : break;
910 : 7236 : }
911 : : // Unknown stuff
912 : 75880 : default:
913 : : // Read in the value
914 [ + + ]: 75880 : std::vector<unsigned char> val_bytes;
915 : 75817 : s >> val_bytes;
916 [ + - ]: 75817 : unknown.emplace(std::move(key), std::move(val_bytes));
917 : : break;
918 : 75880 : }
919 : : }
920 : :
921 : : if (!found_sep) {
922 [ + - ]: 264 : throw std::ios_base::failure("Separator is missing at the end of an input map");
923 : : }
924 : :
925 : : // Make sure required PSBTv2 fields are present
926 [ - + ]: 41164 : if (m_psbt_version >= 2) {
927 [ # # ]: 0 : if (!found_prev_txid) {
928 [ # # ]: 0 : throw std::ios_base::failure("Previous TXID is required in PSBTv2");
929 : : }
930 [ # # ]: 0 : if (!found_prev_out) {
931 [ # # ]: 0 : throw std::ios_base::failure("Previous output's index is required in PSBTv2");
932 : : }
933 : : }
934 : 41164 : }
935 : : };
936 : :
937 : : /** A structure for PSBTs which contains per output information */
938 : : class PSBTOutput
939 : : {
940 : : private:
941 : 7685 : uint32_t m_psbt_version;
942 : :
943 : : public:
944 : : CScript redeem_script;
945 : : CScript witness_script;
946 : 7685 : std::map<CPubKey, KeyOriginInfo> hd_keypaths;
947 : :
948 : : XOnlyPubKey m_tap_internal_key;
949 : 7685 : std::vector<std::tuple<uint8_t, uint8_t, std::vector<unsigned char>>> m_tap_tree;
950 : 7685 : std::map<XOnlyPubKey, std::pair<std::set<uint256>, KeyOriginInfo>> m_tap_bip32_paths;
951 : 7685 : std::map<CPubKey, std::vector<CPubKey>> m_musig2_participants;
952 : :
953 : 7685 : std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
954 : 7685 : std::set<PSBTProprietary> m_proprietary;
955 : :
956 : 7685 : CAmount amount;
957 : : CScript script;
958 : :
959 : : void FillSignatureData(SignatureData& sigdata) const;
960 : : void FromSignatureData(const SignatureData& sigdata);
961 : : [[nodiscard]] bool Merge(const PSBTOutput& output);
962 : 7915 : uint32_t GetVersion() const { return m_psbt_version; }
963 : :
964 : 47243 : explicit PSBTOutput(uint32_t psbt_version, CAmount amount, const CScript& script)
965 : 47243 : : m_psbt_version(psbt_version),
966 : 47243 : amount(amount),
967 : 47243 : script(script)
968 : : {
969 [ - + ]: 47243 : assert(m_psbt_version == 0 || m_psbt_version == 2);
970 : 47243 : }
971 : :
972 : : // Construct a PSBTOutput when the amount and script are expected to be serialized
973 : : template <typename Stream>
974 : 0 : explicit PSBTOutput(deserialize_type, Stream& s, uint32_t psbt_version)
975 [ # # ]: 0 : : m_psbt_version(psbt_version)
976 : : {
977 [ # # ]: 0 : assert(m_psbt_version == 2);
978 [ # # ]: 0 : Unserialize(s);
979 : 0 : }
980 : :
981 : 46110 : bool operator==(const PSBTOutput&) const = default;
[ + - + -
+ - + - +
- + - + -
+ - + - +
- + - -
+ ]
982 : :
983 : : template <typename Stream>
984 : 24889 : inline void Serialize(Stream& s) const {
985 : : // Write the redeem script
986 [ + + + + ]: 25162 : if (!redeem_script.empty()) {
987 : 910 : SerializeToVector(s, CompactSizeWriter(PSBT_OUT_REDEEMSCRIPT));
988 : 910 : s << redeem_script;
989 : : }
990 : :
991 : : // Write the witness script
992 [ + + + + ]: 25237 : if (!witness_script.empty()) {
993 : 896 : SerializeToVector(s, CompactSizeWriter(PSBT_OUT_WITNESSSCRIPT));
994 : 896 : s << witness_script;
995 : : }
996 : :
997 : : // Write any hd keypaths
998 : 24889 : SerializeHDKeypaths(s, hd_keypaths, CompactSizeWriter(PSBT_OUT_BIP32_DERIVATION));
999 : :
1000 [ + + ]: 24889 : if (m_psbt_version >= 2) {
1001 : : // Write amount and spk
1002 : 1133 : SerializeToVector(s, CompactSizeWriter(PSBT_OUT_AMOUNT));
1003 : 1133 : SerializeToVector(s, amount);
1004 : :
1005 : 1133 : SerializeToVector(s, CompactSizeWriter(PSBT_OUT_SCRIPT));
1006 : 1133 : s << script;
1007 : : }
1008 : :
1009 : : // Write proprietary things
1010 [ + + ]: 35074 : for (const auto& entry : m_proprietary) {
1011 : 10185 : s << entry.key;
1012 : 10185 : s << entry.value;
1013 : : }
1014 : :
1015 : : // Write taproot internal key
1016 [ + + ]: 49778 : if (!m_tap_internal_key.IsNull()) {
1017 : 1679 : SerializeToVector(s, PSBT_OUT_TAP_INTERNAL_KEY);
1018 [ + - ]: 3358 : s << ToByteVector(m_tap_internal_key);
1019 : : }
1020 : :
1021 : : // Write taproot tree
1022 [ + + ]: 24889 : if (!m_tap_tree.empty()) {
1023 : 1333 : SerializeToVector(s, PSBT_OUT_TAP_TREE);
1024 : 1333 : std::vector<unsigned char> value;
1025 [ + - ]: 1333 : VectorWriter s_value{value, 0};
1026 [ + - + + ]: 6723 : for (const auto& [depth, leaf_ver, script] : m_tap_tree) {
1027 [ + - ]: 5390 : s_value << depth;
1028 [ + - ]: 5390 : s_value << leaf_ver;
1029 : 5390 : s_value << script;
1030 : : }
1031 : 1333 : s << value;
1032 : 1333 : }
1033 : :
1034 : : // Write taproot bip32 keypaths
1035 [ + + ]: 27573 : for (const auto& [xonly, leaf] : m_tap_bip32_paths) {
1036 : 2684 : const auto& [leaf_hashes, origin] = leaf;
1037 : 2684 : SerializeToVector(s, PSBT_OUT_TAP_BIP32_DERIVATION, xonly);
1038 : 2684 : std::vector<unsigned char> value;
1039 [ + - ]: 2684 : VectorWriter s_value{value, 0};
1040 [ + - ]: 2684 : s_value << leaf_hashes;
1041 [ + - + - ]: 5368 : SerializeKeyOrigin(s_value, origin);
1042 : 2684 : s << value;
1043 : : }
1044 : :
1045 : : // Write MuSig2 Participants
1046 [ + + ]: 29394 : for (const auto& [agg_pubkey, part_pubs] : m_musig2_participants) {
1047 : 4505 : SerializeToVector(s, CompactSizeWriter(PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS), std::span{agg_pubkey});
1048 : 4505 : std::vector<unsigned char> value;
1049 [ + - ]: 4505 : VectorWriter s_value{value, 0};
1050 [ + - + + ]: 6504 : for (auto& pk : part_pubs) {
1051 [ + - ]: 3998 : s_value << std::span{pk};
1052 : : }
1053 : 4505 : s << value;
1054 : : }
1055 : :
1056 : : // Write unknown things
1057 [ + + ]: 46765 : for (auto& entry : unknown) {
1058 : 21876 : s << entry.first;
1059 : 21876 : s << entry.second;
1060 : : }
1061 : :
1062 : 24889 : s << PSBT_SEPARATOR;
1063 : 24889 : }
1064 : :
1065 : :
1066 : : template <typename Stream>
1067 : 32350 : inline void Unserialize(Stream& s) {
1068 : : // Used for duplicate key detection
1069 : 32350 : std::set<std::vector<unsigned char>> key_lookup;
1070 : : // Cache whether PSBTv2 required fields are found
1071 : 32350 : bool found_amount = false;
1072 : 32350 : bool found_script = false;
1073 : :
1074 : : // Read loop
1075 : 32350 : bool found_sep = false;
1076 [ + + ]: 131439 : while(!s.empty()) {
1077 : : // Read the key of format "<keylen><keytype><keydata>" after which
1078 : : // "key" will contain "<keytype><keydata>"
1079 [ + + ]: 129836 : std::vector<unsigned char> key;
1080 : 129599 : s >> key;
1081 : :
1082 : : // the key is empty if that was actually a separator byte
1083 : : // This is a special case for key lengths 0 as those are not allowed (except for separator)
1084 [ + + ]: 129599 : if (key.empty()) {
1085 : 30747 : found_sep = true;
1086 : : break;
1087 : : }
1088 : :
1089 : : // Duplicate keys are not permitted
1090 [ + - + + ]: 98852 : if (!key_lookup.emplace(key).second) {
1091 [ - + + - : 148 : throw std::ios_base::failure(tfm::format("Duplicate Key, output key \"%s\" already provided", HexStr(key)));
+ - + - ]
1092 : : }
1093 : :
1094 : : // "skey" is used so that "key" is unchanged after reading keytype below
1095 : 98778 : SpanReader skey{key};
1096 : : // keytype is of the format compact size uint at the beginning of "key"
1097 [ + + ]: 98778 : uint64_t type = ReadCompactSize(skey);
1098 : :
1099 : : // Do stuff based on keytype "type", i.e., key checks, reading values of the
1100 : : // format "<valuelen><valuedata>" from the stream "s", and value checks
1101 : 98770 : switch(type) {
[ + + + +
+ + + + +
+ + ]
1102 : 2311 : case PSBT_OUT_REDEEMSCRIPT:
1103 : : {
1104 [ + - + + ]: 2336 : ExpectedKeySize("Output redeemScript", key, 1);
1105 [ + + ]: 2286 : s >> redeem_script;
1106 : : break;
1107 : : }
1108 : 2292 : case PSBT_OUT_WITNESSSCRIPT:
1109 : : {
1110 [ + - + + ]: 2304 : ExpectedKeySize("Output witnessScript", key, 1);
1111 [ + + ]: 2280 : s >> witness_script;
1112 : : break;
1113 : : }
1114 : 13557 : case PSBT_OUT_BIP32_DERIVATION:
1115 : : {
1116 [ + + ]: 13557 : DeserializeHDKeypaths(s, key, hd_keypaths);
1117 : : break;
1118 : : }
1119 : 129 : case PSBT_OUT_AMOUNT:
1120 : : {
1121 [ + - + + ]: 223 : ExpectedKeySize("Output Amount", key, 1);
1122 [ + - ]: 35 : if (m_psbt_version < 2) {
1123 [ + - ]: 70 : throw std::ios_base::failure("Output amount is not allowed in PSBTv0");
1124 : : }
1125 [ # # ]: 0 : UnserializeFromVector(s, amount);
1126 : : found_amount = true;
1127 : : break;
1128 : : }
1129 : 93 : case PSBT_OUT_SCRIPT:
1130 : : {
1131 [ + - + + ]: 162 : ExpectedKeySize("Output Script", key, 1);
1132 [ + - ]: 24 : if (m_psbt_version < 2) {
1133 [ + - ]: 48 : throw std::ios_base::failure("Output script is not allowed in PSBTv0");
1134 : : }
1135 [ - - ]: 97557 : s >> script;
1136 : : found_script = true;
1137 : : break;
1138 : : }
1139 : 1861 : case PSBT_OUT_TAP_INTERNAL_KEY:
1140 : : {
1141 [ + - + + ]: 1876 : ExpectedKeySize("Output Taproot Internal Key", key, 1);
1142 [ + + ]: 1846 : UnserializeFromVector(s, m_tap_internal_key);
1143 : : break;
1144 : : }
1145 : 2510 : case PSBT_OUT_TAP_TREE:
1146 : : {
1147 [ + - + + ]: 2527 : ExpectedKeySize("Output Taproot Tree Key", key, 1);
1148 [ + + ]: 2493 : std::vector<unsigned char> tree_v;
1149 [ - + ]: 2467 : s >> tree_v;
1150 [ + + ]: 2467 : SpanReader s_tree{tree_v};
1151 [ + + ]: 2467 : if (s_tree.empty()) {
1152 [ + - ]: 26 : throw std::ios_base::failure("Output Taproot tree must not be empty");
1153 : : }
1154 : 2454 : TaprootBuilder builder;
1155 [ + + ]: 82052 : while (!s_tree.empty()) {
1156 : : uint8_t depth;
1157 : : uint8_t leaf_ver;
1158 [ + - ]: 79598 : std::vector<unsigned char> script;
1159 [ + + ]: 79598 : s_tree >> depth;
1160 [ + + ]: 79552 : s_tree >> leaf_ver;
1161 : 79396 : s_tree >> script;
1162 [ + + ]: 79396 : if (depth > TAPROOT_CONTROL_MAX_NODE_COUNT) {
1163 [ + - ]: 66 : throw std::ios_base::failure("Output Taproot tree has as leaf greater than Taproot maximum depth");
1164 : : }
1165 [ + + ]: 79363 : if ((leaf_ver & ~TAPROOT_LEAF_MASK) != 0) {
1166 [ + - ]: 70 : throw std::ios_base::failure("Output Taproot tree has a leaf with an invalid leaf version");
1167 : : }
1168 [ + - ]: 79328 : m_tap_tree.emplace_back(depth, leaf_ver, script);
1169 [ - + + - ]: 79328 : builder.Add((int)depth, script, (int)leaf_ver, /*track=*/true);
1170 : : }
1171 [ + + ]: 2184 : if (!builder.IsComplete()) {
1172 [ + - ]: 162 : throw std::ios_base::failure("Output Taproot tree is malformed");
1173 : : }
1174 : : break;
1175 : 2844 : }
1176 : 5119 : case PSBT_OUT_TAP_BIP32_DERIVATION:
1177 : : {
1178 [ + - + + : 10238 : ExpectedKeySize("Output Taproot BIP32 Keypath", key, 33);
- + ]
1179 [ + + ]: 5103 : XOnlyPubKey xonly(uint256(std::span<uint8_t>(key).last(32)));
1180 : 5103 : std::set<uint256> leaf_hashes;
1181 [ + + + + ]: 5103 : uint64_t value_len = ReadCompactSize(s);
1182 [ + + ]: 5093 : size_t before_hashes = s.size();
1183 [ + + ]: 4990 : s >> leaf_hashes;
1184 : 4990 : size_t after_hashes = s.size();
1185 : 4990 : size_t hashes_len = before_hashes - after_hashes;
1186 [ + + ]: 4990 : if (hashes_len > value_len) {
1187 [ + - ]: 40 : throw std::ios_base::failure("Output Taproot BIP32 keypath has an invalid length");
1188 : : }
1189 : 4970 : size_t origin_len = value_len - hashes_len;
1190 [ + + + - ]: 9925 : m_tap_bip32_paths.emplace(xonly, std::make_pair(leaf_hashes, DeserializeKeyOrigin(s, origin_len)));
1191 : : break;
1192 : 5103 : }
1193 : 8068 : case PSBT_OUT_MUSIG2_PARTICIPANT_PUBKEYS:
1194 : : {
1195 [ + - + + ]: 8085 : ExpectedKeySize("Output MuSig2 Participants Pubkeys", key, CPubKey::COMPRESSED_SIZE + 1);
1196 [ + - + + ]: 16102 : DeserializeMuSig2ParticipantPubkeys(s, skey, m_musig2_participants, std::string{"Output"});
1197 : : break;
1198 : : }
1199 [ + + ]: 18487 : case PSBT_OUT_PROPRIETARY:
1200 : : {
1201 [ + + ]: 18487 : PSBTProprietary this_prop;
1202 : 18473 : skey >> this_prop.identifier;
1203 [ + + ]: 18473 : this_prop.subtype = ReadCompactSize(skey);
1204 [ + - ]: 18472 : this_prop.key = key;
1205 : :
1206 : 18431 : s >> this_prop.value;
1207 [ + - ]: 18431 : m_proprietary.insert(this_prop);
1208 : : break;
1209 : 18487 : }
1210 : : // Unknown stuff
1211 : 44343 : default: {
1212 : : // Read in the value
1213 [ + + ]: 44343 : std::vector<unsigned char> val_bytes;
1214 : 44269 : s >> val_bytes;
1215 [ + - ]: 44269 : unknown.emplace(std::move(key), std::move(val_bytes));
1216 : : break;
1217 : 44343 : }
1218 : : }
1219 : : }
1220 : :
1221 : : if (!found_sep) {
1222 [ + - ]: 142 : throw std::ios_base::failure("Separator is missing at the end of an output map");
1223 : : }
1224 : :
1225 : : // Make sure required PSBTv2 fields are present
1226 [ - + ]: 30747 : if (m_psbt_version >= 2) {
1227 [ # # ]: 0 : if (!found_amount) {
1228 [ # # ]: 0 : throw std::ios_base::failure("Output amount is required in PSBTv2");
1229 : : }
1230 [ # # ]: 0 : if (!found_script) {
1231 [ # # ]: 0 : throw std::ios_base::failure("Output script is required in PSBTv2");
1232 : : }
1233 : : }
1234 : 30747 : }
1235 : : };
1236 : :
1237 : : /** A version of CTransaction with the PSBT format*/
1238 : : class PartiallySignedTransaction
1239 : : {
1240 : : private:
1241 : : std::optional<uint32_t> m_version;
1242 : :
1243 : : public:
1244 : : // We use a vector of CExtPubKey in the event that there happens to be the same KeyOriginInfos for different CExtPubKeys
1245 : : // Note that this map swaps the key and values from the serialization
1246 : : std::map<KeyOriginInfo, std::set<CExtPubKey>> m_xpubs;
1247 : : std::optional<std::bitset<8>> m_tx_modifiable;
1248 : : std::vector<PSBTInput> inputs;
1249 : : std::vector<PSBTOutput> outputs;
1250 : : std::map<std::vector<unsigned char>, std::vector<unsigned char>> unknown;
1251 : : std::set<PSBTProprietary> m_proprietary;
1252 : :
1253 : : uint32_t tx_version;
1254 : : std::optional<uint32_t> fallback_locktime;
1255 : :
1256 : : uint32_t GetVersion() const;
1257 : :
1258 : : /** Merge psbt into this. The two psbts must have the same underlying CTransaction (i.e. the
1259 : : * same actual Bitcoin transaction.) Returns true if the merge succeeded, false otherwise. */
1260 : : [[nodiscard]] bool Merge(const PartiallySignedTransaction& psbt);
1261 : : /** Merge the global xpubs of psbt into this, keeping the existing origin for an xpub
1262 : : * seen again with a different one, as the serialized records are keyed by xpub. */
1263 : : void MergeGlobalXPubs(const PartiallySignedTransaction& psbt);
1264 : : bool AddInput(const PSBTInput& psbtin);
1265 : : bool AddOutput(const PSBTOutput& psbtout);
1266 : : std::optional<uint32_t> ComputeTimeLock() const;
1267 : : std::optional<CMutableTransaction> GetUnsignedTx() const;
1268 : : std::optional<Txid> GetUniqueID() const;
1269 : : explicit PartiallySignedTransaction(const CMutableTransaction& tx, uint32_t version = 2);
1270 : :
1271 : : template <typename Stream>
1272 : 23775 : inline void Serialize(Stream& s) const {
1273 : :
1274 : : // magic bytes
1275 : 23775 : s << PSBT_MAGIC_BYTES;
1276 : :
1277 [ + + ]: 23775 : if (GetVersion() < 2) {
1278 : : // unsigned tx flag
1279 : 23741 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_UNSIGNED_TX));
1280 : :
1281 : : // Write serialized tx to a stream
1282 [ + - ]: 47482 : SerializeToVector(s, TX_NO_WITNESS(*GetUnsignedTx()));
1283 : : }
1284 : :
1285 : : // Write xpubs
1286 [ + + ]: 29656 : for (const auto& xpub_pair : m_xpubs) {
1287 [ + + ]: 12832 : for (const auto& xpub : xpub_pair.second) {
1288 : : unsigned char ser_xpub[BIP32_EXTKEY_WITH_VERSION_SIZE];
1289 : 6951 : xpub.EncodeWithVersion(ser_xpub);
1290 : : // Note that the serialization swaps the key and value
1291 : : // The xpub is the key (for uniqueness) while the path is the value
1292 : 6951 : SerializeToVector(s, PSBT_GLOBAL_XPUB, ser_xpub);
1293 [ + - ]: 13902 : SerializeHDKeypath(s, xpub_pair.first);
1294 : : }
1295 : : }
1296 : :
1297 [ + + ]: 23775 : if (GetVersion() >= 2) {
1298 : : // Write PSBTv2 tx version, locktime, counts, etc.
1299 : 34 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_TX_VERSION));
1300 : 34 : SerializeToVector(s, tx_version);
1301 [ + - ]: 34 : if (fallback_locktime != std::nullopt) {
1302 : 34 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_FALLBACK_LOCKTIME));
1303 : 34 : SerializeToVector(s, *fallback_locktime);
1304 : : }
1305 : :
1306 : 34 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_INPUT_COUNT));
1307 [ - + ]: 34 : SerializeToVector(s, CompactSizeWriter(inputs.size()));
1308 : 34 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_OUTPUT_COUNT));
1309 [ - + ]: 34 : SerializeToVector(s, CompactSizeWriter(outputs.size()));
1310 : :
1311 [ - + ]: 34 : if (m_tx_modifiable != std::nullopt) {
1312 : 0 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_TX_MODIFIABLE));
1313 : 0 : SerializeToVector(s, static_cast<uint8_t>(m_tx_modifiable->to_ulong()));
1314 : : }
1315 : : }
1316 : :
1317 : : // PSBT version
1318 [ + + ]: 23775 : if (GetVersion() > 0) {
1319 : 34 : SerializeToVector(s, CompactSizeWriter(PSBT_GLOBAL_VERSION));
1320 : 34 : SerializeToVector(s, *m_version);
1321 : : }
1322 : :
1323 : : // Write proprietary things
1324 [ + + ]: 27411 : for (const auto& entry : m_proprietary) {
1325 : 3636 : s << entry.key;
1326 : 3636 : s << entry.value;
1327 : : }
1328 : :
1329 : : // Write the unknown things
1330 [ + + ]: 40719 : for (auto& entry : unknown) {
1331 : 16944 : s << entry.first;
1332 : 16944 : s << entry.second;
1333 : : }
1334 : :
1335 : : // Separator
1336 : 23775 : s << PSBT_SEPARATOR;
1337 : :
1338 : : // Write inputs
1339 [ + + ]: 51392 : for (const PSBTInput& input : inputs) {
1340 : 27617 : s << input;
1341 : : }
1342 : : // Write outputs
1343 [ + + ]: 48488 : for (const PSBTOutput& output : outputs) {
1344 : 24713 : s << output;
1345 : : }
1346 : 23775 : }
1347 : :
1348 : :
1349 : : template <typename Stream>
1350 : 49093 : inline void Unserialize(Stream& s) {
1351 : : // Read the magic bytes
1352 : : uint8_t magic[5];
1353 : 46180 : s >> magic;
1354 [ + + ]: 46180 : if (!std::equal(magic, magic + 5, PSBT_MAGIC_BYTES)) {
1355 [ + - ]: 2246 : throw std::ios_base::failure("Invalid PSBT magic bytes");
1356 : : }
1357 : :
1358 : : // Used for duplicate key detection
1359 : 45057 : std::set<std::vector<unsigned char>> key_lookup;
1360 : :
1361 : : // Read global data
1362 : 45057 : bool found_sep = false;
1363 : 45057 : std::optional<CMutableTransaction> tx;
1364 : 45057 : uint64_t input_count = 0;
1365 : 45057 : uint64_t output_count = 0;
1366 : 45057 : bool found_input_count = false;
1367 : 45057 : bool found_output_count = false;
1368 : 45057 : bool found_tx_version = false;
1369 : 45057 : bool found_fallback_locktime = false;
1370 [ + + ]: 144905 : while(!s.empty()) {
1371 : : // Read the key of format "<keylen><keytype><keydata>" after which
1372 : : // "key" will contain "<keytype><keydata>"
1373 [ + + ]: 143415 : std::vector<unsigned char> key;
1374 : 143264 : s >> key;
1375 : :
1376 : : // the key is empty if that was actually a separator byte
1377 : : // This is a special case for key lengths 0 as those are not allowed (except for separator)
1378 [ + + ]: 143264 : if (key.empty()) {
1379 : 43567 : found_sep = true;
1380 : : break;
1381 : : }
1382 : :
1383 : : // Duplicate keys are not permitted
1384 [ + - + + ]: 99697 : if (!key_lookup.emplace(key).second) {
1385 [ - + + - : 98 : throw std::ios_base::failure(tfm::format("Duplicate Key, global key \"%s\" already provided", HexStr(key)));
+ - + - ]
1386 : : }
1387 : :
1388 : : // "skey" is used so that "key" is unchanged after reading keytype below
1389 : 99648 : SpanReader skey{key};
1390 : : // keytype is of the format compact size uint at the beginning of "key"
1391 [ + + ]: 99648 : uint64_t type = ReadCompactSize(skey);
1392 : :
1393 : : // Do stuff based on keytype "type", i.e., key checks, reading values of the
1394 : : // format "<valuelen><valuedata>" from the stream "s", and value checks
1395 [ + + + + : 99634 : switch(type) {
+ + + + +
+ ]
1396 : 44257 : case PSBT_GLOBAL_UNSIGNED_TX:
1397 : : {
1398 [ + - + + ]: 44275 : ExpectedKeySize("Global Unsigned TX", key, 1);
1399 : : // Set the stream to serialize with non-witness since this should always be non-witness
1400 [ + - ]: 44239 : tx.emplace();
1401 [ + + ]: 44239 : UnserializeFromVector(s, TX_NO_WITNESS(*tx));
1402 : : // Make sure that all scriptSigs and scriptWitnesses are empty
1403 [ + + ]: 88534 : for (const CTxIn& txin : tx->vin) {
1404 [ + + + + : 44629 : if (!txin.scriptSig.empty() || !txin.scriptWitness.IsNull()) {
- + ]
1405 [ + - ]: 34 : throw std::ios_base::failure("Unsigned tx does not have empty scriptSigs and scriptWitnesses.");
1406 : : }
1407 : : }
1408 : 43915 : tx_version = tx->version;
1409 [ - + ]: 43915 : fallback_locktime = tx->nLockTime;
1410 : : // Set the input and output counts
1411 [ - + - + ]: 43915 : input_count = tx->vin.size();
1412 [ - + ]: 43915 : output_count = tx->vout.size();
1413 : 43915 : break;
1414 : : }
1415 : 252 : case PSBT_GLOBAL_TX_VERSION:
1416 : : {
1417 [ + - + + ]: 478 : ExpectedKeySize("Global Transaction Version", key, 1);
1418 [ + + ]: 26 : UnserializeFromVector(s, tx_version);
1419 : : found_tx_version = true;
1420 : : break;
1421 : : }
1422 : 223 : case PSBT_GLOBAL_FALLBACK_LOCKTIME:
1423 : : {
1424 [ + - + + ]: 403 : ExpectedKeySize("Global Fallback Locktime", key, 1);
1425 [ + + ]: 43 : fallback_locktime.emplace();
1426 [ + + ]: 43 : UnserializeFromVector(s, *fallback_locktime);
1427 : : found_fallback_locktime = true;
1428 : : break;
1429 : : }
1430 : 81 : case PSBT_GLOBAL_INPUT_COUNT:
1431 : : {
1432 [ + - + + : 162 : ExpectedKeySize("Global Input Count", key, 1);
+ + ]
1433 : 34 : CompactSizeReader reader(input_count);
1434 [ + + ]: 34 : UnserializeFromVector(s, reader);
1435 : : found_input_count = true;
1436 : : break;
1437 : : }
1438 : 46 : case PSBT_GLOBAL_OUTPUT_COUNT:
1439 : : {
1440 [ + - + + : 92 : ExpectedKeySize("Global Output Count", key, 1);
+ + ]
1441 : 24 : CompactSizeReader reader(output_count);
1442 [ + + ]: 24 : UnserializeFromVector(s, reader);
1443 : : found_output_count = true;
1444 : : break;
1445 : : }
1446 : 61 : case PSBT_GLOBAL_TX_MODIFIABLE:
1447 : : {
1448 [ + - + + ]: 99 : ExpectedKeySize("Global TX Modifiable Flags", key, 1);
1449 : : uint8_t tx_mod;
1450 [ + + ]: 23 : UnserializeFromVector(s, tx_mod);
1451 [ - + ]: 20 : m_tx_modifiable.emplace(tx_mod);
1452 : : break;
1453 : : }
1454 : 15386 : case PSBT_GLOBAL_XPUB:
1455 : : {
1456 [ + - + + : 30772 : ExpectedKeySize("Global XPUB", key, BIP32_EXTKEY_WITH_VERSION_SIZE + 1);
+ - ]
1457 : : // Read in the xpub from key
1458 [ + - ]: 15363 : CExtPubKey xpub;
1459 [ + - ]: 15363 : xpub.DecodeWithVersion(&key.data()[1]);
1460 [ + - + + ]: 15363 : if (!xpub.pubkey.IsFullyValid()) {
1461 [ + - ]: 134 : throw std::ios_base::failure("Invalid pubkey");
1462 : : }
1463 : : // Read in the keypath from stream
1464 : 15296 : KeyOriginInfo keypath;
1465 [ + + ]: 15296 : DeserializeHDKeypath(s, keypath);
1466 : :
1467 : : // Note that we store these swapped to make searches faster.
1468 : : // Serialization uses xpub -> keypath to enqure key uniqueness
1469 [ + + ]: 15251 : if (!m_xpubs.contains(keypath)) {
1470 : : // Make a new set to put the xpub in
1471 [ + - + + : 38277 : m_xpubs[keypath] = {xpub};
- - ]
1472 : : } else {
1473 : : // Insert xpub into existing set
1474 [ + - + - ]: 2492 : m_xpubs[keypath].insert(xpub);
1475 : : }
1476 : : break;
1477 : 15408 : }
1478 : 73 : case PSBT_GLOBAL_VERSION:
1479 : : {
1480 [ + - + + ]: 84 : ExpectedKeySize("Global PSBT Version", key, 1);
1481 : : uint32_t v;
1482 [ + + ]: 62 : UnserializeFromVector(s, v);
1483 : 51 : m_version = v;
1484 [ + + ]: 51 : if (*m_version > PSBT_HIGHEST_VERSION) {
1485 [ + - ]: 14 : throw std::ios_base::failure("Unsupported version number");
1486 : : }
1487 : : break;
1488 : : }
1489 [ + + ]: 6946 : case PSBT_GLOBAL_PROPRIETARY:
1490 : : {
1491 [ + + ]: 6946 : PSBTProprietary this_prop;
1492 : 6932 : skey >> this_prop.identifier;
1493 [ + - ]: 6932 : this_prop.subtype = ReadCompactSize(skey);
1494 [ + - ]: 6932 : this_prop.key = key;
1495 : :
1496 : 6900 : s >> this_prop.value;
1497 [ + - ]: 6900 : m_proprietary.insert(this_prop);
1498 : : break;
1499 : 6946 : }
1500 : : // Unknown stuff
1501 : 32309 : default: {
1502 : : // Read in the value
1503 [ + + ]: 32309 : std::vector<unsigned char> val_bytes;
1504 : 32248 : s >> val_bytes;
1505 [ + - ]: 32248 : unknown.emplace(std::move(key), std::move(val_bytes));
1506 : 32309 : }
1507 : : }
1508 : : }
1509 : :
1510 : : if (!found_sep) {
1511 [ + - ]: 130 : throw std::ios_base::failure("Separator is missing at the end of the global map");
1512 : : }
1513 : :
1514 [ + - ]: 43567 : const uint32_t psbt_ver = GetVersion();
1515 : :
1516 : : // Check PSBT version constraints
1517 [ + + ]: 43567 : if (psbt_ver == 0) {
1518 : : // Make sure that we got an unsigned tx for PSBTv0
1519 [ + + ]: 43547 : if (!tx) {
1520 [ + - ]: 92 : throw std::ios_base::failure("No unsigned transaction was provided");
1521 : : }
1522 : : // Make sure no PSBTv2 fields are present
1523 [ + + ]: 43501 : if (found_tx_version) {
1524 [ + - ]: 8 : throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is not allowed in PSBTv0");
1525 : : }
1526 [ + + ]: 43497 : if (found_fallback_locktime) {
1527 [ + - ]: 14 : throw std::ios_base::failure("PSBT_GLOBAL_FALLBACK_LOCKTIME is not allowed in PSBTv0");
1528 : : }
1529 [ + + ]: 43490 : if (found_input_count) {
1530 [ + - ]: 12 : throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is not allowed in PSBTv0");
1531 : : }
1532 [ + + ]: 43484 : if (found_output_count) {
1533 [ + - ]: 8 : throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is not allowed in PSBTv0");
1534 : : }
1535 [ + + ]: 43480 : if (m_tx_modifiable != std::nullopt) {
1536 [ + - ]: 10 : throw std::ios_base::failure("PSBT_GLOBAL_TX_MODIFIABLE is not allowed in PSBTv0");
1537 : : }
1538 : : }
1539 : : // Disallow v1
1540 [ + + ]: 43495 : if (psbt_ver == 1) {
1541 [ + - ]: 14 : throw std::ios_base::failure("There is no PSBT version 1");
1542 : : }
1543 [ + + ]: 43488 : if (psbt_ver == 2) {
1544 : : // Tx version, input, and output counts are required
1545 [ + + ]: 13 : if (!found_tx_version) {
1546 [ + - ]: 14 : throw std::ios_base::failure("PSBT_GLOBAL_TX_VERSION is required in PSBTv2");
1547 : : }
1548 [ + + ]: 6 : if (!found_input_count) {
1549 [ + - ]: 6 : throw std::ios_base::failure("PSBT_GLOBAL_INPUT_COUNT is required in PSBTv2");
1550 : : }
1551 [ + - ]: 3 : if (!found_output_count) {
1552 [ + - ]: 6 : throw std::ios_base::failure("PSBT_GLOBAL_OUTPUT_COUNT is required in PSBTv2");
1553 : : }
1554 : : // Unsigned tx is disallowed
1555 [ # # ]: 0 : if (tx) {
1556 [ # # ]: 0 : throw std::ios_base::failure("PSBT_GLOBAL_UNSIGNED_TX is not allowed in PSBTv2");
1557 : : }
1558 : : }
1559 [ - + ]: 43475 : if (psbt_ver > 2) {
1560 [ # # ]: 0 : throw std::ios_base::failure("Unknown PSBT version");
1561 : : }
1562 : :
1563 : : // Read input data
1564 : : unsigned int i = 0;
1565 [ + + + + ]: 84175 : while (!s.empty() && i < input_count) {
1566 [ + - ]: 43267 : if (psbt_ver < 2) {
1567 [ + - ]: 43267 : inputs.emplace_back(psbt_ver, tx->vin[i].prevout.hash, tx->vin[i].prevout.n, tx->vin[i].nSequence);
1568 [ + + ]: 43267 : s >> inputs.back();
1569 : : } else {
1570 [ # # ]: 0 : inputs.emplace_back(deserialize, s, psbt_ver);
1571 : : }
1572 : :
1573 : : // Make sure the non-witness utxo matches the outpoint
1574 : 40783 : const PSBTInput& input = inputs.back();
1575 [ + + ]: 40783 : if (input.non_witness_utxo) {
1576 [ + - ]: 521 : if (psbt_ver < 2) {
1577 [ + + - + ]: 521 : if (input.non_witness_utxo->GetHash() != tx->vin[i].prevout.hash) {
1578 [ + - ]: 156 : throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1579 : : }
1580 [ - + + + ]: 443 : if (tx->vin[i].prevout.n >= input.non_witness_utxo->vout.size()) {
1581 [ + - ]: 10 : throw std::ios_base::failure("Input specifies output index that does not exist");
1582 : : }
1583 : : } else {
1584 [ # # ]: 0 : if (input.non_witness_utxo->GetHash() != input.prev_txid) {
1585 [ # # ]: 0 : throw std::ios_base::failure("Non-witness UTXO does not match outpoint hash");
1586 : : }
1587 [ # # # # ]: 0 : if (input.prev_out >= input.non_witness_utxo->vout.size()) {
1588 [ # # ]: 0 : throw std::ios_base::failure("Input specifies output index that does not exist");
1589 : : }
1590 : : }
1591 : : }
1592 : 40700 : ++i;
1593 : : }
1594 : : // Make sure that the number of inputs matches the number of inputs in the transaction
1595 [ - + + + ]: 40908 : if (inputs.size() != input_count) {
1596 [ + - ]: 72 : throw std::ios_base::failure("Inputs provided does not match the number of inputs in transaction.");
1597 : : }
1598 : :
1599 : : // Read output data
1600 : : i = 0;
1601 [ + + + + ]: 71443 : while (!s.empty() && i < output_count) {
1602 [ + - ]: 31869 : if (psbt_ver < 2) {
1603 [ + - ]: 31869 : outputs.emplace_back(psbt_ver, tx->vout[i].nValue, tx->vout[i].scriptPubKey);
1604 [ + + ]: 31869 : s >> outputs.back();
1605 : : } else {
1606 [ # # ]: 0 : outputs.emplace_back(deserialize, s, psbt_ver);
1607 : : }
1608 : 30571 : ++i;
1609 : : }
1610 : : // Make sure that the number of outputs matches the number of outputs in the transaction
1611 [ - + + + ]: 39574 : if (outputs.size() != output_count) {
1612 [ + - ]: 120 : throw std::ios_base::failure("Outputs provided does not match the number of outputs in transaction.");
1613 : : }
1614 [ + - ]: 57816 : }
1615 : :
1616 : : template <typename Stream>
1617 [ + + ]: 49093 : PartiallySignedTransaction(deserialize_type, Stream& s) {
1618 [ + + ]: 49093 : Unserialize(s);
1619 : 68251 : }
1620 : : };
1621 : :
1622 : : enum class PSBTRole {
1623 : : CREATOR,
1624 : : UPDATER,
1625 : : SIGNER,
1626 : : FINALIZER,
1627 : : EXTRACTOR
1628 : : };
1629 : :
1630 : : std::string PSBTRoleName(PSBTRole role);
1631 : :
1632 : : /** Compute a PrecomputedTransactionData object from a psbt. */
1633 : : std::optional<PrecomputedTransactionData> PrecomputePSBTData(const PartiallySignedTransaction& psbt);
1634 : :
1635 : : /** Checks whether a PSBTInput is already signed by checking for non-null finalized fields. */
1636 : : bool PSBTInputSigned(const PSBTInput& input);
1637 : :
1638 : : /** Checks whether a PSBTInput is already signed by doing script verification using final fields. */
1639 : : bool PSBTInputSignedAndVerified(const PartiallySignedTransaction& psbt, unsigned int input_index, const PrecomputedTransactionData* txdata);
1640 : :
1641 : : /** Signs a PSBTInput, verifying that all provided data matches what is being signed.
1642 : : *
1643 : : * txdata should be the output of PrecomputePSBTData (which can be shared across
1644 : : * multiple SignPSBTInput calls). If it is nullptr, a dummy signature will be created.
1645 : : **/
1646 : : [[nodiscard]] util::Expected<void, PSBTError> SignPSBTInput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index, const PrecomputedTransactionData* txdata, const common::PSBTFillOptions& options, SignatureData* out_sigdata = nullptr);
1647 : :
1648 : : /** Reduces the size of the PSBT by dropping unnecessary `non_witness_utxos` (i.e. complete previous transactions) from a psbt when all inputs are segwit v1. */
1649 : : void RemoveUnnecessaryTransactions(PartiallySignedTransaction& psbtx);
1650 : :
1651 : : /** Counts the unsigned inputs of a PSBT. */
1652 : : size_t CountPSBTUnsignedInputs(const PartiallySignedTransaction& psbt);
1653 : :
1654 : : /** Updates a PSBTOutput with information from provider.
1655 : : *
1656 : : * This fills in the redeem_script, witness_script, and hd_keypaths where possible.
1657 : : */
1658 : : void UpdatePSBTOutput(const SigningProvider& provider, PartiallySignedTransaction& psbt, int index);
1659 : :
1660 : : /**
1661 : : * Finalizes a PSBT if possible, combining partial signatures.
1662 : : *
1663 : : * @param[in,out] psbtx PartiallySignedTransaction to finalize
1664 : : * return True if the PSBT is now complete, false otherwise
1665 : : */
1666 : : bool FinalizePSBT(PartiallySignedTransaction& psbtx);
1667 : :
1668 : : /**
1669 : : * Finalizes a PSBT if possible, and extracts it to a CMutableTransaction if it could be finalized.
1670 : : *
1671 : : * @param[in] psbtx PartiallySignedTransaction
1672 : : * @param[out] result CMutableTransaction representing the complete transaction, if successful
1673 : : * @return True if we successfully extracted the transaction, false otherwise
1674 : : */
1675 : : bool FinalizeAndExtractPSBT(PartiallySignedTransaction& psbtx, CMutableTransaction& result);
1676 : :
1677 : : /**
1678 : : * Combines PSBTs with the same underlying transaction, resulting in a single PSBT with all partial signatures from each input.
1679 : : *
1680 : : * @param[in] psbtxs the PSBTs to combine
1681 : : * @return The combined PSBT or std::nullopt if the PSBTs cannot be combined
1682 : : */
1683 : : [[nodiscard]] std::optional<PartiallySignedTransaction> CombinePSBTs(const std::vector<PartiallySignedTransaction>& psbtxs);
1684 : :
1685 : : //! Decode a base64ed PSBT into a PartiallySignedTransaction
1686 : : [[nodiscard]] util::Result<PartiallySignedTransaction> DecodeBase64PSBT(const std::string& base64_tx);
1687 : : //! Decode a raw (binary blob) PSBT into a PartiallySignedTransaction
1688 : : [[nodiscard]] util::Result<PartiallySignedTransaction> DecodeRawPSBT(std::span<const std::byte> tx_data);
1689 : :
1690 : : #endif // BITCOIN_PSBT_H
|