Coverage Report

Created: 2026-05-30 09:47

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