47#include <unordered_set>
58 if ((
high >> 31) != 0) {
133 c = ((
c & 0x7ffffffff) << 5) ^ val;
134 if (
c0 & 1)
c ^= 0xf5dee51989;
135 if (
c0 & 2)
c ^= 0xa9fdca3312;
136 if (
c0 & 4)
c ^= 0x1bab10e32d;
137 if (
c0 & 8)
c ^= 0x3706b1677a;
138 if (
c0 & 16)
c ^= 0x644d626ffd;
158 "0123456789()[],'/*abcdefgh@:$%{}"
159 "IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
160 "ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
164 std::array<int8_t, 256> table;
173 static constexpr std::string_view
CHECKSUM_CHARSET =
"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
178 for (
auto ch : span) {
180 if (pos == -1)
return "";
182 cls =
cls * 3 + (pos >> 5);
194 std::string
ret(8,
' ');
205typedef std::vector<uint32_t>
KeyPath;
227 virtual bool IsRange()
const = 0;
230 virtual size_t GetSize()
const = 0;
232 enum class StringType {
239 virtual std::string
ToString(StringType type)
const = 0;
246 virtual bool ToPrivateString(
const SigningProvider& arg, std::string& out)
const = 0;
270 virtual std::unique_ptr<PubkeyProvider> Clone()
const = 0;
273 virtual bool IsBIP32()
const = 0;
276 virtual size_t GetKeyCount()
const {
return 1; }
279 virtual bool CanSelfExpand()
const = 0;
286 case StringType::COMPAT:
290 case StringType::CANONICAL:
294 case StringType::PUBLIC:
302class OriginPubkeyProvider final :
public PubkeyProvider
305 std::unique_ptr<PubkeyProvider> m_provider;
322 if (!pub)
return std::nullopt;
327 suborigin.fingerprint = m_origin.fingerprint;
328 suborigin.path.insert(
suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
332 out.origins.insert_or_assign(
keyid, std::move(origin.mapped()));
335 bool IsRange()
const override {
return m_provider->IsRange(); }
336 size_t GetSize()
const override {
return m_provider->GetSize(); }
337 bool IsBIP32()
const override {
return m_provider->IsBIP32(); }
338 std::string
ToString(StringType type)
const override {
return "[" +
OriginString(type) +
"]" + m_provider->ToString(type); }
349 if (!m_provider->ToNormalizedString(arg,
sub, cache))
return false;
363 m_provider->GetPrivKey(pos, arg, out);
367 return m_provider->GetRootPubKey();
371 return m_provider->GetRootExtPubKey();
373 std::unique_ptr<PubkeyProvider> Clone()
const override
375 return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
377 bool CanSelfExpand()
const override {
return m_provider->CanSelfExpand(); }
381class ConstPubkeyProvider final :
public PubkeyProvider
401 out.origins.emplace(
keyid, std::make_pair(m_pubkey, info));
402 out.pubkeys.emplace(
keyid, m_pubkey);
405 bool IsRange()
const override {
return false; }
406 size_t GetSize()
const override {
return m_pubkey.size(); }
407 bool IsBIP32()
const override {
return false; }
408 std::string
ToString(StringType type)
const override {
return m_xonly ?
HexStr(m_pubkey).substr(2) :
HexStr(m_pubkey); }
411 std::optional<CKey> key = GetPrivKey(arg);
426 std::optional<CKey> key = GetPrivKey(arg);
428 out.keys.emplace(key->GetPubKey().GetID(), *key);
438 std::unique_ptr<PubkeyProvider> Clone()
const override
440 return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
442 bool CanSelfExpand() const final {
return true; }
445enum class DeriveType {
452class BIP32PubkeyProvider final :
public PubkeyProvider
464 if (!arg.
GetKey(m_root_extkey.pubkey.GetID(), key))
return false;
465 ret.nDepth = m_root_extkey.nDepth;
466 ret.fingerprint = m_root_extkey.fingerprint;
467 ret.nChild = m_root_extkey.nChild;
468 ret.chaincode = m_root_extkey.chaincode;
476 if (!GetExtKey(arg,
xprv))
return false;
477 for (
auto entry : m_path) {
478 if (!
xprv.Derive(
xprv, entry))
return false;
488 if (m_derive == DeriveType::HARDENED_RANGED)
return true;
494 bool IsRange()
const override {
return m_derive != DeriveType::NON_RANGED; }
495 size_t GetSize()
const override {
return 33; }
496 bool IsBIP32()
const override {
return true; }
500 info.
fingerprint = m_root_extkey.id_key_fingerprint();
502 if (m_derive == DeriveType::UNHARDENED_RANGED) info.
path.push_back((
uint32_t)pos);
512 if (m_derive == DeriveType::HARDENED_RANGED)
return std::nullopt;
530 for (
auto entry : m_path) {
535 assert(m_derive != DeriveType::HARDENED_RANGED);
537 if (!
der)
return std::nullopt;
544 if (m_derive != DeriveType::HARDENED_RANGED) {
550 }
else if (info.
path.size() > 0) {
567 std::string
ToString(StringType type)
const override
571 bool ToPrivateString(
const SigningProvider& arg, std::string& out)
const override
574 if (!GetExtKey(arg, key)) {
581 if (m_derive == DeriveType::HARDENED_RANGED)
out += m_apostrophe ?
'\'' :
'h';
587 if (m_derive == DeriveType::HARDENED_RANGED) {
593 int i = (
int)m_path.size() - 1;
594 for (; i >= 0; --i) {
595 if (m_path.at(i) >> 31) {
607 for (;
k <= i; ++
k) {
609 origin.
path.push_back(m_path.at(
k));
613 for (;
k < (
int)m_path.size(); ++
k) {
616 origin.
fingerprint = m_root_extkey.id_key_fingerprint();
621 if (cache !=
nullptr) {
624 if (!
xpub.pubkey.IsValid()) {
637 assert(m_derive == DeriveType::UNHARDENED_RANGED);
646 if (m_derive == DeriveType::UNHARDENED_RANGED && !
extkey.Derive(
extkey, pos))
return;
656 return m_root_extkey;
658 std::unique_ptr<PubkeyProvider> Clone()
const override
660 return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
662 bool CanSelfExpand()
const override {
return !
IsHardened(); }
666class MuSigPubkeyProvider final :
public PubkeyProvider
670 const std::vector<std::unique_ptr<PubkeyProvider>> m_participants;
674 mutable std::unique_ptr<PubkeyProvider> m_aggregate_provider;
675 mutable std::optional<CPubKey> m_aggregate_pubkey;
676 const DeriveType m_derive;
677 const bool m_ranged_participants;
684 std::vector<std::unique_ptr<PubkeyProvider>>
providers,
690 m_path(
std::move(path)),
692 m_ranged_participants(
std::any_of(m_participants.begin(), m_participants.end(), [](const
auto& pubkey) {
return pubkey->IsRange(); }))
695 throw std::runtime_error(
"musig(): Cannot have both ranged participants and ranged derivation");
697 if (!
Assume(m_derive != DeriveType::HARDENED_RANGED)) {
698 throw std::runtime_error(
"musig(): Cannot have hardened derivation");
706 if (!m_aggregate_provider && !m_ranged_participants) {
708 std::vector<CPubKey> pubkeys;
709 for (
const auto&
prov : m_participants) {
711 if (!pubkey.has_value()) {
714 pubkeys.push_back(pubkey.value());
716 std::sort(pubkeys.begin(), pubkeys.end());
720 if (!
Assume(m_aggregate_pubkey.has_value()))
return std::nullopt;
726 m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index,
extpub, m_path, m_derive,
false);
728 m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(),
false);
733 std::vector<CPubKey> pubkeys;
734 for (
const auto&
prov : m_participants) {
736 if (!pub)
return std::nullopt;
737 pubkeys.emplace_back(*pub);
739 std::sort(pubkeys.begin(), pubkeys.end());
742 if (m_aggregate_provider) {
746 std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out,
read_cache,
write_cache);
747 if (!pub)
return std::nullopt;
749 out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
751 if (!
Assume(m_ranged_participants) || !
Assume(m_path.empty()))
return std::nullopt;
759 out.aggregate_pubkeys.emplace(
pubout, pubkeys);
765 bool IsRange()
const override {
return IsRangedDerivation() || m_ranged_participants; }
767 size_t GetSize()
const override {
return 32; }
769 std::string
ToString(StringType type)
const override
771 std::string
out =
"musig(";
772 for (
size_t i = 0; i < m_participants.size(); ++i) {
773 const auto& pubkey = m_participants.at(i);
775 out += pubkey->ToString(type);
784 bool ToPrivateString(
const SigningProvider& arg, std::string& out)
const override
788 for (
size_t i = 0; i < m_participants.size(); ++i) {
789 const auto& pubkey = m_participants.at(i);
792 if (pubkey->ToPrivateString(arg,
tmp)) {
807 for (
size_t i = 0; i < m_participants.size(); ++i) {
808 const auto& pubkey = m_participants.at(i);
811 if (!pubkey->ToNormalizedString(arg,
tmp, cache)) {
829 for (
const auto&
prov : m_participants) {
830 prov->GetPrivKey(pos, arg, out);
836 return std::ranges::all_of(m_participants, [&](
const auto&
prov) {
return prov->HavePrivateKeys(arg); });
853 std::unique_ptr<PubkeyProvider> Clone()
const override
855 std::vector<std::unique_ptr<PubkeyProvider>>
providers;
856 providers.reserve(m_participants.size());
857 for (
const std::unique_ptr<PubkeyProvider>&
p : m_participants) {
860 return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(
providers), m_path, m_derive);
865 return std::all_of(m_participants.begin(), m_participants.end(), [](
const auto& pubkey) { return pubkey->IsBIP32(); });
867 size_t GetKeyCount()
const override
869 return 1 + m_participants.size();
871 bool CanSelfExpand()
const override
875 for (
const auto& key : m_participants) {
876 if (!key->CanSelfExpand())
return false;
887 const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
889 const std::string m_name;
891 std::vector<std::string> m_warnings;
897 const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
912 virtual std::vector<CScript>
MakeScripts(
const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts,
FlatSigningProvider& out)
const = 0;
915 DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys,
const std::string&
name) : m_pubkey_args(
std::move(pubkeys)), m_name(
name), m_subdescriptor_args() {}
916 DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, std::unique_ptr<DescriptorImpl>
script,
const std::string&
name) : m_pubkey_args(
std::move(pubkeys)), m_name(
name), m_subdescriptor_args(
Vector(
std::move(
script))) {}
917 DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, std::vector<std::unique_ptr<DescriptorImpl>> scripts,
const std::string&
name) : m_pubkey_args(
std::move(pubkeys)), m_name(
name), m_subdescriptor_args(
std::move(scripts)) {}
919 enum class StringType
931 for (
const auto& arg : m_subdescriptor_args) {
932 if (!arg->IsSolvable())
return false;
940 if (m_pubkey_args.empty() && m_subdescriptor_args.empty())
return false;
942 for (
const auto&
sub: m_subdescriptor_args) {
943 if (!
sub->HavePrivateKeys(arg))
return false;
946 for (
const auto& pubkey : m_pubkey_args) {
947 if (!pubkey->HavePrivateKeys(arg))
return false;
956 for (
const auto& pubkey : m_pubkey_args) {
957 if (pubkey->IsRange())
return true;
959 for (
const auto& arg : m_subdescriptor_args) {
960 if (arg->IsRange())
return true;
973 for (
const auto&
scriptarg : m_subdescriptor_args) {
974 if (pos++)
ret +=
',';
988 size_t pos =
extra.size() > 0 ? 1 : 0;
989 std::string
ret = m_name +
"(" +
extra;
995 for (
const auto& pubkey : m_pubkey_args) {
996 if (pos++)
ret +=
',';
999 case StringType::NORMALIZED:
1000 if (!pubkey->ToNormalizedString(*arg,
tmp, cache))
return false;
1002 case StringType::PRIVATE:
1005 case StringType::PUBLIC:
1006 tmp = pubkey->ToString(PubkeyProvider::StringType::PUBLIC);
1008 case StringType::COMPAT:
1009 tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
1011 case StringType::CANONICAL:
1012 tmp = pubkey->ToString(PubkeyProvider::StringType::CANONICAL);
1058 std::vector<CPubKey> pubkeys;
1059 pubkeys.reserve(m_pubkey_args.size());
1062 for (
const auto&
p : m_pubkey_args) {
1064 if (!pubkey)
return false;
1065 pubkeys.push_back(pubkey.value());
1068 for (
const auto&
subarg : m_subdescriptor_args) {
1093 for (
const auto&
p : m_pubkey_args) {
1096 for (
const auto& arg : m_subdescriptor_args) {
1097 arg->ExpandPrivate(pos,
provider, out);
1101 std::optional<OutputType>
GetOutputType()
const override {
return std::nullopt; }
1103 std::optional<int64_t>
ScriptSize()
const override {
return {}; }
1117 void GetPubKeys(std::set<CPubKey>& pubkeys, std::set<CExtPubKey>&
ext_pubs)
const override
1119 for (
const auto&
p : m_pubkey_args) {
1120 std::optional<CPubKey> pub =
p->GetRootPubKey();
1121 if (pub) pubkeys.insert(*pub);
1122 std::optional<CExtPubKey>
ext_pub =
p->GetRootExtPubKey();
1125 for (
const auto& arg : m_subdescriptor_args) {
1126 arg->GetPubKeys(pubkeys,
ext_pubs);
1130 virtual std::unique_ptr<DescriptorImpl> Clone()
const = 0;
1132 bool HasScripts()
const override {
return true; }
1135 std::vector<std::string>
Warnings()
const override {
1136 std::vector<std::string>
all = m_warnings;
1137 for (
const auto&
sub : m_subdescriptor_args) {
1147 std::vector<const DescriptorImpl*>
todo = {
this};
1148 while (!
todo.empty()) {
1149 const DescriptorImpl* desc =
todo.back();
1151 for (
const auto&
p : desc->m_pubkey_args) {
1154 for (
const auto& s : desc->m_subdescriptor_args) {
1155 todo.push_back(
s.get());
1161 size_t GetKeyCount() const final
1164 std::vector<const DescriptorImpl*>
todo = {
this};
1165 while (!
todo.empty()) {
1166 const DescriptorImpl* desc =
todo.back();
1168 for (
const auto&
p : desc->m_pubkey_args) {
1169 count +=
p->GetKeyCount();
1171 for (
const auto& s : desc->m_subdescriptor_args) {
1172 todo.push_back(
s.get());
1179 bool CanSelfExpand()
const override
1181 for (
const auto& key : m_pubkey_args) {
1182 if (!key->CanSelfExpand())
return false;
1184 for (
const auto&
sub : m_subdescriptor_args) {
1185 if (!
sub->CanSelfExpand())
return false;
1192class AddressDescriptor final :
public DescriptorImpl
1199 AddressDescriptor(
CTxDestination destination) : DescriptorImpl({},
"addr"), m_destination(std::move(destination)) {}
1200 bool IsSolvable() const final {
return false; }
1202 std::optional<OutputType> GetOutputType()
const override
1206 bool IsSingleType() const final {
return true; }
1207 bool ToPrivateString(
const SigningProvider& arg, std::string& out)
const final {
return false; }
1210 std::unique_ptr<DescriptorImpl> Clone()
const override
1212 return std::make_unique<AddressDescriptor>(m_destination);
1217class RawDescriptor final :
public DescriptorImpl
1225 bool IsSolvable() const final {
return false; }
1227 std::optional<OutputType> GetOutputType()
const override
1233 bool IsSingleType() const final {
return true; }
1234 bool ToPrivateString(
const SigningProvider& arg, std::string& out)
const final {
return false; }
1236 std::optional<int64_t> ScriptSize()
const override {
return m_script.size(); }
1238 std::unique_ptr<DescriptorImpl> Clone()
const override
1240 return std::make_unique<RawDescriptor>(m_script);
1245class PKDescriptor final :
public DescriptorImpl
1260 PKDescriptor(std::unique_ptr<PubkeyProvider>
prov,
bool xonly =
false) : DescriptorImpl(
Vector(
std::move(
prov)),
"pk"), m_xonly(
xonly) {}
1261 bool IsSingleType() const final {
return true; }
1263 std::optional<int64_t> ScriptSize()
const override {
1264 return 1 + (m_xonly ? 32 : m_pubkey_args[0]->GetSize()) + 1;
1272 std::optional<int64_t> MaxSatisfactionWeight(
bool use_max_sig)
const override {
1276 std::optional<int64_t> MaxSatisfactionElems()
const override {
return 1; }
1278 std::unique_ptr<DescriptorImpl> Clone()
const override
1280 return std::make_unique<PKDescriptor>(m_pubkey_args.at(0)->Clone(), m_xonly);
1285class PKHDescriptor final :
public DescriptorImpl
1294 PKHDescriptor(std::unique_ptr<PubkeyProvider>
prov) : DescriptorImpl(
Vector(
std::move(
prov)),
"pkh") {}
1295 std::optional<OutputType> GetOutputType()
const override {
return OutputType::LEGACY; }
1296 bool IsSingleType() const final {
return true; }
1298 std::optional<int64_t> ScriptSize()
const override {
return 1 + 1 + 1 + 20 + 1 + 1; }
1302 return 1 +
sig_size + 1 + m_pubkey_args[0]->GetSize();
1305 std::optional<int64_t> MaxSatisfactionWeight(
bool use_max_sig)
const override {
1309 std::optional<int64_t> MaxSatisfactionElems()
const override {
return 2; }
1311 std::unique_ptr<DescriptorImpl> Clone()
const override
1313 return std::make_unique<PKHDescriptor>(m_pubkey_args.at(0)->Clone());
1318class WPKHDescriptor final :
public DescriptorImpl
1327 WPKHDescriptor(std::unique_ptr<PubkeyProvider>
prov) : DescriptorImpl(
Vector(
std::move(
prov)),
"wpkh") {}
1328 std::optional<OutputType> GetOutputType()
const override {
return OutputType::BECH32; }
1329 bool IsSingleType() const final {
return true; }
1331 std::optional<int64_t> ScriptSize()
const override {
return 1 + 1 + 20; }
1335 return (1 + sig_size + 1 + 33);
1338 std::optional<int64_t> MaxSatisfactionWeight(
bool use_max_sig)
const override {
1342 std::optional<int64_t> MaxSatisfactionElems()
const override {
return 2; }
1344 std::unique_ptr<DescriptorImpl> Clone()
const override
1346 return std::make_unique<WPKHDescriptor>(m_pubkey_args.at(0)->Clone());
1351class ComboDescriptor final :
public DescriptorImpl
1356 std::vector<CScript>
ret;
1360 if (
keys[0].IsCompressed()) {
1369 ComboDescriptor(std::unique_ptr<PubkeyProvider>
prov) : DescriptorImpl(
Vector(
std::move(
prov)),
"combo") {}
1370 bool IsSingleType() const final {
return false; }
1371 std::unique_ptr<DescriptorImpl> Clone()
const override
1373 return std::make_unique<ComboDescriptor>(m_pubkey_args.at(0)->Clone());
1378class MultisigDescriptor final :
public DescriptorImpl
1380 const int m_threshold;
1381 const bool m_sorted;
1393 MultisigDescriptor(
int threshold, std::vector<std::unique_ptr<PubkeyProvider>>
providers,
bool sorted =
false) : DescriptorImpl(
std::move(
providers),
sorted ?
"sortedmulti" :
"multi"), m_threshold(threshold), m_sorted(
sorted) {}
1394 bool IsSingleType() const final {
return true; }
1396 std::optional<int64_t> ScriptSize()
const override {
1397 const auto n_keys = m_pubkey_args.size();
1398 auto op = [](
int64_t acc,
const std::unique_ptr<PubkeyProvider>&
pk) {
return acc + 1 +
pk->GetSize();};
1399 const auto pubkeys_size{std::accumulate(m_pubkey_args.begin(), m_pubkey_args.end(),
int64_t{0}, op)};
1405 return (1 + (1 + sig_size) * m_threshold);
1408 std::optional<int64_t> MaxSatisfactionWeight(
bool use_max_sig)
const override {
1412 std::optional<int64_t> MaxSatisfactionElems()
const override {
return 1 + m_threshold; }
1414 std::unique_ptr<DescriptorImpl> Clone()
const override
1416 std::vector<std::unique_ptr<PubkeyProvider>>
providers;
1417 providers.reserve(m_pubkey_args.size());
1418 std::transform(m_pubkey_args.begin(), m_pubkey_args.end(), std::back_inserter(
providers), [](
const std::unique_ptr<PubkeyProvider>&
p) { return p->Clone(); });
1419 return std::make_unique<MultisigDescriptor>(m_threshold, std::move(
providers), m_sorted);
1424class MultiADescriptor final :
public DescriptorImpl
1426 const int m_threshold;
1427 const bool m_sorted;
1432 std::vector<XOnlyPubKey>
xkeys;
1434 for (
const auto& key :
keys)
xkeys.emplace_back(key);
1435 if (m_sorted) std::sort(
xkeys.begin(),
xkeys.end());
1437 for (
size_t i = 1; i <
keys.size(); ++i) {
1444 MultiADescriptor(
int threshold, std::vector<std::unique_ptr<PubkeyProvider>>
providers,
bool sorted =
false) : DescriptorImpl(
std::move(
providers),
sorted ?
"sortedmulti_a" :
"multi_a"), m_threshold(threshold), m_sorted(
sorted) {}
1445 bool IsSingleType() const final {
return true; }
1447 std::optional<int64_t> ScriptSize()
const override {
1448 const auto n_keys = m_pubkey_args.size();
1453 return (1 + 65) * m_threshold + (m_pubkey_args.size() - m_threshold);
1456 std::optional<int64_t> MaxSatisfactionElems()
const override {
return m_pubkey_args.size(); }
1458 std::unique_ptr<DescriptorImpl> Clone()
const override
1460 std::vector<std::unique_ptr<PubkeyProvider>>
providers;
1461 providers.reserve(m_pubkey_args.size());
1462 for (
const auto& arg : m_pubkey_args) {
1465 return std::make_unique<MultiADescriptor>(m_threshold, std::move(
providers), m_sorted);
1470class SHDescriptor final :
public DescriptorImpl
1476 if (
ret.size())
out.scripts.emplace(
CScriptID(scripts[0]), scripts[0]);
1480 bool IsSegwit()
const {
return m_subdescriptor_args[0]->GetOutputType() ==
OutputType::BECH32; }
1483 SHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc),
"sh") {}
1485 std::optional<OutputType> GetOutputType()
const override
1487 assert(m_subdescriptor_args.size() == 1);
1491 bool IsSingleType() const final {
return true; }
1493 std::optional<int64_t> ScriptSize()
const override {
return 1 + 1 + 20 + 1; }
1495 std::optional<int64_t> MaxSatisfactionWeight(
bool use_max_sig)
const override {
1497 if (
const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1508 std::optional<int64_t> MaxSatisfactionElems()
const override {
1509 if (
const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems())
return 1 + *
sub_elems;
1513 std::unique_ptr<DescriptorImpl> Clone()
const override
1515 return std::make_unique<SHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1520class WSHDescriptor final :
public DescriptorImpl
1526 if (
ret.size())
out.scripts.emplace(
CScriptID(scripts[0]), scripts[0]);
1530 WSHDescriptor(std::unique_ptr<DescriptorImpl> desc) : DescriptorImpl({}, std::move(desc),
"wsh") {}
1531 std::optional<OutputType> GetOutputType()
const override {
return OutputType::BECH32; }
1532 bool IsSingleType() const final {
return true; }
1534 std::optional<int64_t> ScriptSize()
const override {
return 1 + 1 + 32; }
1538 if (
const auto subscript_size = m_subdescriptor_args[0]->ScriptSize()) {
1545 std::optional<int64_t> MaxSatisfactionWeight(
bool use_max_sig)
const override {
1549 std::optional<int64_t> MaxSatisfactionElems()
const override {
1550 if (
const auto sub_elems = m_subdescriptor_args[0]->MaxSatisfactionElems())
return 1 + *
sub_elems;
1554 std::unique_ptr<DescriptorImpl> Clone()
const override
1556 return std::make_unique<WSHDescriptor>(m_subdescriptor_args.at(0)->Clone());
1561class TRDescriptor final :
public DescriptorImpl
1563 std::vector<int> m_depths;
1568 assert(m_depths.size() == scripts.size());
1569 for (
size_t pos = 0; pos < m_depths.size(); ++pos) {
1572 if (!
builder.IsComplete())
return {};
1575 if (!
xpk.IsFullyValid())
return {};
1583 if (m_depths.empty()) {
1589 return type != StringType::PRIVATE;
1591 std::vector<bool> path;
1592 bool is_private{type == StringType::PRIVATE};
1597 for (
size_t pos = 0; pos < m_depths.size(); ++pos) {
1598 if (pos)
ret +=
',';
1599 while ((
int)path.size() <= m_depths[pos]) {
1600 if (path.size())
ret +=
'{';
1601 path.push_back(
false);
1604 bool subscript_res{m_subdescriptor_args[pos]->ToStringHelper(arg,
tmp, type, cache)};
1608 while (!path.empty() && path.back()) {
1609 if (path.size() > 1)
ret +=
'}';
1612 if (!path.empty()) path.back() =
true;
1617 TRDescriptor(std::unique_ptr<PubkeyProvider> internal_key, std::vector<std::unique_ptr<DescriptorImpl>>
descs, std::vector<int>
depths) :
1620 assert(m_subdescriptor_args.size() == m_depths.size());
1623 bool IsSingleType() const final {
return true; }
1625 std::optional<int64_t> ScriptSize()
const override {
return 1 + 1 + 32; }
1627 std::optional<int64_t> MaxSatisfactionWeight(
bool)
const override {
1632 std::optional<int64_t> MaxSatisfactionElems()
const override {
1637 std::unique_ptr<DescriptorImpl> Clone()
const override
1639 std::vector<std::unique_ptr<DescriptorImpl>>
subdescs;
1640 subdescs.reserve(m_subdescriptor_args.size());
1641 std::transform(m_subdescriptor_args.begin(), m_subdescriptor_args.end(), std::back_inserter(
subdescs), [](
const std::unique_ptr<DescriptorImpl>& d) { return d->Clone(); });
1642 return std::make_unique<TRDescriptor>(m_pubkey_args.at(0)->Clone(), std::move(
subdescs), m_depths);
1656 const std::vector<CPubKey>& m_keys;
1667 return m_keys[key].GetID();
1673 std::vector<unsigned char> ToPKBytes(
uint32_t key)
const {
1676 return {m_keys[key].begin(), m_keys[key].end()};
1684 return {
id.begin(),
id.end()};
1695 const std::vector<std::unique_ptr<PubkeyProvider>>& m_pubkeys;
1697 const DescriptorImpl::StringType m_type;
1702 const std::vector<std::unique_ptr<PubkeyProvider>>& pubkeys
LIFETIMEBOUND,
1703 DescriptorImpl::StringType type,
1705 : m_arg(arg), m_pubkeys(pubkeys), m_type(type), m_cache(cache) {}
1712 case DescriptorImpl::StringType::PUBLIC:
1713 ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::PUBLIC);
1715 case DescriptorImpl::StringType::PRIVATE:
1718 case DescriptorImpl::StringType::NORMALIZED:
1719 if (!m_pubkeys[key]->ToNormalizedString(*m_arg,
ret, m_cache))
return {};
1721 case DescriptorImpl::StringType::COMPAT:
1726 ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::PUBLIC);
1728 case DescriptorImpl::StringType::CANONICAL:
1729 ret = m_pubkeys[key]->ToString(PubkeyProvider::StringType::CANONICAL);
1736class MiniscriptDescriptor final :
public DescriptorImpl
1742 std::vector<CScript>
MakeScripts(
const std::vector<CPubKey>&
keys, std::span<const CScript> scripts,
1745 const auto script_ctx{
m_node.GetMsCtx()};
1746 for (
const auto& key :
keys) {
1750 provider.pubkeys.emplace(key.GetID(), key);
1763 const uint32_t raw = node.K();
1764 const uint32_t value_part = raw & ~CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG;
1765 if (value_part > CTxIn::SEQUENCE_LOCKTIME_MASK) {
1766 const bool is_time_based = (raw & CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG) != 0;
1767 if (is_time_based) {
1768 m_warnings.push_back(strprintf(
"time-based relative locktime: older(%u) > (65535 * 512) seconds is unsafe", raw));
1770 m_warnings.push_back(strprintf(
"height-based relative locktime: older(%u) > 65535 blocks is unsafe", raw));
1783 if (type == StringType::PRIVATE) {
1787 return res.has_value();
1791 bool IsSolvable()
const override {
return true; }
1792 bool IsSingleType() const final {
return true; }
1794 std::optional<int64_t> ScriptSize()
const override {
return m_node.ScriptSize(); }
1796 std::optional<int64_t>
MaxSatSize(
bool)
const override
1799 return m_node.GetWitnessSize();
1802 std::optional<int64_t> MaxSatisfactionElems()
const override
1804 return m_node.GetStackSize();
1807 std::unique_ptr<DescriptorImpl> Clone()
const override
1809 std::vector<std::unique_ptr<PubkeyProvider>>
providers;
1810 providers.reserve(m_pubkey_args.size());
1811 for (
const auto& arg : m_pubkey_args) {
1814 return std::make_unique<MiniscriptDescriptor>(std::move(
providers),
m_node.Clone());
1819class RawTRDescriptor final :
public DescriptorImpl
1826 if (!
xpk.IsFullyValid())
return {};
1833 bool IsSingleType() const final {
return true; }
1835 std::optional<int64_t> ScriptSize()
const override {
return 1 + 1 + 32; }
1837 std::optional<int64_t> MaxSatisfactionWeight(
bool)
const override {
1842 std::optional<int64_t> MaxSatisfactionElems()
const override {
1847 std::unique_ptr<DescriptorImpl> Clone()
const override
1849 return std::make_unique<RawTRDescriptor>(m_pubkey_args.at(0)->Clone());
1854class UnusedDescriptor final :
public DescriptorImpl
1859 UnusedDescriptor(std::unique_ptr<PubkeyProvider>
prov) : DescriptorImpl(
Vector(
std::move(
prov)),
"unused") {}
1860 bool IsSingleType() const final {
return true; }
1861 bool HasScripts()
const override {
return false; }
1863 std::unique_ptr<DescriptorImpl> Clone()
const override
1865 return std::make_unique<UnusedDescriptor>(m_pubkey_args.at(0)->Clone());
1874enum class ParseScriptContext {
1896 auto parse_elem = [&](std::span<const char>
elem) -> std::optional<uint32_t> {
1900 return std::nullopt;
1902 if (
parsed->is_hardened) {
1906 return parsed->ChildNumber();
1912 std::vector<uint32_t>
values;
1917 for (
size_t i = 1; i < split.size(); ++i) {
1918 const std::span<const char>&
elem = split[i];
1921 if (!
elem.empty() &&
elem.front() ==
'<' &&
elem.back() ==
'>') {
1923 error =
strprintf(
"Key path value '%s' specifies multipath in a section where multipath is not allowed", std::string(
elem.begin(),
elem.end()));
1927 error =
"Multiple multipath key path specifiers found";
1932 std::vector<std::span<const char>>
nums =
Split(std::span(
elem.begin()+1,
elem.end()-1),
";");
1933 if (
nums.size() < 2) {
1934 error =
"Multipath key path specifiers must have at least two items";
1940 for (
const auto& num :
nums) {
1942 if (!
op_num)
return false;
1945 error =
strprintf(
"Duplicated key path value %u in multipath specifier", *
op_num);
1951 path.emplace_back();
1955 if (!
op_num)
return false;
1956 path.emplace_back(*
op_num);
1961 out.emplace_back(std::move(path));
1981 DeriveType type = DeriveType::NON_RANGED;
1982 if (std::ranges::equal(split.back(), std::span{
"*"}.first(1))) {
1984 type = DeriveType::UNHARDENED_RANGED;
1985 }
else if (std::ranges::equal(split.back(), std::span{
"*'"}.first(2)) || std::ranges::equal(split.back(), std::span{
"*h"}.first(2))) {
1986 apostrophe = std::ranges::equal(split.back(), std::span{
"*'"}.first(2));
1988 type = DeriveType::HARDENED_RANGED;
1996 std::vector<std::unique_ptr<PubkeyProvider>>
ret;
1997 bool permit_uncompressed = ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH;
1999 std::string_view str(split[0].
data(), split[0].size());
2000 if (str.size() == 0) {
2001 error =
"No key provided";
2005 error =
strprintf(
"Key '%s' is invalid due to whitespace", str);
2008 if (split.size() == 1) {
2012 if (pubkey.IsValid() && !pubkey.IsValidNonHybrid()) {
2013 error =
"Hybrid public keys are not allowed";
2016 if (pubkey.IsFullyValid()) {
2018 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(
key_exp_index, pubkey,
false));
2022 error =
"Uncompressed keys are not allowed";
2025 }
else if (
data.size() == 32 && ctx == ParseScriptContext::P2TR) {
2026 unsigned char fullkey[33] = {0x02};
2029 if (pubkey.IsFullyValid()) {
2030 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(
key_exp_index, pubkey,
true));
2035 error =
strprintf(
"Pubkey '%s' is invalid", str);
2042 out.keys.emplace(pubkey.
GetID(), key);
2043 ret.emplace_back(std::make_unique<ConstPubkeyProvider>(
key_exp_index, pubkey, ctx == ParseScriptContext::P2TR));
2047 error =
"Uncompressed keys are not allowed";
2054 error =
strprintf(
"key '%s' is not valid", str);
2057 std::vector<KeyPath>
paths;
2060 if (
extkey.key.IsValid()) {
2064 for (
auto& path :
paths) {
2075 std::vector<std::unique_ptr<PubkeyProvider>>
ret;
2080 std::span<const char> span =
sp;
2081 if (
Const(
"musig(", span,
false)) {
2082 if (ctx != ParseScriptContext::P2TR) {
2083 error =
"musig() is only allowed in tr() and rawtr()";
2089 auto split =
Split(
sp,
')',
true);
2090 if (split.size() > 2) {
2091 error =
"Too many ')' in musig() expression";
2094 std::span<const char>
expr(split.at(0).begin(), split.at(0).end());
2096 error =
"Invalid musig() expression";
2103 std::vector<std::vector<std::unique_ptr<PubkeyProvider>>>
providers;
2106 while (
expr.size()) {
2108 error =
strprintf(
"musig(): expected ',', got '%c'",
expr[0]);
2114 error =
strprintf(
"musig(): %s", error);
2127 error =
"musig(): Must contain key expressions";
2132 DeriveType
deriv_type = DeriveType::NON_RANGED;
2134 if (split.size() == 2 &&
Const(
"/", split.at(1),
false)) {
2136 error =
"musig(): derivation requires all participants to be xpubs or xprvs";
2140 error =
"musig(): Cannot have ranged participant keys if musig() also has derivation";
2146 if (
deriv_type == DeriveType::HARDENED_RANGED) {
2147 error =
"musig(): Cannot have hardened child derivation";
2152 error =
"musig(): " + error;
2156 error =
"musig(): cannot have hardened derivation steps";
2168 for (
size_t i = 1; i < length; ++i) {
2182 std::vector<std::unique_ptr<PubkeyProvider>>
pubs;
2191 error =
"musig(): Cannot have multipath participant keys if musig() is also multipath";
2195 error =
strprintf(
"musig(): Multipath derivation paths have mismatched lengths");
2205 error =
"musig(): Multipath derivation path with multipath participants is disallowed";
2222 error =
"Multiple ']' characters found for a single pubkey";
2231 error =
strprintf(
"Key origin start '[ character expected but not found, got '%c' instead",
2237 error =
strprintf(
"Fingerprint is not 4 bytes (%u characters instead of 8 characters)",
slash_split[0].size());
2247 static_assert(
sizeof(info.
fingerprint) == 4,
"Fingerprint must be 4 bytes");
2250 std::vector<KeyPath> path;
2252 info.
path = path.at(0);
2257 ret.emplace_back(std::make_unique<OriginPubkeyProvider>(
prov->m_expr_index, info, std::move(
prov),
apostrophe));
2269 if (ctx != ParseScriptContext::TOP && ctx != ParseScriptContext::P2SH && !pubkey.
IsCompressed()) {
2272 std::unique_ptr<PubkeyProvider>
key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey,
false);
2275 return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(
key_provider),
false);
2282 CPubKey pubkey{
xkey.GetEvenCorrespondingCPubKey()};
2283 std::unique_ptr<PubkeyProvider>
key_provider = std::make_unique<ConstPubkeyProvider>(0, pubkey,
true);
2286 return std::make_unique<OriginPubkeyProvider>(0, std::move(info), std::move(
key_provider),
false);
2302 mutable std::vector<std::vector<std::unique_ptr<PubkeyProvider>>> m_keys;
2304 mutable std::string m_key_parsing_error;
2314 bool KeyCompare(
const Key&
a,
const Key& b)
const {
2318 const PubkeyProvider&
key_a{*m_keys.at(
a).at(0)};
2319 const PubkeyProvider&
key_b{*m_keys.at(b).at(0)};
2326 if (
pub_a.has_value() !=
pub_b.has_value())
return !
pub_a.has_value();
2327 return key_a.ToString(PubkeyProvider::StringType::PUBLIC) <
key_b.ToString(PubkeyProvider::StringType::PUBLIC);
2331 switch (m_script_ctx) {
2338 std::optional<Key>
FromString(std::span<const char>& in)
const
2341 Key key = m_keys.
size();
2343 if (
pk.empty())
return {};
2344 m_keys.emplace_back(std::move(pk));
2348 std::optional<std::string>
ToString(
const Key& key,
bool&)
const
2350 return m_keys.at(key).at(0)->ToString(PubkeyProvider::StringType::PUBLIC);
2353 template<
typename I> std::optional<Key> FromPKBytes(I begin, I end)
const
2356 Key key = m_keys.size();
2359 std::copy(begin, end, pubkey.
begin());
2361 m_keys.emplace_back();
2368 m_keys.emplace_back();
2376 template<
typename I> std::optional<Key> FromPKHBytes(I begin, I end)
const
2378 assert(end - begin == 20);
2381 std::copy(begin, end, hash.
begin());
2386 Key key = m_keys.
size();
2387 m_keys.emplace_back();
2396 return m_script_ctx;
2405 Assume(ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR);
2406 std::vector<std::unique_ptr<DescriptorImpl>>
ret;
2410 if (pubkeys.empty()) {
2414 for (
auto& pubkey : pubkeys) {
2415 ret.emplace_back(std::make_unique<PKDescriptor>(std::move(pubkey), ctx == ParseScriptContext::P2TR));
2419 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) &&
Func(
"pkh",
expr)) {
2421 if (pubkeys.empty()) {
2425 for (
auto& pubkey : pubkeys) {
2426 ret.emplace_back(std::make_unique<PKHDescriptor>(std::move(pubkey)));
2430 if (ctx == ParseScriptContext::TOP &&
Func(
"combo",
expr)) {
2432 if (pubkeys.empty()) {
2433 error =
strprintf(
"combo(): %s", error);
2436 for (
auto& pubkey : pubkeys) {
2437 ret.emplace_back(std::make_unique<ComboDescriptor>(std::move(pubkey)));
2441 error =
"Can only have combo() at top level";
2448 if (((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH) && (
multi ||
sortedmulti)) ||
2452 std::vector<std::vector<std::unique_ptr<PubkeyProvider>>>
providers;
2456 error =
strprintf(
"Multi threshold '%s' is not valid", std::string(threshold.begin(), threshold.end()));
2461 while (
expr.size()) {
2463 error =
strprintf(
"Multi: expected ',', got '%c'",
expr[0]);
2482 }
else if (
thres < 1) {
2483 error =
strprintf(
"Multisig threshold cannot be %d, must be at least 1",
thres);
2486 error =
strprintf(
"Multisig threshold cannot be larger than the number of keys; threshold is %d but only %u keys specified",
thres,
providers.size());
2489 if (ctx == ParseScriptContext::TOP) {
2491 error =
strprintf(
"Cannot have %u pubkeys in bare multisig; only at most 3 pubkeys",
providers.size());
2495 if (ctx == ParseScriptContext::P2SH) {
2506 if (
vec.size() == 1) {
2508 vec.emplace_back(
vec.at(0)->Clone());
2511 error =
strprintf(
"multi(): Multipath derivation paths have mismatched lengths");
2519 std::vector<std::unique_ptr<PubkeyProvider>>
pubs;
2522 pubs.emplace_back(std::move(pub.at(i)));
2532 error =
"Can only have multi/sortedmulti at top level, in sh(), or in wsh()";
2535 error =
"Can only have multi_a/sortedmulti_a inside tr()";
2538 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) &&
Func(
"wpkh",
expr)) {
2540 if (pubkeys.empty()) {
2544 for (
auto& pubkey : pubkeys) {
2545 ret.emplace_back(std::make_unique<WPKHDescriptor>(std::move(pubkey)));
2549 error =
"Can only have wpkh() at top level or inside sh()";
2552 if (ctx == ParseScriptContext::TOP &&
Func(
"sh",
expr)) {
2554 if (
descs.empty() ||
expr.size())
return {};
2555 std::vector<std::unique_ptr<DescriptorImpl>>
ret;
2557 for (
auto& desc :
descs) {
2558 ret.push_back(std::make_unique<SHDescriptor>(std::move(desc)));
2562 error =
"Can only have sh() at top level";
2565 if ((ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH) &&
Func(
"wsh",
expr)) {
2567 if (
descs.empty() ||
expr.size())
return {};
2568 for (
auto& desc :
descs) {
2569 ret.emplace_back(std::make_unique<WSHDescriptor>(std::move(desc)));
2573 error =
"Can only have wsh() at top level or inside sh()";
2576 if (ctx == ParseScriptContext::TOP &&
Func(
"addr",
expr)) {
2579 error =
"Address is not valid";
2582 ret.emplace_back(std::make_unique<AddressDescriptor>(std::move(dest)));
2585 error =
"Can only have addr() at top level";
2588 if (ctx == ParseScriptContext::TOP &&
Func(
"tr",
expr)) {
2596 std::vector<std::vector<std::unique_ptr<DescriptorImpl>>>
subscripts;
2627 error =
strprintf(
"tr(): expected '}' after script expression");
2635 error =
strprintf(
"tr(): expected ',' after script expression");
2643 error =
strprintf(
"tr(): expected ')' after script expression");
2652 if (
vec.size() == 1) {
2654 vec.emplace_back(
vec.at(0)->Clone());
2657 error =
strprintf(
"tr(): Multipath subscripts have mismatched lengths");
2663 error =
strprintf(
"tr(): Multipath internal key mismatches multipath subscripts lengths");
2674 std::vector<std::unique_ptr<DescriptorImpl>>
this_subs;
2677 this_subs.emplace_back(std::move(subs.at(i)));
2685 error =
"Can only have tr at top level";
2688 if (ctx == ParseScriptContext::TOP &&
Func(
"rawtr",
expr)) {
2691 error =
strprintf(
"rawtr(): only one key expected.");
2696 error =
strprintf(
"rawtr(): %s", error);
2700 ret.emplace_back(std::make_unique<RawTRDescriptor>(std::move(pubkey)));
2704 error =
"Can only have rawtr at top level";
2707 if (ctx == ParseScriptContext::TOP &&
Func(
"unused",
expr)) {
2711 error =
strprintf(
"unused(): only one key expected");
2715 if (
keys.empty())
return {};
2716 for (
auto& pubkey :
keys) {
2717 if (pubkey->IsRange()) {
2718 error =
"unused(): key cannot be ranged";
2721 ret.emplace_back(std::make_unique<UnusedDescriptor>(std::move(pubkey)));
2725 error =
"Can only have unused at top level";
2728 if (ctx == ParseScriptContext::TOP &&
Func(
"raw",
expr)) {
2729 std::string str(
expr.begin(),
expr.end());
2731 error =
"Raw script is not hex";
2735 ret.emplace_back(std::make_unique<RawDescriptor>(
CScript(bytes.begin(), bytes.end())));
2738 error =
"Can only have raw() at top level";
2746 if (
parser.m_key_parsing_error !=
"") {
2747 error = std::move(
parser.m_key_parsing_error);
2751 if (ctx != ParseScriptContext::P2WSH && ctx != ParseScriptContext::P2TR) {
2752 error =
"Miniscript expressions can only be used in wsh or tr.";
2755 if (!
node->IsSane() ||
node->IsNotSatisfiable()) {
2761 error +=
" is invalid";
2762 }
else if (!
node->IsSane()) {
2763 error +=
" is not sane";
2765 error +=
": malleable witnesses exist";
2767 error +=
": witnesses without signature exist";
2769 error +=
": contains mixes of timelocks expressed in blocks and seconds";
2771 error +=
": contains duplicate public keys";
2773 error +=
": needs witnesses that may exceed resource limits";
2776 error +=
" is not satisfiable";
2786 [](
const std::vector<std::unique_ptr<PubkeyProvider>>&
a,
const std::vector<std::unique_ptr<PubkeyProvider>>& b) {
2787 return a.size() < b.size();
2791 if (
vec.size() == 1) {
2793 vec.emplace_back(
vec.at(0)->Clone());
2796 error =
strprintf(
"Miniscript: Multipath derivation paths have mismatched lengths");
2804 std::vector<std::unique_ptr<PubkeyProvider>>
pubs;
2806 for (
auto& pub :
parser.m_keys) {
2807 pubs.emplace_back(std::move(pub.at(i)));
2809 ret.emplace_back(std::make_unique<MiniscriptDescriptor>(std::move(
pubs),
node->Clone()));
2814 if (ctx == ParseScriptContext::P2SH) {
2815 error =
"A function is needed within P2SH";
2817 }
else if (ctx == ParseScriptContext::P2WSH) {
2818 error =
"A function is needed within P2WSH";
2821 error =
strprintf(
"'%s' is not a valid descriptor function", std::string(
expr.begin(),
expr.end()));
2828 if (!
match)
return {};
2829 std::vector<std::unique_ptr<PubkeyProvider>>
keys;
2832 if (
keyspan.size() != 32)
return {};
2834 if (!key)
return {};
2835 keys.push_back(std::move(key));
2837 return std::make_unique<MultiADescriptor>(
match->first, std::move(
keys));
2848 if (ctx == ParseScriptContext::P2TR) {
2853 std::vector<std::vector<unsigned char>>
data;
2856 if (
txntype ==
TxoutType::PUBKEY && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2862 if (
txntype ==
TxoutType::PUBKEYHASH && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2882 if (
txntype ==
TxoutType::MULTISIG && (ctx == ParseScriptContext::TOP || ctx == ParseScriptContext::P2SH || ctx == ParseScriptContext::P2WSH)) {
2884 std::vector<std::unique_ptr<PubkeyProvider>>
providers;
2885 for (
size_t i = 1; i + 1 <
data.size(); ++i) {
2894 if (
ok)
return std::make_unique<MultisigDescriptor>((
int)
data[0][0], std::move(
providers));
2902 if (
sub)
return std::make_unique<SHDescriptor>(std::move(
sub));
2910 if (
sub)
return std::make_unique<WSHDescriptor>(std::move(
sub));
2925 std::vector<std::unique_ptr<DescriptorImpl>>
subscripts;
2928 std::unique_ptr<DescriptorImpl>
subdesc;
2942 return std::make_unique<TRDescriptor>(std::move(key), std::move(
subscripts), std::move(
depths));
2950 return std::make_unique<RawTRDescriptor>(std::move(key));
2955 if (ctx == ParseScriptContext::P2WSH || ctx == ParseScriptContext::P2TR) {
2961 std::vector<std::unique_ptr<PubkeyProvider>>
keys;
2963 for (
auto& key :
parser.m_keys) {
2964 keys.emplace_back(std::move(key.at(0)));
2966 return std::make_unique<MiniscriptDescriptor>(std::move(
keys), std::move(*
node));
2972 if (ctx != ParseScriptContext::TOP)
return nullptr;
2977 return std::make_unique<AddressDescriptor>(std::move(dest));
2981 return std::make_unique<RawDescriptor>(
script);
2992 error =
"Multiple '#' symbols";
2996 error =
"Missing checksum";
3007 error =
"Invalid characters in payload";
3023 std::span<const char>
sp{descriptor};
3027 if (
sp.empty() && !
ret.empty()) {
3028 std::vector<std::unique_ptr<Descriptor>>
descs;
3030 for (
auto& r :
ret) {
3031 descs.emplace_back(std::unique_ptr<Descriptor>(std::move(r)));
3042 std::span<const char>
sp{descriptor};
3109 throw std::runtime_error(std::string(
__func__) +
": New cached parent xpub does not match already cached parent xpub");
3121 throw std::runtime_error(std::string(
__func__) +
": New cached derived xpub does not match already cached derived xpub");
3133 throw std::runtime_error(std::string(
__func__) +
": New cached last hardened xpub does not match already cached last hardened xpub");
bool ExtractDestination(const CScript &scriptPubKey, CTxDestination &addressRet)
Parse a scriptPubKey for the destination.
bool IsValidDestination(const CTxDestination &dest)
Check whether a CTxDestination corresponds to one with an address.
CScript GetScriptForDestination(const CTxDestination &dest)
Generate a Bitcoin scriptPubKey for the given CTxDestination.
std::variant< CNoDestination, PubKeyDestination, PKHash, ScriptHash, WitnessV0ScriptHash, WitnessV0KeyHash, WitnessV1Taproot, PayToAnchor, WitnessUnknown > CTxDestination
A txout script categorized into standard templates.
std::string FormatHDKeypath(const std::vector< uint32_t > &path, bool apostrophe)
util::Expected< KeyPathElement, std::string > ParseKeyPathElement(std::span< const char > elem)
Parse a single key path element like "0", "0'", or "0h".
bool HasHardenedDerivation(std::span< const uint32_t > keypath)
Whether a parsed HD keypath contains at least one hardened derivation step.
static constexpr uint32_t BIP32_HARDENED_FLAG
BIP32 hardened derivation flag (2^31)
#define CHECK_NONFATAL(condition)
Identity function.
#define Assert(val)
Identity function.
#define Assume(val)
Assume is the identity function.
An encapsulated private key.
unsigned int size() const
Simple read-only vector-like interface.
bool IsValid() const
Check whether this private key is valid.
bool IsCompressed() const
Check whether the public key corresponding to this private key is (to be) compressed.
CPubKey GetPubKey() const
Compute the public key from a private key.
A reference to a CKey: the Hash160 of its serialized public key.
An encapsulated public key.
bool IsCompressed() const
Check whether this is a compressed public key.
CKeyID GetID() const
Get the KeyID of this public key (hash of its serialization)
bool IsValidNonHybrid() const noexcept
Check if a public key is a syntactically valid compressed or uncompressed key.
A hasher class for SHA-256.
void Finalize(unsigned char hash[OUTPUT_SIZE])
CSHA256 & Write(const unsigned char *data, size_t len)
Serialized script, used inside transaction inputs and outputs.
A reference to a CScript: the Hash160 of its serialization.
Cache for single descriptor's derived extended pubkeys.
bool GetCachedParentExtPubKey(uint32_t key_exp_pos, CExtPubKey &xpub) const
Retrieve a cached parent xpub.
std::unordered_map< uint32_t, ExtPubKeyMap > GetCachedDerivedExtPubKeys() const
Retrieve all cached derived xpubs.
ExtPubKeyMap m_last_hardened_xpubs
Map key expression index -> last hardened xpub.
void CacheDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, const CExtPubKey &xpub)
Cache an xpub derived at an index.
DescriptorCache MergeAndDiff(const DescriptorCache &other)
Combine another DescriptorCache into this one.
ExtPubKeyMap GetCachedParentExtPubKeys() const
Retrieve all cached parent xpubs.
ExtPubKeyMap GetCachedLastHardenedExtPubKeys() const
Retrieve all cached last hardened xpubs.
void CacheParentExtPubKey(uint32_t key_exp_pos, const CExtPubKey &xpub)
Cache a parent xpub.
void CacheLastHardenedExtPubKey(uint32_t key_exp_pos, const CExtPubKey &xpub)
Cache a last hardened xpub.
bool GetCachedDerivedExtPubKey(uint32_t key_exp_pos, uint32_t der_index, CExtPubKey &xpub) const
Retrieve a cached xpub derived at an index.
std::unordered_map< uint32_t, ExtPubKeyMap > m_derived_xpubs
Map key expression index -> map of (key derivation index -> xpub)
bool GetCachedLastHardenedExtPubKey(uint32_t key_exp_pos, CExtPubKey &xpub) const
Retrieve a cached last hardened xpub.
ExtPubKeyMap m_parent_xpubs
Map key expression index -> parent xpub.
An interface to be implemented by keystores that support signing.
bool GetKeyByXOnly(const XOnlyPubKey &pubkey, CKey &key) const
virtual bool GetPubKey(const CKeyID &address, CPubKey &pubkey) const
virtual bool GetKey(const CKeyID &address, CKey &key) const
Utility class to construct Taproot outputs from internal key and script tree.
static bool ValidDepths(const std::vector< int > &depths)
Check if a list of depths is legal (will lead to IsComplete()).
const unsigned char * begin() const
static constexpr size_t size()
bool IsFullyValid() const
Determine if this pubkey is fully valid.
constexpr unsigned char * begin()
A node in a miniscript expression.
void reserve(size_type new_capacity)
The util::Expected class provides a standard way for low-level functions to return either error value...
The util::Unexpected class represents an unexpected value stored in util::Expected.
static const PrecomputedData data
Precomputed COutPoint and CCoins values.
constexpr int WITNESS_SCALE_FACTOR
CScript ParseScript(const std::string &s)
uint160 Hash160(const T1 &in1)
Compute the 160-bit hash an object.
uint160 RIPEMD160(std::span< const unsigned char > data)
Compute the 160-bit RIPEMD-160 hash of an array.
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
constexpr uint8_t TAPROOT_LEAF_TAPSCRIPT
constexpr size_t TAPROOT_CONTROL_MAX_NODE_COUNT
std::string EncodeExtKey(const CExtKey &key)
CTxDestination DecodeDestination(const std::string &str, std::string &error_msg, std::vector< int > *error_locations)
std::pair< CExtKey, CExtPubKey > DecodeExtKeyOrPubKey(std::string_view str)
Decode a base58-encoded extended key string as either an xprv or xpub, using a single base58 decode.
std::string EncodeSecret(const CKey &key)
std::string EncodeDestination(const CTxDestination &dest)
std::string EncodeExtPubKey(const CExtPubKey &key)
CKey DecodeSecret(std::string_view str)
CExtPubKey CreateMuSig2SyntheticXpub(const CPubKey &pubkey)
Construct the BIP 328 synthetic xpub for a pubkey.
std::optional< CPubKey > MuSig2AggregatePubkeys(const std::vector< CPubKey > &pubkeys, secp256k1_musig_keyagg_cache &keyagg_cache, const std::optional< CPubKey > &expected_aggregate)
Compute the full aggregate pubkey from the given participant pubkeys in their current order.
constexpr bool IsTapscript(MiniscriptContext ms_ctx)
Whether the context Tapscript, ensuring the only other possibility is P2WSH.
std::optional< Node< typename Ctx::Key > > FromScript(const CScript &script, const Ctx &ctx)
void ForEachNode(const Node< Key > &root, Fn &&fn)
Unordered traversal of a miniscript node tree.
std::optional< Node< typename Ctx::Key > > FromString(const std::string &str, const Ctx &ctx)
@ OLDER
[n] OP_CHECKSEQUENCEVERIFY
std::span< const char > Expr(std::span< const char > &sp)
Extract the expression that sp begins with.
bool Func(const std::string &str, std::span< const char > &sp)
Parse a function call.
bool Const(const std::string &str, std::span< const char > &sp, bool skip)
Parse a constant.
std::vector< T > Split(std::span< const char > sp LIFETIMEBOUND, std::string_view separators, bool include_sep=false)
Split a string on any char found in separators, returning a vector.
std::string ToString(const T &t)
Locale-independent version of std::to_string.
std::optional< OutputType > OutputTypeFromDestination(const CTxDestination &dest)
Get the OutputType for a CTxDestination.
std::unique_ptr< Descriptor > InferDescriptor(const CScript &script, const SigningProvider &provider)
Find a descriptor for the specified script, using information from provider where possible.
bool CheckChecksum(std::span< const char > &sp, bool require_checksum, std::string &error, std::string *out_checksum=nullptr)
Check a descriptor checksum, and update desc to be the checksum-less part.
std::vector< std::unique_ptr< Descriptor > > Parse(std::string_view descriptor, FlatSigningProvider &out, std::string &error, bool require_checksum)
Parse a descriptor string.
std::string GetDescriptorChecksum(const std::string &descriptor)
Get the checksum for a descriptor.
uint256 CompatDescriptorHash(const Descriptor &desc)
Hash of the COMPAT string representation of the descriptor that is not supposed to change over time.
util::Expected< void, std::string > CheckDescriptorRangeBounds(int64_t low, int64_t high)
Validate the numeric bounds of a descriptor key-expression range [low, high] (high inclusive).
std::unordered_map< uint32_t, CExtPubKey > ExtPubKeyMap
constexpr unsigned int MAX_PUBKEYS_PER_MULTI_A
The limit of keys in OP_CHECKSIGADD-based scripts.
constexpr unsigned int MAX_SCRIPT_ELEMENT_SIZE
constexpr int MAX_PUBKEYS_PER_MULTISIG
CScript BuildScript(Ts &&... inputs)
Build a script by concatenating other scripts, or any argument accepted by CScript::operator<<.
std::vector< unsigned char > ToByteVector(const T &in)
static const int64_t values[]
A selection of numbers that do not trigger int64_t overflow when added/subtracted.
constexpr unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
static bool GetPubKey(const SigningProvider &provider, const SignatureData &sigdata, const CKeyID &address, CPubKey &pubkey)
std::optional< std::vector< std::tuple< int, std::vector< unsigned char >, int > > > InferTaprootTree(const TaprootSpendData &spenddata, const XOnlyPubKey &output)
Given a TaprootSpendData and the output key, reconstruct its script tree.
const SigningProvider & DUMMY_SIGNING_PROVIDER
void PolyMod(const std::vector< typename F::Elem > &mod, std::vector< typename F::Elem > &val, const F &field)
Compute the remainder of a polynomial division of val by mod, putting the result in mod.
TxoutType Solver(const CScript &scriptPubKey, std::vector< std::vector< unsigned char > > &vSolutionsRet)
Parse a scriptPubKey and identify script type for standard scripts.
CScript GetScriptForMultisig(int nRequired, const std::vector< CPubKey > &keys)
Generate a multisig script.
std::optional< std::pair< int, std::vector< std::span< const unsigned char > > > > MatchMultiA(const CScript &script)
CScript GetScriptForRawPubKey(const CPubKey &pubKey)
Generate a P2PK script for the given pubkey.
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
constexpr bool IsSpace(char c) noexcept
Tests if the given character is a whitespace character.
CExtPubKey Neuter() const
bool Derive(CExtPubKey &out, unsigned int nChild, uint256 *bip32_tweak_out=nullptr) const
Interface for parsed descriptor objects.
virtual std::optional< int64_t > MaxSatisfactionElems() const =0
Get the maximum size number of stack elements for satisfying this descriptor.
virtual void GetPubKeys(std::set< CPubKey > &pubkeys, std::set< CExtPubKey > &ext_pubs) const =0
Return all (extended) public keys for this descriptor, including any from subdescriptors.
virtual bool ToNormalizedString(const SigningProvider &provider, std::string &out, const DescriptorCache *cache=nullptr) const =0
Convert the descriptor to a normalized string.
virtual std::optional< int64_t > MaxSatisfactionWeight(bool use_max_sig) const =0
Get the maximum size of a satisfaction for this descriptor, in weight units.
virtual std::vector< std::string > Warnings() const =0
Semantic/safety warnings (includes subdescriptors).
virtual std::string ToCanonicalString() const =0
Convert the descriptor to the canonical string.
virtual std::string ToString(bool compat_format=false) const =0
Convert the descriptor back to a string, undoing parsing.
virtual std::optional< OutputType > GetOutputType() const =0
virtual bool HasScripts() const =0
Whether this descriptor produces any scripts with the Expand functions.
virtual bool Expand(int pos, const SigningProvider &provider, std::vector< CScript > &output_scripts, FlatSigningProvider &out, DescriptorCache *write_cache=nullptr) const =0
Expand a descriptor at a specified position.
virtual bool IsRange() const =0
Whether the expansion of this descriptor depends on the position.
virtual std::optional< int64_t > ScriptSize() const =0
Get the size of the scriptPubKey for this descriptor.
virtual bool IsSolvable() const =0
Whether this descriptor has all information about signing ignoring lack of private keys.
virtual void ExpandPrivate(int pos, const SigningProvider &provider, FlatSigningProvider &out) const =0
Expand the private key for a descriptor at a specified position, if possible.
virtual uint32_t GetMaxKeyExpr() const =0
Get the maximum key expression index.
virtual bool ToPrivateString(const SigningProvider &provider, std::string &out) const =0
Convert the descriptor to a private string.
virtual bool HavePrivateKeys(const SigningProvider &provider) const =0
Whether the given provider has all private keys required by this descriptor.
virtual bool ExpandFromCache(int pos, const DescriptorCache &read_cache, std::vector< CScript > &output_scripts, FlatSigningProvider &out) const =0
Expand a descriptor at a specified position using cached expansion data.
bool GetPubKey(const CKeyID &keyid, CPubKey &pubkey) const override
KeyFingerprint fingerprint
First 32 bits of the Hash160 of the public key at the root of the path.
std::vector< uint32_t > path
std::vector< uint16_t > keys
FuzzedDataProvider provider
consteval auto _(util::TranslatedLiteral str)
bool IsHex(std::string_view str)
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
std::vector< std::common_type_t< Args... > > Vector(Args &&... args)
Construct a vector with the specified elements.