-
Notifications
You must be signed in to change notification settings - Fork 367
Expand file tree
/
Copy pathdescriptor.cpp
More file actions
3071 lines (2809 loc) · 129 KB
/
Copy pathdescriptor.cpp
File metadata and controls
3071 lines (2809 loc) · 129 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2018-present The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <script/descriptor.h>
#include <hash.h>
#include <key_io.h>
#include <pubkey.h>
#include <musig.h>
#include <script/miniscript.h>
#include <script/parsing.h>
#include <script/script.h>
#include <script/signingprovider.h>
#include <script/solver.h>
#include <uint256.h>
#include <common/args.h>
#include <span.h>
#include <util/bip32.h>
#include <util/check.h>
#include <util/strencodings.h>
#include <util/vector.h>
#include <algorithm>
#include <memory>
#include <numeric>
#include <optional>
#include <string>
#include <vector>
using util::Split;
namespace {
////////////////////////////////////////////////////////////////////////////
// Checksum //
////////////////////////////////////////////////////////////////////////////
// This section implements a checksum algorithm for descriptors with the
// following properties:
// * Mistakes in a descriptor string are measured in "symbol errors". The higher
// the number of symbol errors, the harder it is to detect:
// * An error substituting a character from 0123456789()[],'/*abcdefgh@:$%{} for
// another in that set always counts as 1 symbol error.
// * Note that hex encoded keys are covered by these characters. Xprvs and
// xpubs use other characters too, but already have their own checksum
// mechanism.
// * Function names like "multi()" use other characters, but mistakes in
// these would generally result in an unparsable descriptor.
// * A case error always counts as 1 symbol error.
// * Any other 1 character substitution error counts as 1 or 2 symbol errors.
// * Any 1 symbol error is always detected.
// * Any 2 or 3 symbol error in a descriptor of up to 49154 characters is always detected.
// * Any 4 symbol error in a descriptor of up to 507 characters is always detected.
// * Any 5 symbol error in a descriptor of up to 77 characters is always detected.
// * Is optimized to minimize the chance a 5 symbol error in a descriptor up to 387 characters is undetected
// * Random errors have a chance of 1 in 2**40 of being undetected.
//
// These properties are achieved by expanding every group of 3 (non checksum) characters into
// 4 GF(32) symbols, over which a cyclic code is defined.
/*
* Interprets c as 8 groups of 5 bits which are the coefficients of a degree 8 polynomial over GF(32),
* multiplies that polynomial by x, computes its remainder modulo a generator, and adds the constant term val.
*
* This generator is G(x) = x^8 + {30}x^7 + {23}x^6 + {15}x^5 + {14}x^4 + {10}x^3 + {6}x^2 + {12}x + {9}.
* It is chosen to define an cyclic error detecting code which is selected by:
* - Starting from all BCH codes over GF(32) of degree 8 and below, which by construction guarantee detecting
* 3 errors in windows up to 19000 symbols.
* - Taking all those generators, and for degree 7 ones, extend them to degree 8 by adding all degree-1 factors.
* - Selecting just the set of generators that guarantee detecting 4 errors in a window of length 512.
* - Selecting one of those with best worst-case behavior for 5 errors in windows of length up to 512.
*
* The generator and the constants to implement it can be verified using this Sage code:
* B = GF(2) # Binary field
* BP.<b> = B[] # Polynomials over the binary field
* F_mod = b**5 + b**3 + 1
* F.<f> = GF(32, modulus=F_mod, repr='int') # GF(32) definition
* FP.<x> = F[] # Polynomials over GF(32)
* E_mod = x**3 + x + F.fetch_int(8)
* E.<e> = F.extension(E_mod) # Extension field definition
* alpha = e**2743 # Choice of an element in extension field
* for p in divisors(E.order() - 1): # Verify alpha has order 32767.
* assert((alpha**p == 1) == (p % 32767 == 0))
* G = lcm([(alpha**i).minpoly() for i in [1056,1057,1058]] + [x + 1])
* print(G) # Print out the generator
* for i in [1,2,4,8,16]: # Print out {1,2,4,8,16}*(G mod x^8), packed in hex integers.
* v = 0
* for coef in reversed((F.fetch_int(i)*(G % x**8)).coefficients(sparse=True)):
* v = v*32 + coef.integer_representation()
* print("0x%x" % v)
*/
uint64_t PolyMod(uint64_t c, int val)
{
uint8_t c0 = c >> 35;
c = ((c & 0x7ffffffff) << 5) ^ val;
if (c0 & 1) c ^= 0xf5dee51989;
if (c0 & 2) c ^= 0xa9fdca3312;
if (c0 & 4) c ^= 0x1bab10e32d;
if (c0 & 8) c ^= 0x3706b1677a;
if (c0 & 16) c ^= 0x644d626ffd;
return c;
}
std::string DescriptorChecksum(const std::span<const char>& span)
{
/** A character set designed such that:
* - The most common 'unprotected' descriptor characters (hex, keypaths) are in the first group of 32.
* - Case errors cause an offset that's a multiple of 32.
* - As many alphabetic characters are in the same group (while following the above restrictions).
*
* If p(x) gives the position of a character c in this character set, every group of 3 characters
* (a,b,c) is encoded as the 4 symbols (p(a) & 31, p(b) & 31, p(c) & 31, (p(a) / 32) + 3 * (p(b) / 32) + 9 * (p(c) / 32).
* This means that changes that only affect the lower 5 bits of the position, or only the higher 2 bits, will just
* affect a single symbol.
*
* As a result, within-group-of-32 errors count as 1 symbol, as do cross-group errors that don't affect
* the position within the groups.
*/
static const std::string INPUT_CHARSET =
"0123456789()[],'/*abcdefgh@:$%{}"
"IJKLMNOPQRSTUVWXYZ&+-.;<=>?!^_|~"
"ijklmnopqrstuvwxyzABCDEFGH`#\"\\ ";
/** The character set for the checksum itself (same as bech32). */
static const std::string CHECKSUM_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l";
uint64_t c = 1;
int cls = 0;
int clscount = 0;
for (auto ch : span) {
auto pos = INPUT_CHARSET.find(ch);
if (pos == std::string::npos) return "";
c = PolyMod(c, pos & 31); // Emit a symbol for the position inside the group, for every character.
cls = cls * 3 + (pos >> 5); // Accumulate the group numbers
if (++clscount == 3) {
// Emit an extra symbol representing the group numbers, for every 3 characters.
c = PolyMod(c, cls);
cls = 0;
clscount = 0;
}
}
if (clscount > 0) c = PolyMod(c, cls);
for (int j = 0; j < 8; ++j) c = PolyMod(c, 0); // Shift further to determine the checksum.
c ^= 1; // Prevent appending zeroes from not affecting the checksum.
std::string ret(8, ' ');
for (int j = 0; j < 8; ++j) ret[j] = CHECKSUM_CHARSET[(c >> (5 * (7 - j))) & 31];
return ret;
}
std::string AddChecksum(const std::string& str) { return str + "#" + DescriptorChecksum(str); }
////////////////////////////////////////////////////////////////////////////
// Internal representation //
////////////////////////////////////////////////////////////////////////////
typedef std::vector<uint32_t> KeyPath;
/** Interface for public key objects in descriptors. */
struct PubkeyProvider
{
public:
//! Index of this key expression in the descriptor
//! E.g. If this PubkeyProvider is key1 in multi(2, key1, key2, key3), then m_expr_index = 0
const uint32_t m_expr_index;
explicit PubkeyProvider(uint32_t exp_index) : m_expr_index(exp_index) {}
virtual ~PubkeyProvider() = default;
/** Compare two public keys represented by this provider.
* Used by the Miniscript descriptors to check for duplicate keys in the script.
*/
bool operator<(PubkeyProvider& other) const {
FlatSigningProvider dummy;
std::optional<CPubKey> a = GetPubKey(0, dummy, dummy);
std::optional<CPubKey> b = other.GetPubKey(0, dummy, dummy);
return a < b;
}
/** Derive a public key and put it into out.
* read_cache is the cache to read keys from (if not nullptr)
* write_cache is the cache to write keys to (if not nullptr)
* Caches are not exclusive but this is not tested. Currently we use them exclusively
*/
virtual std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const = 0;
/** Whether this represent multiple public keys at different positions. */
virtual bool IsRange() const = 0;
/** Get the size of the generated public key(s) in bytes (33 or 65). */
virtual size_t GetSize() const = 0;
enum class StringType {
PUBLIC,
COMPAT // string calculation that mustn't change over time to stay compatible with previous software versions
};
/** Get the descriptor string form. */
virtual std::string ToString(StringType type=StringType::PUBLIC) const = 0;
/** Get the descriptor string form including private data (if available in arg).
* If the private data is not available, the output string in the "out" parameter
* will not contain any private key information,
* and this function will return "false".
*/
virtual bool ToPrivateString(const SigningProvider& arg, std::string& out) const = 0;
/** Get the descriptor string form with the xpub at the last hardened derivation,
* and always use h for hardened derivation.
*/
virtual bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const = 0;
/** Derive a private key, if private data is available in arg and put it into out. */
virtual void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const = 0;
/** Return the non-extended public key for this PubkeyProvider, if it has one. */
virtual std::optional<CPubKey> GetRootPubKey() const = 0;
/** Return the extended public key for this PubkeyProvider, if it has one. */
virtual std::optional<CExtPubKey> GetRootExtPubKey() const = 0;
/** Make a deep copy of this PubkeyProvider */
virtual std::unique_ptr<PubkeyProvider> Clone() const = 0;
/** Whether this PubkeyProvider is a BIP 32 extended key that can be derived from */
virtual bool IsBIP32() const = 0;
/** Get the count of keys known by this PubkeyProvider. Usually one, but may be more for key aggregation schemes */
virtual size_t GetKeyCount() const { return 1; }
/** Whether this PubkeyProvider can always provide a public key without cache or private key arguments */
virtual bool CanSelfExpand() const = 0;
};
class OriginPubkeyProvider final : public PubkeyProvider
{
KeyOriginInfo m_origin;
std::unique_ptr<PubkeyProvider> m_provider;
bool m_apostrophe;
std::string OriginString(StringType type, bool normalized=false) const
{
// If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
return HexStr(m_origin.fingerprint) + FormatHDKeypath(m_origin.path, use_apostrophe);
}
public:
OriginPubkeyProvider(uint32_t exp_index, KeyOriginInfo info, std::unique_ptr<PubkeyProvider> provider, bool apostrophe) : PubkeyProvider(exp_index), m_origin(std::move(info)), m_provider(std::move(provider)), m_apostrophe(apostrophe) {}
std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
{
std::optional<CPubKey> pub = m_provider->GetPubKey(pos, arg, out, read_cache, write_cache);
if (!pub) return std::nullopt;
Assert(out.pubkeys.contains(pub->GetID()));
auto& [pubkey, suborigin] = out.origins[pub->GetID()];
Assert(pubkey == *pub); // m_provider must have a valid origin by this point.
std::copy(std::begin(m_origin.fingerprint), std::end(m_origin.fingerprint), suborigin.fingerprint);
suborigin.path.insert(suborigin.path.begin(), m_origin.path.begin(), m_origin.path.end());
return pub;
}
bool IsRange() const override { return m_provider->IsRange(); }
size_t GetSize() const override { return m_provider->GetSize(); }
bool IsBIP32() const override { return m_provider->IsBIP32(); }
std::string ToString(StringType type) const override { return "[" + OriginString(type) + "]" + m_provider->ToString(type); }
bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
{
std::string sub;
bool has_priv_key{m_provider->ToPrivateString(arg, sub)};
ret = "[" + OriginString(StringType::PUBLIC) + "]" + std::move(sub);
return has_priv_key;
}
bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
{
std::string sub;
if (!m_provider->ToNormalizedString(arg, sub, cache)) return false;
// If m_provider is a BIP32PubkeyProvider, we may get a string formatted like a OriginPubkeyProvider
// In that case, we need to strip out the leading square bracket and fingerprint from the substring,
// and append that to our own origin string.
if (sub[0] == '[') {
sub = sub.substr(9);
ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + std::move(sub);
} else {
ret = "[" + OriginString(StringType::PUBLIC, /*normalized=*/true) + "]" + std::move(sub);
}
return true;
}
void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
{
m_provider->GetPrivKey(pos, arg, out);
}
std::optional<CPubKey> GetRootPubKey() const override
{
return m_provider->GetRootPubKey();
}
std::optional<CExtPubKey> GetRootExtPubKey() const override
{
return m_provider->GetRootExtPubKey();
}
std::unique_ptr<PubkeyProvider> Clone() const override
{
return std::make_unique<OriginPubkeyProvider>(m_expr_index, m_origin, m_provider->Clone(), m_apostrophe);
}
bool CanSelfExpand() const override { return m_provider->CanSelfExpand(); }
};
/** An object representing a parsed constant public key in a descriptor. */
class ConstPubkeyProvider final : public PubkeyProvider
{
CPubKey m_pubkey;
bool m_xonly;
std::optional<CKey> GetPrivKey(const SigningProvider& arg) const
{
CKey key;
if (!(m_xonly ? arg.GetKeyByXOnly(XOnlyPubKey(m_pubkey), key) :
arg.GetKey(m_pubkey.GetID(), key))) return std::nullopt;
return key;
}
public:
ConstPubkeyProvider(uint32_t exp_index, const CPubKey& pubkey, bool xonly) : PubkeyProvider(exp_index), m_pubkey(pubkey), m_xonly(xonly) {}
std::optional<CPubKey> GetPubKey(int pos, const SigningProvider&, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
{
KeyOriginInfo info;
CKeyID keyid = m_pubkey.GetID();
std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
out.origins.emplace(keyid, std::make_pair(m_pubkey, info));
out.pubkeys.emplace(keyid, m_pubkey);
return m_pubkey;
}
bool IsRange() const override { return false; }
size_t GetSize() const override { return m_pubkey.size(); }
bool IsBIP32() const override { return false; }
std::string ToString(StringType type) const override { return m_xonly ? HexStr(m_pubkey).substr(2) : HexStr(m_pubkey); }
bool ToPrivateString(const SigningProvider& arg, std::string& ret) const override
{
std::optional<CKey> key = GetPrivKey(arg);
if (!key) {
ret = ToString(StringType::PUBLIC);
return false;
}
ret = EncodeSecret(*key);
return true;
}
bool ToNormalizedString(const SigningProvider& arg, std::string& ret, const DescriptorCache* cache) const override
{
ret = ToString(StringType::PUBLIC);
return true;
}
void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
{
std::optional<CKey> key = GetPrivKey(arg);
if (!key) return;
out.keys.emplace(key->GetPubKey().GetID(), *key);
}
std::optional<CPubKey> GetRootPubKey() const override
{
return m_pubkey;
}
std::optional<CExtPubKey> GetRootExtPubKey() const override
{
return std::nullopt;
}
std::unique_ptr<PubkeyProvider> Clone() const override
{
return std::make_unique<ConstPubkeyProvider>(m_expr_index, m_pubkey, m_xonly);
}
bool CanSelfExpand() const final { return true; }
};
enum class DeriveType {
NON_RANGED,
UNHARDENED_RANGED,
HARDENED_RANGED,
};
/** An object representing a parsed extended public key in a descriptor. */
class BIP32PubkeyProvider final : public PubkeyProvider
{
// Root xpub, path, and final derivation step type being used, if any
CExtPubKey m_root_extkey;
KeyPath m_path;
DeriveType m_derive;
// Whether ' or h is used in harded derivation
bool m_apostrophe;
bool GetExtKey(const SigningProvider& arg, CExtKey& ret) const
{
CKey key;
if (!arg.GetKey(m_root_extkey.pubkey.GetID(), key)) return false;
ret.nDepth = m_root_extkey.nDepth;
std::copy(m_root_extkey.vchFingerprint, m_root_extkey.vchFingerprint + sizeof(ret.vchFingerprint), ret.vchFingerprint);
ret.nChild = m_root_extkey.nChild;
ret.chaincode = m_root_extkey.chaincode;
ret.key = key;
return true;
}
// Derives the last xprv
bool GetDerivedExtKey(const SigningProvider& arg, CExtKey& xprv, CExtKey& last_hardened) const
{
if (!GetExtKey(arg, xprv)) return false;
for (auto entry : m_path) {
if (!xprv.Derive(xprv, entry)) return false;
if (entry >> 31) {
last_hardened = xprv;
}
}
return true;
}
bool IsHardened() const
{
if (m_derive == DeriveType::HARDENED_RANGED) return true;
for (auto entry : m_path) {
if (entry >> 31) return true;
}
return false;
}
public:
BIP32PubkeyProvider(uint32_t exp_index, const CExtPubKey& extkey, KeyPath path, DeriveType derive, bool apostrophe) : PubkeyProvider(exp_index), m_root_extkey(extkey), m_path(std::move(path)), m_derive(derive), m_apostrophe(apostrophe) {}
bool IsRange() const override { return m_derive != DeriveType::NON_RANGED; }
size_t GetSize() const override { return 33; }
bool IsBIP32() const override { return true; }
std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
{
KeyOriginInfo info;
CKeyID keyid = m_root_extkey.pubkey.GetID();
std::copy(keyid.begin(), keyid.begin() + sizeof(info.fingerprint), info.fingerprint);
info.path = m_path;
if (m_derive == DeriveType::UNHARDENED_RANGED) info.path.push_back((uint32_t)pos);
if (m_derive == DeriveType::HARDENED_RANGED) info.path.push_back(((uint32_t)pos) | 0x80000000L);
// Derive keys or fetch them from cache
CExtPubKey final_extkey = m_root_extkey;
CExtPubKey parent_extkey = m_root_extkey;
CExtPubKey last_hardened_extkey;
bool der = true;
if (read_cache) {
if (!read_cache->GetCachedDerivedExtPubKey(m_expr_index, pos, final_extkey)) {
if (m_derive == DeriveType::HARDENED_RANGED) return std::nullopt;
// Try to get the derivation parent
if (!read_cache->GetCachedParentExtPubKey(m_expr_index, parent_extkey)) return std::nullopt;
final_extkey = parent_extkey;
if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
}
} else if (IsHardened()) {
CExtKey xprv;
CExtKey lh_xprv;
if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return std::nullopt;
parent_extkey = xprv.Neuter();
if (m_derive == DeriveType::UNHARDENED_RANGED) der = xprv.Derive(xprv, pos);
if (m_derive == DeriveType::HARDENED_RANGED) der = xprv.Derive(xprv, pos | 0x80000000UL);
final_extkey = xprv.Neuter();
if (lh_xprv.key.IsValid()) {
last_hardened_extkey = lh_xprv.Neuter();
}
} else {
for (auto entry : m_path) {
if (!parent_extkey.Derive(parent_extkey, entry)) return std::nullopt;
}
final_extkey = parent_extkey;
if (m_derive == DeriveType::UNHARDENED_RANGED) der = parent_extkey.Derive(final_extkey, pos);
assert(m_derive != DeriveType::HARDENED_RANGED);
}
if (!der) return std::nullopt;
out.origins.emplace(final_extkey.pubkey.GetID(), std::make_pair(final_extkey.pubkey, info));
out.pubkeys.emplace(final_extkey.pubkey.GetID(), final_extkey.pubkey);
if (write_cache) {
// Only cache parent if there is any unhardened derivation
if (m_derive != DeriveType::HARDENED_RANGED) {
write_cache->CacheParentExtPubKey(m_expr_index, parent_extkey);
// Cache last hardened xpub if we have it
if (last_hardened_extkey.pubkey.IsValid()) {
write_cache->CacheLastHardenedExtPubKey(m_expr_index, last_hardened_extkey);
}
} else if (info.path.size() > 0) {
write_cache->CacheDerivedExtPubKey(m_expr_index, pos, final_extkey);
}
}
return final_extkey.pubkey;
}
std::string ToString(StringType type, bool normalized) const
{
// If StringType==COMPAT, always use the apostrophe to stay compatible with previous versions
const bool use_apostrophe = (!normalized && m_apostrophe) || type == StringType::COMPAT;
std::string ret = EncodeExtPubKey(m_root_extkey) + FormatHDKeypath(m_path, /*apostrophe=*/use_apostrophe);
if (IsRange()) {
ret += "/*";
if (m_derive == DeriveType::HARDENED_RANGED) ret += use_apostrophe ? '\'' : 'h';
}
return ret;
}
std::string ToString(StringType type=StringType::PUBLIC) const override
{
return ToString(type, /*normalized=*/false);
}
bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
{
CExtKey key;
if (!GetExtKey(arg, key)) {
out = ToString(StringType::PUBLIC);
return false;
}
out = EncodeExtKey(key) + FormatHDKeypath(m_path, /*apostrophe=*/m_apostrophe);
if (IsRange()) {
out += "/*";
if (m_derive == DeriveType::HARDENED_RANGED) out += m_apostrophe ? '\'' : 'h';
}
return true;
}
bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override
{
if (m_derive == DeriveType::HARDENED_RANGED) {
out = ToString(StringType::PUBLIC, /*normalized=*/true);
return true;
}
// Step backwards to find the last hardened step in the path
int i = (int)m_path.size() - 1;
for (; i >= 0; --i) {
if (m_path.at(i) >> 31) {
break;
}
}
// Either no derivation or all unhardened derivation
if (i == -1) {
out = ToString();
return true;
}
// Get the path to the last hardened stup
KeyOriginInfo origin;
int k = 0;
for (; k <= i; ++k) {
// Add to the path
origin.path.push_back(m_path.at(k));
}
// Build the remaining path
KeyPath end_path;
for (; k < (int)m_path.size(); ++k) {
end_path.push_back(m_path.at(k));
}
// Get the fingerprint
CKeyID id = m_root_extkey.pubkey.GetID();
std::copy(id.begin(), id.begin() + 4, origin.fingerprint);
CExtPubKey xpub;
CExtKey lh_xprv;
// If we have the cache, just get the parent xpub
if (cache != nullptr) {
cache->GetCachedLastHardenedExtPubKey(m_expr_index, xpub);
}
if (!xpub.pubkey.IsValid()) {
// Cache miss, or nor cache, or need privkey
CExtKey xprv;
if (!GetDerivedExtKey(arg, xprv, lh_xprv)) return false;
xpub = lh_xprv.Neuter();
}
assert(xpub.pubkey.IsValid());
// Build the string
std::string origin_str = HexStr(origin.fingerprint) + FormatHDKeypath(origin.path);
out = "[" + origin_str + "]" + EncodeExtPubKey(xpub) + FormatHDKeypath(end_path);
if (IsRange()) {
out += "/*";
assert(m_derive == DeriveType::UNHARDENED_RANGED);
}
return true;
}
void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
{
CExtKey extkey;
CExtKey dummy;
if (!GetDerivedExtKey(arg, extkey, dummy)) return;
if (m_derive == DeriveType::UNHARDENED_RANGED && !extkey.Derive(extkey, pos)) return;
if (m_derive == DeriveType::HARDENED_RANGED && !extkey.Derive(extkey, pos | 0x80000000UL)) return;
out.keys.emplace(extkey.key.GetPubKey().GetID(), extkey.key);
}
std::optional<CPubKey> GetRootPubKey() const override
{
return std::nullopt;
}
std::optional<CExtPubKey> GetRootExtPubKey() const override
{
return m_root_extkey;
}
std::unique_ptr<PubkeyProvider> Clone() const override
{
return std::make_unique<BIP32PubkeyProvider>(m_expr_index, m_root_extkey, m_path, m_derive, m_apostrophe);
}
bool CanSelfExpand() const override { return !IsHardened(); }
};
/** PubkeyProvider for a musig() expression */
class MuSigPubkeyProvider final : public PubkeyProvider
{
private:
//! PubkeyProvider for the participants
const std::vector<std::unique_ptr<PubkeyProvider>> m_participants;
//! Derivation path
const KeyPath m_path;
//! PubkeyProvider for the aggregate pubkey if it can be cached (i.e. participants are not ranged)
mutable std::unique_ptr<PubkeyProvider> m_aggregate_provider;
mutable std::optional<CPubKey> m_aggregate_pubkey;
const DeriveType m_derive;
const bool m_ranged_participants;
bool IsRangedDerivation() const { return m_derive != DeriveType::NON_RANGED; }
public:
MuSigPubkeyProvider(
uint32_t exp_index,
std::vector<std::unique_ptr<PubkeyProvider>> providers,
KeyPath path,
DeriveType derive
)
: PubkeyProvider(exp_index),
m_participants(std::move(providers)),
m_path(std::move(path)),
m_derive(derive),
m_ranged_participants(std::any_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsRange(); }))
{
if (!Assume(!(m_ranged_participants && IsRangedDerivation()))) {
throw std::runtime_error("musig(): Cannot have both ranged participants and ranged derivation");
}
if (!Assume(m_derive != DeriveType::HARDENED_RANGED)) {
throw std::runtime_error("musig(): Cannot have hardened derivation");
}
}
std::optional<CPubKey> GetPubKey(int pos, const SigningProvider& arg, FlatSigningProvider& out, const DescriptorCache* read_cache = nullptr, DescriptorCache* write_cache = nullptr) const override
{
FlatSigningProvider dummy;
// If the participants are not ranged, we can compute and cache the aggregate pubkey by creating a PubkeyProvider for it
if (!m_aggregate_provider && !m_ranged_participants) {
// Retrieve the pubkeys from the providers
std::vector<CPubKey> pubkeys;
for (const auto& prov : m_participants) {
std::optional<CPubKey> pubkey = prov->GetPubKey(0, arg, dummy, read_cache, write_cache);
if (!pubkey.has_value()) {
return std::nullopt;
}
pubkeys.push_back(pubkey.value());
}
std::sort(pubkeys.begin(), pubkeys.end());
// Aggregate the pubkey
m_aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
if (!Assume(m_aggregate_pubkey.has_value())) return std::nullopt;
// Make our pubkey provider
if (IsRangedDerivation() || !m_path.empty()) {
// Make the synthetic xpub and construct the BIP32PubkeyProvider
CExtPubKey extpub = CreateMuSig2SyntheticXpub(m_aggregate_pubkey.value());
m_aggregate_provider = std::make_unique<BIP32PubkeyProvider>(m_expr_index, extpub, m_path, m_derive, /*apostrophe=*/false);
} else {
m_aggregate_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, m_aggregate_pubkey.value(), /*xonly=*/false);
}
}
// Retrieve all participant pubkeys
std::vector<CPubKey> pubkeys;
for (const auto& prov : m_participants) {
std::optional<CPubKey> pub = prov->GetPubKey(pos, arg, out, read_cache, write_cache);
if (!pub) return std::nullopt;
pubkeys.emplace_back(*pub);
}
std::sort(pubkeys.begin(), pubkeys.end());
CPubKey pubout;
if (m_aggregate_provider) {
// When we have a cached aggregate key, we are either returning it or deriving from it
// Either way, we can passthrough to its GetPubKey
// Use a dummy signing provider as private keys do not exist for the aggregate pubkey
std::optional<CPubKey> pub = m_aggregate_provider->GetPubKey(pos, dummy, out, read_cache, write_cache);
if (!pub) return std::nullopt;
pubout = *pub;
out.aggregate_pubkeys.emplace(m_aggregate_pubkey.value(), pubkeys);
} else {
if (!Assume(m_ranged_participants) || !Assume(m_path.empty())) return std::nullopt;
// Compute aggregate key from derived participants
std::optional<CPubKey> aggregate_pubkey = MuSig2AggregatePubkeys(pubkeys);
if (!aggregate_pubkey) return std::nullopt;
pubout = *aggregate_pubkey;
std::unique_ptr<ConstPubkeyProvider> this_agg_provider = std::make_unique<ConstPubkeyProvider>(m_expr_index, aggregate_pubkey.value(), /*xonly=*/false);
this_agg_provider->GetPubKey(0, dummy, out, read_cache, write_cache);
out.aggregate_pubkeys.emplace(pubout, pubkeys);
}
if (!Assume(pubout.IsValid())) return std::nullopt;
return pubout;
}
bool IsRange() const override { return IsRangedDerivation() || m_ranged_participants; }
// musig() expressions can only be used in tr() contexts which have 32 byte xonly pubkeys
size_t GetSize() const override { return 32; }
std::string ToString(StringType type=StringType::PUBLIC) const override
{
std::string out = "musig(";
for (size_t i = 0; i < m_participants.size(); ++i) {
const auto& pubkey = m_participants.at(i);
if (i) out += ",";
out += pubkey->ToString(type);
}
out += ")";
out += FormatHDKeypath(m_path);
if (IsRangedDerivation()) {
out += "/*";
}
return out;
}
bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
{
bool any_privkeys = false;
out = "musig(";
for (size_t i = 0; i < m_participants.size(); ++i) {
const auto& pubkey = m_participants.at(i);
if (i) out += ",";
std::string tmp;
if (pubkey->ToPrivateString(arg, tmp)) {
any_privkeys = true;
}
out += tmp;
}
out += ")";
out += FormatHDKeypath(m_path);
if (IsRangedDerivation()) {
out += "/*";
}
return any_privkeys;
}
bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache = nullptr) const override
{
out = "musig(";
for (size_t i = 0; i < m_participants.size(); ++i) {
const auto& pubkey = m_participants.at(i);
if (i) out += ",";
std::string tmp;
if (!pubkey->ToNormalizedString(arg, tmp, cache)) {
return false;
}
out += tmp;
}
out += ")";
out += FormatHDKeypath(m_path);
if (IsRangedDerivation()) {
out += "/*";
}
return true;
}
void GetPrivKey(int pos, const SigningProvider& arg, FlatSigningProvider& out) const override
{
// Get the private keys for any participants that we have
// If there is participant derivation, it will be done.
// If there is not, then the participant privkeys will be included directly
for (const auto& prov : m_participants) {
prov->GetPrivKey(pos, arg, out);
}
}
// Get RootPubKey and GetRootExtPubKey are used to return the single pubkey underlying the pubkey provider
// to be presented to the user in gethdkeys. As this is a multisig construction, there is no single underlying
// pubkey hence nothing should be returned.
// While the aggregate pubkey could be returned as the root (ext)pubkey, it is not a pubkey that anyone should
// be using by itself in a descriptor as it is unspendable without knowing its participants.
std::optional<CPubKey> GetRootPubKey() const override
{
return std::nullopt;
}
std::optional<CExtPubKey> GetRootExtPubKey() const override
{
return std::nullopt;
}
std::unique_ptr<PubkeyProvider> Clone() const override
{
std::vector<std::unique_ptr<PubkeyProvider>> providers;
providers.reserve(m_participants.size());
for (const std::unique_ptr<PubkeyProvider>& p : m_participants) {
providers.emplace_back(p->Clone());
}
return std::make_unique<MuSigPubkeyProvider>(m_expr_index, std::move(providers), m_path, m_derive);
}
bool IsBIP32() const override
{
// musig() can only be a BIP 32 key if all participants are bip32 too
return std::all_of(m_participants.begin(), m_participants.end(), [](const auto& pubkey) { return pubkey->IsBIP32(); });
}
size_t GetKeyCount() const override
{
return 1 + m_participants.size();
}
bool CanSelfExpand() const override
{
for (const auto& key : m_participants) {
if (!key->CanSelfExpand()) return false;
}
return true;
}
};
/** Base class for all Descriptor implementations. */
class DescriptorImpl : public Descriptor
{
protected:
//! Public key arguments for this descriptor (size 1 for PK, PKH, WPKH; any size for WSH and Multisig).
const std::vector<std::unique_ptr<PubkeyProvider>> m_pubkey_args;
//! The string name of the descriptor function.
const std::string m_name;
//! Warnings (not including subdescriptors).
std::vector<std::string> m_warnings;
//! The sub-descriptor arguments (empty for everything but SH and WSH).
//! In doc/descriptors.m this is referred to as SCRIPT expressions sh(SCRIPT)
//! and wsh(SCRIPT), and distinct from KEY expressions and ADDR expressions.
//! Subdescriptors can only ever generate a single script.
const std::vector<std::unique_ptr<DescriptorImpl>> m_subdescriptor_args;
//! Return a serialization of anything except pubkey and script arguments, to be prepended to those.
virtual std::string ToStringExtra() const { return ""; }
/** A helper function to construct the scripts for this descriptor.
*
* This function is invoked once by ExpandHelper.
*
* @param pubkeys The evaluations of the m_pubkey_args field.
* @param scripts The evaluations of m_subdescriptor_args (one for each m_subdescriptor_args element).
* @param out A FlatSigningProvider to put scripts or public keys in that are necessary to the solver.
* The origin info of the provided pubkeys is automatically added.
* @return A vector with scriptPubKeys for this descriptor.
*/
virtual std::vector<CScript> MakeScripts(const std::vector<CPubKey>& pubkeys, std::span<const CScript> scripts, FlatSigningProvider& out) const = 0;
public:
DescriptorImpl(std::vector<std::unique_ptr<PubkeyProvider>> pubkeys, const std::string& name) : m_pubkey_args(std::move(pubkeys)), m_name(name), m_subdescriptor_args() {}
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))) {}
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)) {}
enum class StringType
{
PUBLIC,
PRIVATE,
NORMALIZED,
COMPAT, // string calculation that mustn't change over time to stay compatible with previous software versions
};
// NOLINTNEXTLINE(misc-no-recursion)
bool IsSolvable() const override
{
for (const auto& arg : m_subdescriptor_args) {
if (!arg->IsSolvable()) return false;
}
return true;
}
// NOLINTNEXTLINE(misc-no-recursion)
bool HavePrivateKeys(const SigningProvider& arg) const override
{
if (m_pubkey_args.empty() && m_subdescriptor_args.empty()) return false;
for (const auto& sub: m_subdescriptor_args) {
if (!sub->HavePrivateKeys(arg)) return false;
}
FlatSigningProvider tmp_provider;
for (const auto& pubkey : m_pubkey_args) {
tmp_provider.keys.clear();
pubkey->GetPrivKey(0, arg, tmp_provider);
if (tmp_provider.keys.empty()) return false;
}
return true;
}
// NOLINTNEXTLINE(misc-no-recursion)
bool IsRange() const final
{
for (const auto& pubkey : m_pubkey_args) {
if (pubkey->IsRange()) return true;
}
for (const auto& arg : m_subdescriptor_args) {
if (arg->IsRange()) return true;
}
return false;
}
// NOLINTNEXTLINE(misc-no-recursion)
virtual bool ToStringSubScriptHelper(const SigningProvider* arg, std::string& ret, const StringType type, const DescriptorCache* cache = nullptr) const
{
size_t pos = 0;
bool is_private{type == StringType::PRIVATE};
// For private string output, track if at least one key has a private key available.
// Initialize to true for non-private types.
bool any_success{!is_private};
for (const auto& scriptarg : m_subdescriptor_args) {
if (pos++) ret += ",";
std::string tmp;
bool subscript_res{scriptarg->ToStringHelper(arg, tmp, type, cache)};
if (!is_private && !subscript_res) return false;
any_success = any_success || subscript_res;
ret += tmp;
}
return any_success;
}
// NOLINTNEXTLINE(misc-no-recursion)
virtual bool ToStringHelper(const SigningProvider* arg, std::string& out, const StringType type, const DescriptorCache* cache = nullptr) const
{
std::string extra = ToStringExtra();
size_t pos = extra.size() > 0 ? 1 : 0;
std::string ret = m_name + "(" + extra;
bool is_private{type == StringType::PRIVATE};
// For private string output, track if at least one key has a private key available.
// Initialize to true for non-private types.
bool any_success{!is_private};
for (const auto& pubkey : m_pubkey_args) {
if (pos++) ret += ",";
std::string tmp;
switch (type) {
case StringType::NORMALIZED:
if (!pubkey->ToNormalizedString(*arg, tmp, cache)) return false;
break;
case StringType::PRIVATE:
any_success = pubkey->ToPrivateString(*arg, tmp) || any_success;
break;
case StringType::PUBLIC:
tmp = pubkey->ToString();
break;
case StringType::COMPAT:
tmp = pubkey->ToString(PubkeyProvider::StringType::COMPAT);
break;
}
ret += tmp;
}
std::string subscript;
bool subscript_res{ToStringSubScriptHelper(arg, subscript, type, cache)};
if (!is_private && !subscript_res) return false;
any_success = any_success || subscript_res;
if (pos && subscript.size()) ret += ',';
out = std::move(ret) + std::move(subscript) + ")";
return any_success;
}
std::string ToString(bool compat_format) const final
{
std::string ret;
ToStringHelper(nullptr, ret, compat_format ? StringType::COMPAT : StringType::PUBLIC);
return AddChecksum(ret);
}
bool ToPrivateString(const SigningProvider& arg, std::string& out) const override
{
bool has_priv_key{ToStringHelper(&arg, out, StringType::PRIVATE)};
out = AddChecksum(out);
return has_priv_key;
}
bool ToNormalizedString(const SigningProvider& arg, std::string& out, const DescriptorCache* cache) const override final
{
bool ret = ToStringHelper(&arg, out, StringType::NORMALIZED, cache);
out = AddChecksum(out);
return ret;
}
// NOLINTNEXTLINE(misc-no-recursion)
bool ExpandHelper(int pos, const SigningProvider& arg, const DescriptorCache* read_cache, std::vector<CScript>& output_scripts, FlatSigningProvider& out, DescriptorCache* write_cache) const
{
FlatSigningProvider subprovider;
std::vector<CPubKey> pubkeys;
pubkeys.reserve(m_pubkey_args.size());
// Construct temporary data in `pubkeys`, `subscripts`, and `subprovider` to avoid producing output in case of failure.
for (const auto& p : m_pubkey_args) {
std::optional<CPubKey> pubkey = p->GetPubKey(pos, arg, subprovider, read_cache, write_cache);
if (!pubkey) return false;
pubkeys.push_back(pubkey.value());
}
std::vector<CScript> subscripts;
for (const auto& subarg : m_subdescriptor_args) {
std::vector<CScript> outscripts;
if (!subarg->ExpandHelper(pos, arg, read_cache, outscripts, subprovider, write_cache)) return false;
assert(outscripts.size() == 1);
subscripts.emplace_back(std::move(outscripts[0]));
}
out.Merge(std::move(subprovider));
output_scripts = MakeScripts(pubkeys, std::span{subscripts}, out);
return true;
}