-
Notifications
You must be signed in to change notification settings - Fork 47
/
miniscript.h
2181 lines (2041 loc) · 109 KB
/
miniscript.h
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) 2019-2022 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_SCRIPT_MINISCRIPT_H
#define BITCOIN_SCRIPT_MINISCRIPT_H
#include <algorithm>
#include <functional>
#include <numeric>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#include <assert.h>
#include <cstdlib>
#include <policy/policy.h>
#include <primitives/transaction.h>
#include <script/script.h>
#include <span.h>
#include <util/spanparsing.h>
#include <util/strencodings.h>
#include <util/string.h>
#include <util/vector.h>
namespace miniscript {
/** This type encapsulates the miniscript type system properties.
*
* Every miniscript expression is one of 4 basic types, and additionally has
* a number of boolean type properties.
*
* The basic types are:
* - "B" Base:
* - Takes its inputs from the top of the stack.
* - When satisfied, pushes a nonzero value of up to 4 bytes onto the stack.
* - When dissatisfied, pushes a 0 onto the stack.
* - This is used for most expressions, and required for the top level one.
* - For example: older(n) = <n> OP_CHECKSEQUENCEVERIFY.
* - "V" Verify:
* - Takes its inputs from the top of the stack.
* - When satisfied, pushes nothing.
* - Cannot be dissatisfied.
* - This can be obtained by adding an OP_VERIFY to a B, modifying the last opcode
* of a B to its -VERIFY version (only for OP_CHECKSIG, OP_CHECKSIGVERIFY
* and OP_EQUAL), or by combining a V fragment under some conditions.
* - For example vc:pk_k(key) = <key> OP_CHECKSIGVERIFY
* - "K" Key:
* - Takes its inputs from the top of the stack.
* - Becomes a B when followed by OP_CHECKSIG.
* - Always pushes a public key onto the stack, for which a signature is to be
* provided to satisfy the expression.
* - For example pk_h(key) = OP_DUP OP_HASH160 <Hash160(key)> OP_EQUALVERIFY
* - "W" Wrapped:
* - Takes its input from one below the top of the stack.
* - When satisfied, pushes a nonzero value (like B) on top of the stack, or one below.
* - When dissatisfied, pushes 0 op top of the stack or one below.
* - Is always "OP_SWAP [B]" or "OP_TOALTSTACK [B] OP_FROMALTSTACK".
* - For example sc:pk_k(key) = OP_SWAP <key> OP_CHECKSIG
*
* There a type properties that help reasoning about correctness:
* - "z" Zero-arg:
* - Is known to always consume exactly 0 stack elements.
* - For example after(n) = <n> OP_CHECKLOCKTIMEVERIFY
* - "o" One-arg:
* - Is known to always consume exactly 1 stack element.
* - Conflicts with property 'z'
* - For example sha256(hash) = OP_SIZE 32 OP_EQUALVERIFY OP_SHA256 <hash> OP_EQUAL
* - "n" Nonzero:
* - For every way this expression can be satisfied, a satisfaction exists that never needs
* a zero top stack element.
* - Conflicts with property 'z' and with type 'W'.
* - "d" Dissatisfiable:
* - There is an easy way to construct a dissatisfaction for this expression.
* - Conflicts with type 'V'.
* - "u" Unit:
* - In case of satisfaction, an exact 1 is put on the stack (rather than just nonzero).
* - Conflicts with type 'V'.
*
* Additional type properties help reasoning about nonmalleability:
* - "e" Expression:
* - This implies property 'd', but the dissatisfaction is nonmalleable.
* - This generally requires 'e' for all subexpressions which are invoked for that
* dissatifsaction, and property 'f' for the unexecuted subexpressions in that case.
* - Conflicts with type 'V'.
* - "f" Forced:
* - Dissatisfactions (if any) for this expression always involve at least one signature.
* - Is always true for type 'V'.
* - "s" Safe:
* - Satisfactions for this expression always involve at least one signature.
* - "m" Nonmalleable:
* - For every way this expression can be satisfied (which may be none),
* a nonmalleable satisfaction exists.
* - This generally requires 'm' for all subexpressions, and 'e' for all subexpressions
* which are dissatisfied when satisfying the parent.
*
* One type property is an implementation detail:
* - "x" Expensive verify:
* - Expressions with this property have a script whose last opcode is not EQUAL, CHECKSIG, or CHECKMULTISIG.
* - Not having this property means that it can be converted to a V at no cost (by switching to the
* -VERIFY version of the last opcode).
*
* Five more type properties for representing timelock information. Spend paths
* in miniscripts containing conflicting timelocks and heightlocks cannot be spent together.
* This helps users detect if miniscript does not match the semantic behaviour the
* user expects.
* - "g" Whether the branch contains a relative time timelock
* - "h" Whether the branch contains a relative height timelock
* - "i" Whether the branch contains an absolute time timelock
* - "j" Whether the branch contains an absolute height timelock
* - "k"
* - Whether all satisfactions of this expression don't contain a mix of heightlock and timelock
* of the same type.
* - If the miniscript does not have the "k" property, the miniscript template will not match
* the user expectation of the corresponding spending policy.
* For each of these properties the subset rule holds: an expression with properties X, Y, and Z, is also
* valid in places where an X, a Y, a Z, an XY, ... is expected.
*/
class Type {
//! Internal bitmap of properties (see ""_mst operator for details).
uint32_t m_flags;
//! Internal constructor used by the ""_mst operator.
explicit constexpr Type(uint32_t flags) : m_flags(flags) {}
public:
//! The only way to publicly construct a Type is using this literal operator.
friend constexpr Type operator"" _mst(const char* c, size_t l);
//! Compute the type with the union of properties.
constexpr Type operator|(Type x) const { return Type(m_flags | x.m_flags); }
//! Compute the type with the intersection of properties.
constexpr Type operator&(Type x) const { return Type(m_flags & x.m_flags); }
//! Check whether the left hand's properties are superset of the right's (= left is a subtype of right).
constexpr bool operator<<(Type x) const { return (x.m_flags & ~m_flags) == 0; }
//! Comparison operator to enable use in sets/maps (total ordering incompatible with <<).
constexpr bool operator<(Type x) const { return m_flags < x.m_flags; }
//! Equality operator.
constexpr bool operator==(Type x) const { return m_flags == x.m_flags; }
//! The empty type if x is false, itself otherwise.
constexpr Type If(bool x) const { return Type(x ? m_flags : 0); }
};
//! Literal operator to construct Type objects.
inline constexpr Type operator"" _mst(const char* c, size_t l) {
Type typ{0};
for (const char *p = c; p < c + l; p++) {
typ = typ | Type(
*p == 'B' ? 1 << 0 : // Base type
*p == 'V' ? 1 << 1 : // Verify type
*p == 'K' ? 1 << 2 : // Key type
*p == 'W' ? 1 << 3 : // Wrapped type
*p == 'z' ? 1 << 4 : // Zero-arg property
*p == 'o' ? 1 << 5 : // One-arg property
*p == 'n' ? 1 << 6 : // Nonzero arg property
*p == 'd' ? 1 << 7 : // Dissatisfiable property
*p == 'u' ? 1 << 8 : // Unit property
*p == 'e' ? 1 << 9 : // Expression property
*p == 'f' ? 1 << 10 : // Forced property
*p == 's' ? 1 << 11 : // Safe property
*p == 'm' ? 1 << 12 : // Nonmalleable property
*p == 'x' ? 1 << 13 : // Expensive verify
*p == 'g' ? 1 << 14 : // older: contains relative time timelock (csv_time)
*p == 'h' ? 1 << 15 : // older: contains relative height timelock (csv_height)
*p == 'i' ? 1 << 16 : // after: contains time timelock (cltv_time)
*p == 'j' ? 1 << 17 : // after: contains height timelock (cltv_height)
*p == 'k' ? 1 << 18 : // does not contain a combination of height and time locks
(throw std::logic_error("Unknown character in _mst literal"), 0)
);
}
return typ;
}
using Opcode = std::pair<opcodetype, std::vector<unsigned char>>;
template<typename Key> struct Node;
template<typename Key> using NodeRef = std::shared_ptr<const Node<Key>>;
//! Construct a miniscript node as a shared_ptr.
template<typename Key, typename... Args>
NodeRef<Key> MakeNodeRef(Args&&... args) { return std::make_shared<const Node<Key>>(std::forward<Args>(args)...); }
//! The different node types in miniscript.
enum class Fragment {
JUST_0, //!< OP_0
JUST_1, //!< OP_1
PK_K, //!< [key]
PK_H, //!< OP_DUP OP_HASH160 [keyhash] OP_EQUALVERIFY
OLDER, //!< [n] OP_CHECKSEQUENCEVERIFY
AFTER, //!< [n] OP_CHECKLOCKTIMEVERIFY
SHA256, //!< OP_SIZE 32 OP_EQUALVERIFY OP_SHA256 [hash] OP_EQUAL
HASH256, //!< OP_SIZE 32 OP_EQUALVERIFY OP_HASH256 [hash] OP_EQUAL
RIPEMD160, //!< OP_SIZE 32 OP_EQUALVERIFY OP_RIPEMD160 [hash] OP_EQUAL
HASH160, //!< OP_SIZE 32 OP_EQUALVERIFY OP_HASH160 [hash] OP_EQUAL
WRAP_A, //!< OP_TOALTSTACK [X] OP_FROMALTSTACK
WRAP_S, //!< OP_SWAP [X]
WRAP_C, //!< [X] OP_CHECKSIG
WRAP_D, //!< OP_DUP OP_IF [X] OP_ENDIF
WRAP_V, //!< [X] OP_VERIFY (or -VERIFY version of last opcode in X)
WRAP_J, //!< OP_SIZE OP_0NOTEQUAL OP_IF [X] OP_ENDIF
WRAP_N, //!< [X] OP_0NOTEQUAL
AND_V, //!< [X] [Y]
AND_B, //!< [X] [Y] OP_BOOLAND
OR_B, //!< [X] [Y] OP_BOOLOR
OR_C, //!< [X] OP_NOTIF [Y] OP_ENDIF
OR_D, //!< [X] OP_IFDUP OP_NOTIF [Y] OP_ENDIF
OR_I, //!< OP_IF [X] OP_ELSE [Y] OP_ENDIF
ANDOR, //!< [X] OP_NOTIF [Z] OP_ELSE [Y] OP_ENDIF
THRESH, //!< [X1] ([Xn] OP_ADD)* [k] OP_EQUAL
MULTI, //!< [k] [key_n]* [n] OP_CHECKMULTISIG
// AND_N(X,Y) is represented as ANDOR(X,Y,0)
// WRAP_T(X) is represented as AND_V(X,1)
// WRAP_L(X) is represented as OR_I(0,X)
// WRAP_U(X) is represented as OR_I(X,0)
};
enum class Availability {
NO,
YES,
MAYBE,
};
namespace internal {
//! Helper function for Node::CalcType.
Type ComputeType(Fragment fragment, Type x, Type y, Type z, const std::vector<Type>& sub_types, uint32_t k, size_t data_size, size_t n_subs, size_t n_keys);
//! Helper function for Node::CalcScriptLen.
size_t ComputeScriptLen(Fragment fragment, Type sub0typ, size_t subsize, uint32_t k, size_t n_subs, size_t n_keys);
//! A helper sanitizer/checker for the output of CalcType.
Type SanitizeType(Type x);
//! An object representing a sequence of witness stack elements.
struct InputStack {
/** Whether this stack is valid for its intended purpose (satisfaction or dissatisfaction of a Node).
* The MAYBE value is used for size estimation, when keys/preimages may actually be unavailable,
* but may be available at signing time. This makes the InputStack structure and signing logic,
* filled with dummy signatures/preimages usable for witness size estimation.
*/
Availability available = Availability::YES;
//! Whether this stack contains a digital signature.
bool has_sig = false;
//! Whether this stack is malleable (can be turned into an equally valid other stack by a third party).
bool malleable = false;
//! Whether this stack is non-canonical (using a construction known to be unnecessary for satisfaction).
//! Note that this flag does not affect the satisfaction algorithm; it is only used for sanity checking.
bool non_canon = false;
//! Serialized witness size.
size_t size = 0;
//! Data elements.
std::vector<std::vector<unsigned char>> stack;
//! Construct an empty stack (valid).
InputStack() {}
//! Construct a valid single-element stack (with an element up to 75 bytes).
InputStack(std::vector<unsigned char> in) : size(in.size() + 1), stack(Vector(std::move(in))) {}
//! Change availability
InputStack& SetAvailable(Availability avail);
//! Mark this input stack as having a signature.
InputStack& SetWithSig();
//! Mark this input stack as non-canonical (known to not be necessary in non-malleable satisfactions).
InputStack& SetNonCanon();
//! Mark this input stack as malleable.
InputStack& SetMalleable(bool x = true);
//! Concatenate two input stacks.
friend InputStack operator+(InputStack a, InputStack b);
//! Choose between two potential input stacks.
friend InputStack operator|(InputStack a, InputStack b);
};
/** A stack consisting of a single zero-length element (interpreted as 0 by the script interpreter in numeric context). */
static const auto ZERO = InputStack(std::vector<unsigned char>());
/** A stack consisting of a single malleable 32-byte 0x0000...0000 element (for dissatisfying hash challenges). */
static const auto ZERO32 = InputStack(std::vector<unsigned char>(32, 0)).SetMalleable();
/** A stack consisting of a single 0x01 element (interpreted as 1 by the script interpreted in numeric context). */
static const auto ONE = InputStack(Vector((unsigned char)1));
/** The empty stack. */
static const auto EMPTY = InputStack();
/** A stack representing the lack of any (dis)satisfactions. */
static const auto INVALID = InputStack().SetAvailable(Availability::NO);
//! A pair of a satisfaction and a dissatisfaction InputStack.
struct InputResult {
InputStack nsat, sat;
template<typename A, typename B>
InputResult(A&& in_nsat, B&& in_sat) : nsat(std::forward<A>(in_nsat)), sat(std::forward<B>(in_sat)) {}
};
//! Class whose objects represent the maximum of a list of integers.
template<typename I>
struct MaxInt {
const bool valid;
const I value;
MaxInt() : valid(false), value(0) {}
MaxInt(I val) : valid(true), value(val) {}
friend MaxInt<I> operator+(const MaxInt<I>& a, const MaxInt<I>& b) {
if (!a.valid || !b.valid) return {};
return a.value + b.value;
}
friend MaxInt<I> operator|(const MaxInt<I>& a, const MaxInt<I>& b) {
if (!a.valid) return b;
if (!b.valid) return a;
return std::max(a.value, b.value);
}
};
struct Ops {
//! Non-push opcodes.
uint32_t count;
//! Number of keys in possibly executed OP_CHECKMULTISIG(VERIFY)s to satisfy.
MaxInt<uint32_t> sat;
//! Number of keys in possibly executed OP_CHECKMULTISIG(VERIFY)s to dissatisfy.
MaxInt<uint32_t> dsat;
Ops(uint32_t in_count, MaxInt<uint32_t> in_sat, MaxInt<uint32_t> in_dsat) : count(in_count), sat(in_sat), dsat(in_dsat) {};
};
struct StackSize {
//! Maximum stack size to satisfy;
MaxInt<uint32_t> sat;
//! Maximum stack size to dissatisfy;
MaxInt<uint32_t> dsat;
StackSize(MaxInt<uint32_t> in_sat, MaxInt<uint32_t> in_dsat) : sat(in_sat), dsat(in_dsat) {};
};
struct NoDupCheck {};
} // namespace internal
//! A node in a miniscript expression.
template<typename Key>
struct Node {
//! What node type this node is.
const Fragment fragment;
//! The k parameter (time for OLDER/AFTER, threshold for THRESH(_M))
const uint32_t k = 0;
//! The keys used by this expression (only for PK_K/PK_H/MULTI)
const std::vector<Key> keys;
//! The data bytes in this expression (only for HASH160/HASH256/SHA256/RIPEMD10).
const std::vector<unsigned char> data;
//! Subexpressions (for WRAP_*/AND_*/OR_*/ANDOR/THRESH)
const std::vector<NodeRef<Key>> subs;
private:
//! Cached ops counts.
const internal::Ops ops;
//! Cached stack size bounds.
const internal::StackSize ss;
//! Cached expression type (computed by CalcType and fed through SanitizeType).
const Type typ;
//! Cached script length (computed by CalcScriptLen).
const size_t scriptlen;
//! Whether a public key appears more than once in this node. This value is initialized
//! by all constructors except the NoDupCheck ones. The NoDupCheck ones skip the
//! computation, requiring it to be done manually by invoking DuplicateKeyCheck().
//! DuplicateKeyCheck(), or a non-NoDupCheck constructor, will compute has_duplicate_keys
//! for all subnodes as well.
mutable std::optional<bool> has_duplicate_keys;
//! Compute the length of the script for this miniscript (including children).
size_t CalcScriptLen() const {
size_t subsize = 0;
for (const auto& sub : subs) {
subsize += sub->ScriptSize();
}
Type sub0type = subs.size() > 0 ? subs[0]->GetType() : ""_mst;
return internal::ComputeScriptLen(fragment, sub0type, subsize, k, subs.size(), keys.size());
}
/* Apply a recursive algorithm to a Miniscript tree, without actual recursive calls.
*
* The algorithm is defined by two functions: downfn and upfn. Conceptually, the
* result can be thought of as first using downfn to compute a "state" for each node,
* from the root down to the leaves. Then upfn is used to compute a "result" for each
* node, from the leaves back up to the root, which is then returned. In the actual
* implementation, both functions are invoked in an interleaved fashion, performing a
* depth-first traversal of the tree.
*
* In more detail, it is invoked as node.TreeEvalMaybe<Result>(root, downfn, upfn):
* - root is the state of the root node, of type State.
* - downfn is a callable (State&, const Node&, size_t) -> State, which given a
* node, its state, and an index of one of its children, computes the state of that
* child. It can modify the state. Children of a given node will have downfn()
* called in order.
* - upfn is a callable (State&&, const Node&, Span<Result>) -> std::optional<Result>,
* which given a node, its state, and a Span of the results of its children,
* computes the result of the node. If std::nullopt is returned by upfn,
* TreeEvalMaybe() immediately returns std::nullopt.
* The return value of TreeEvalMaybe is the result of the root node.
*
* Result type cannot be bool due to the std::vector<bool> specialization.
*/
template<typename Result, typename State, typename DownFn, typename UpFn>
std::optional<Result> TreeEvalMaybe(State root_state, DownFn downfn, UpFn upfn) const
{
/** Entries of the explicit stack tracked in this algorithm. */
struct StackElem
{
const Node& node; //!< The node being evaluated.
size_t expanded; //!< How many children of this node have been expanded.
State state; //!< The state for that node.
StackElem(const Node& node_, size_t exp_, State&& state_) :
node(node_), expanded(exp_), state(std::move(state_)) {}
};
/* Stack of tree nodes being explored. */
std::vector<StackElem> stack;
/* Results of subtrees so far. Their order and mapping to tree nodes
* is implicitly defined by stack. */
std::vector<Result> results;
stack.emplace_back(*this, 0, std::move(root_state));
/* Here is a demonstration of the algorithm, for an example tree A(B,C(D,E),F).
* State variables are omitted for simplicity.
*
* First: stack=[(A,0)] results=[]
* stack=[(A,1),(B,0)] results=[]
* stack=[(A,1)] results=[B]
* stack=[(A,2),(C,0)] results=[B]
* stack=[(A,2),(C,1),(D,0)] results=[B]
* stack=[(A,2),(C,1)] results=[B,D]
* stack=[(A,2),(C,2),(E,0)] results=[B,D]
* stack=[(A,2),(C,2)] results=[B,D,E]
* stack=[(A,2)] results=[B,C]
* stack=[(A,3),(F,0)] results=[B,C]
* stack=[(A,3)] results=[B,C,F]
* Final: stack=[] results=[A]
*/
while (stack.size()) {
const Node& node = stack.back().node;
if (stack.back().expanded < node.subs.size()) {
/* We encounter a tree node with at least one unexpanded child.
* Expand it. By the time we hit this node again, the result of
* that child (and all earlier children) will be at the end of `results`. */
size_t child_index = stack.back().expanded++;
State child_state = downfn(stack.back().state, node, child_index);
stack.emplace_back(*node.subs[child_index], 0, std::move(child_state));
continue;
}
// Invoke upfn with the last node.subs.size() elements of results as input.
assert(results.size() >= node.subs.size());
std::optional<Result> result{upfn(std::move(stack.back().state), node,
Span<Result>{results}.last(node.subs.size()))};
// If evaluation returns std::nullopt, abort immediately.
if (!result) return {};
// Replace the last node.subs.size() elements of results with the new result.
results.erase(results.end() - node.subs.size(), results.end());
results.push_back(std::move(*result));
stack.pop_back();
}
// The final remaining results element is the root result, return it.
assert(results.size() == 1);
return std::move(results[0]);
}
/** Like TreeEvalMaybe, but without downfn or State type.
* upfn takes (const Node&, Span<Result>) and returns std::optional<Result>. */
template<typename Result, typename UpFn>
std::optional<Result> TreeEvalMaybe(UpFn upfn) const
{
struct DummyState {};
return TreeEvalMaybe<Result>(DummyState{},
[](DummyState, const Node&, size_t) { return DummyState{}; },
[&upfn](DummyState, const Node& node, Span<Result> subs) {
return upfn(node, subs);
}
);
}
/** Like TreeEvalMaybe, but always produces a result. upfn must return Result. */
template<typename Result, typename State, typename DownFn, typename UpFn>
Result TreeEval(State root_state, DownFn&& downfn, UpFn upfn) const
{
// Invoke TreeEvalMaybe with upfn wrapped to return std::optional<Result>, and then
// unconditionally dereference the result (it cannot be std::nullopt).
return std::move(*TreeEvalMaybe<Result>(std::move(root_state),
std::forward<DownFn>(downfn),
[&upfn](State&& state, const Node& node, Span<Result> subs) {
Result res{upfn(std::move(state), node, subs)};
return std::optional<Result>(std::move(res));
}
));
}
/** Like TreeEval, but without downfn or State type.
* upfn takes (const Node&, Span<Result>) and returns Result. */
template<typename Result, typename UpFn>
Result TreeEval(UpFn upfn) const
{
struct DummyState {};
return std::move(*TreeEvalMaybe<Result>(DummyState{},
[](DummyState, const Node&, size_t) { return DummyState{}; },
[&upfn](DummyState, const Node& node, Span<Result> subs) {
Result res{upfn(node, subs)};
return std::optional<Result>(std::move(res));
}
));
}
/** Compare two miniscript subtrees, using a non-recursive algorithm. */
friend int Compare(const Node<Key>& node1, const Node<Key>& node2)
{
std::vector<std::pair<const Node<Key>&, const Node<Key>&>> queue;
queue.emplace_back(node1, node2);
while (!queue.empty()) {
const auto& [a, b] = queue.back();
queue.pop_back();
if (std::tie(a.fragment, a.k, a.keys, a.data) < std::tie(b.fragment, b.k, b.keys, b.data)) return -1;
if (std::tie(b.fragment, b.k, b.keys, b.data) < std::tie(a.fragment, a.k, a.keys, a.data)) return 1;
if (a.subs.size() < b.subs.size()) return -1;
if (b.subs.size() < a.subs.size()) return 1;
size_t n = a.subs.size();
for (size_t i = 0; i < n; ++i) {
queue.emplace_back(*a.subs[n - 1 - i], *b.subs[n - 1 - i]);
}
}
return 0;
}
//! Compute the type for this miniscript.
Type CalcType() const {
using namespace internal;
// THRESH has a variable number of subexpressions
std::vector<Type> sub_types;
if (fragment == Fragment::THRESH) {
for (const auto& sub : subs) sub_types.push_back(sub->GetType());
}
// All other nodes than THRESH can be computed just from the types of the 0-3 subexpressions.
Type x = subs.size() > 0 ? subs[0]->GetType() : ""_mst;
Type y = subs.size() > 1 ? subs[1]->GetType() : ""_mst;
Type z = subs.size() > 2 ? subs[2]->GetType() : ""_mst;
return SanitizeType(ComputeType(fragment, x, y, z, sub_types, k, data.size(), subs.size(), keys.size()));
}
public:
template<typename Ctx>
CScript ToScript(const Ctx& ctx) const
{
// To construct the CScript for a Miniscript object, we use the TreeEval algorithm.
// The State is a boolean: whether or not the node's script expansion is followed
// by an OP_VERIFY (which may need to be combined with the last script opcode).
auto downfn = [](bool verify, const Node& node, size_t index) {
// For WRAP_V, the subexpression is certainly followed by OP_VERIFY.
if (node.fragment == Fragment::WRAP_V) return true;
// The subexpression of WRAP_S, and the last subexpression of AND_V
// inherit the followed-by-OP_VERIFY property from the parent.
if (node.fragment == Fragment::WRAP_S ||
(node.fragment == Fragment::AND_V && index == 1)) return verify;
return false;
};
// The upward function computes for a node, given its followed-by-OP_VERIFY status
// and the CScripts of its child nodes, the CScript of the node.
auto upfn = [&ctx](bool verify, const Node& node, Span<CScript> subs) -> CScript {
switch (node.fragment) {
case Fragment::PK_K: return BuildScript(ctx.ToPKBytes(node.keys[0]));
case Fragment::PK_H: return BuildScript(OP_DUP, OP_HASH160, ctx.ToPKHBytes(node.keys[0]), OP_EQUALVERIFY);
case Fragment::OLDER: return BuildScript(node.k, OP_CHECKSEQUENCEVERIFY);
case Fragment::AFTER: return BuildScript(node.k, OP_CHECKLOCKTIMEVERIFY);
case Fragment::SHA256: return BuildScript(OP_SIZE, 32, OP_EQUALVERIFY, OP_SHA256, node.data, verify ? OP_EQUALVERIFY : OP_EQUAL);
case Fragment::RIPEMD160: return BuildScript(OP_SIZE, 32, OP_EQUALVERIFY, OP_RIPEMD160, node.data, verify ? OP_EQUALVERIFY : OP_EQUAL);
case Fragment::HASH256: return BuildScript(OP_SIZE, 32, OP_EQUALVERIFY, OP_HASH256, node.data, verify ? OP_EQUALVERIFY : OP_EQUAL);
case Fragment::HASH160: return BuildScript(OP_SIZE, 32, OP_EQUALVERIFY, OP_HASH160, node.data, verify ? OP_EQUALVERIFY : OP_EQUAL);
case Fragment::WRAP_A: return BuildScript(OP_TOALTSTACK, subs[0], OP_FROMALTSTACK);
case Fragment::WRAP_S: return BuildScript(OP_SWAP, subs[0]);
case Fragment::WRAP_C: return BuildScript(std::move(subs[0]), verify ? OP_CHECKSIGVERIFY : OP_CHECKSIG);
case Fragment::WRAP_D: return BuildScript(OP_DUP, OP_IF, subs[0], OP_ENDIF);
case Fragment::WRAP_V: {
if (node.subs[0]->GetType() << "x"_mst) {
return BuildScript(std::move(subs[0]), OP_VERIFY);
} else {
return std::move(subs[0]);
}
}
case Fragment::WRAP_J: return BuildScript(OP_SIZE, OP_0NOTEQUAL, OP_IF, subs[0], OP_ENDIF);
case Fragment::WRAP_N: return BuildScript(std::move(subs[0]), OP_0NOTEQUAL);
case Fragment::JUST_1: return BuildScript(OP_1);
case Fragment::JUST_0: return BuildScript(OP_0);
case Fragment::AND_V: return BuildScript(std::move(subs[0]), subs[1]);
case Fragment::AND_B: return BuildScript(std::move(subs[0]), subs[1], OP_BOOLAND);
case Fragment::OR_B: return BuildScript(std::move(subs[0]), subs[1], OP_BOOLOR);
case Fragment::OR_D: return BuildScript(std::move(subs[0]), OP_IFDUP, OP_NOTIF, subs[1], OP_ENDIF);
case Fragment::OR_C: return BuildScript(std::move(subs[0]), OP_NOTIF, subs[1], OP_ENDIF);
case Fragment::OR_I: return BuildScript(OP_IF, subs[0], OP_ELSE, subs[1], OP_ENDIF);
case Fragment::ANDOR: return BuildScript(std::move(subs[0]), OP_NOTIF, subs[2], OP_ELSE, subs[1], OP_ENDIF);
case Fragment::MULTI: {
CScript script = BuildScript(node.k);
for (const auto& key : node.keys) {
script = BuildScript(std::move(script), ctx.ToPKBytes(key));
}
return BuildScript(std::move(script), node.keys.size(), verify ? OP_CHECKMULTISIGVERIFY : OP_CHECKMULTISIG);
}
case Fragment::THRESH: {
CScript script = std::move(subs[0]);
for (size_t i = 1; i < subs.size(); ++i) {
script = BuildScript(std::move(script), subs[i], OP_ADD);
}
return BuildScript(std::move(script), node.k, verify ? OP_EQUALVERIFY : OP_EQUAL);
}
}
assert(false);
};
return TreeEval<CScript>(false, downfn, upfn);
}
template<typename CTx>
std::optional<std::string> ToString(const CTx& ctx) const {
// To construct the std::string representation for a Miniscript object, we use
// the TreeEvalMaybe algorithm. The State is a boolean: whether the parent node is a
// wrapper. If so, non-wrapper expressions must be prefixed with a ":".
auto downfn = [](bool, const Node& node, size_t) {
return (node.fragment == Fragment::WRAP_A || node.fragment == Fragment::WRAP_S ||
node.fragment == Fragment::WRAP_D || node.fragment == Fragment::WRAP_V ||
node.fragment == Fragment::WRAP_J || node.fragment == Fragment::WRAP_N ||
node.fragment == Fragment::WRAP_C ||
(node.fragment == Fragment::AND_V && node.subs[1]->fragment == Fragment::JUST_1) ||
(node.fragment == Fragment::OR_I && node.subs[0]->fragment == Fragment::JUST_0) ||
(node.fragment == Fragment::OR_I && node.subs[1]->fragment == Fragment::JUST_0));
};
// The upward function computes for a node, given whether its parent is a wrapper,
// and the string representations of its child nodes, the string representation of the node.
auto upfn = [&ctx](bool wrapped, const Node& node, Span<std::string> subs) -> std::optional<std::string> {
std::string ret = wrapped ? ":" : "";
switch (node.fragment) {
case Fragment::WRAP_A: return "a" + std::move(subs[0]);
case Fragment::WRAP_S: return "s" + std::move(subs[0]);
case Fragment::WRAP_C:
if (node.subs[0]->fragment == Fragment::PK_K) {
// pk(K) is syntactic sugar for c:pk_k(K)
auto key_str = ctx.ToString(node.subs[0]->keys[0]);
if (!key_str) return {};
return std::move(ret) + "pk(" + std::move(*key_str) + ")";
}
if (node.subs[0]->fragment == Fragment::PK_H) {
// pkh(K) is syntactic sugar for c:pk_h(K)
auto key_str = ctx.ToString(node.subs[0]->keys[0]);
if (!key_str) return {};
return std::move(ret) + "pkh(" + std::move(*key_str) + ")";
}
return "c" + std::move(subs[0]);
case Fragment::WRAP_D: return "d" + std::move(subs[0]);
case Fragment::WRAP_V: return "v" + std::move(subs[0]);
case Fragment::WRAP_J: return "j" + std::move(subs[0]);
case Fragment::WRAP_N: return "n" + std::move(subs[0]);
case Fragment::AND_V:
// t:X is syntactic sugar for and_v(X,1).
if (node.subs[1]->fragment == Fragment::JUST_1) return "t" + std::move(subs[0]);
break;
case Fragment::OR_I:
if (node.subs[0]->fragment == Fragment::JUST_0) return "l" + std::move(subs[1]);
if (node.subs[1]->fragment == Fragment::JUST_0) return "u" + std::move(subs[0]);
break;
default: break;
}
switch (node.fragment) {
case Fragment::PK_K: {
auto key_str = ctx.ToString(node.keys[0]);
if (!key_str) return {};
return std::move(ret) + "pk_k(" + std::move(*key_str) + ")";
}
case Fragment::PK_H: {
auto key_str = ctx.ToString(node.keys[0]);
if (!key_str) return {};
return std::move(ret) + "pk_h(" + std::move(*key_str) + ")";
}
case Fragment::AFTER: return std::move(ret) + "after(" + ::ToString(node.k) + ")";
case Fragment::OLDER: return std::move(ret) + "older(" + ::ToString(node.k) + ")";
case Fragment::HASH256: return std::move(ret) + "hash256(" + HexStr(node.data) + ")";
case Fragment::HASH160: return std::move(ret) + "hash160(" + HexStr(node.data) + ")";
case Fragment::SHA256: return std::move(ret) + "sha256(" + HexStr(node.data) + ")";
case Fragment::RIPEMD160: return std::move(ret) + "ripemd160(" + HexStr(node.data) + ")";
case Fragment::JUST_1: return std::move(ret) + "1";
case Fragment::JUST_0: return std::move(ret) + "0";
case Fragment::AND_V: return std::move(ret) + "and_v(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
case Fragment::AND_B: return std::move(ret) + "and_b(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
case Fragment::OR_B: return std::move(ret) + "or_b(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
case Fragment::OR_D: return std::move(ret) + "or_d(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
case Fragment::OR_C: return std::move(ret) + "or_c(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
case Fragment::OR_I: return std::move(ret) + "or_i(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
case Fragment::ANDOR:
// and_n(X,Y) is syntactic sugar for andor(X,Y,0).
if (node.subs[2]->fragment == Fragment::JUST_0) return std::move(ret) + "and_n(" + std::move(subs[0]) + "," + std::move(subs[1]) + ")";
return std::move(ret) + "andor(" + std::move(subs[0]) + "," + std::move(subs[1]) + "," + std::move(subs[2]) + ")";
case Fragment::MULTI: {
auto str = std::move(ret) + "multi(" + ::ToString(node.k);
for (const auto& key : node.keys) {
auto key_str = ctx.ToString(key);
if (!key_str) return {};
str += "," + std::move(*key_str);
}
return std::move(str) + ")";
}
case Fragment::THRESH: {
auto str = std::move(ret) + "thresh(" + ::ToString(node.k);
for (auto& sub : subs) {
str += "," + std::move(sub);
}
return std::move(str) + ")";
}
default: break;
}
assert(false);
};
return TreeEvalMaybe<std::string>(false, downfn, upfn);
}
private:
internal::Ops CalcOps() const {
switch (fragment) {
case Fragment::JUST_1: return {0, 0, {}};
case Fragment::JUST_0: return {0, {}, 0};
case Fragment::PK_K: return {0, 0, 0};
case Fragment::PK_H: return {3, 0, 0};
case Fragment::OLDER:
case Fragment::AFTER: return {1, 0, {}};
case Fragment::SHA256:
case Fragment::RIPEMD160:
case Fragment::HASH256:
case Fragment::HASH160: return {4, 0, {}};
case Fragment::AND_V: return {subs[0]->ops.count + subs[1]->ops.count, subs[0]->ops.sat + subs[1]->ops.sat, {}};
case Fragment::AND_B: {
const auto count{1 + subs[0]->ops.count + subs[1]->ops.count};
const auto sat{subs[0]->ops.sat + subs[1]->ops.sat};
const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
return {count, sat, dsat};
}
case Fragment::OR_B: {
const auto count{1 + subs[0]->ops.count + subs[1]->ops.count};
const auto sat{(subs[0]->ops.sat + subs[1]->ops.dsat) | (subs[1]->ops.sat + subs[0]->ops.dsat)};
const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
return {count, sat, dsat};
}
case Fragment::OR_D: {
const auto count{3 + subs[0]->ops.count + subs[1]->ops.count};
const auto sat{subs[0]->ops.sat | (subs[1]->ops.sat + subs[0]->ops.dsat)};
const auto dsat{subs[0]->ops.dsat + subs[1]->ops.dsat};
return {count, sat, dsat};
}
case Fragment::OR_C: {
const auto count{2 + subs[0]->ops.count + subs[1]->ops.count};
const auto sat{subs[0]->ops.sat | (subs[1]->ops.sat + subs[0]->ops.dsat)};
return {count, sat, {}};
}
case Fragment::OR_I: {
const auto count{3 + subs[0]->ops.count + subs[1]->ops.count};
const auto sat{subs[0]->ops.sat | subs[1]->ops.sat};
const auto dsat{subs[0]->ops.dsat | subs[1]->ops.dsat};
return {count, sat, dsat};
}
case Fragment::ANDOR: {
const auto count{3 + subs[0]->ops.count + subs[1]->ops.count + subs[2]->ops.count};
const auto sat{(subs[1]->ops.sat + subs[0]->ops.sat) | (subs[0]->ops.dsat + subs[2]->ops.sat)};
const auto dsat{subs[0]->ops.dsat + subs[2]->ops.dsat};
return {count, sat, dsat};
}
case Fragment::MULTI: return {1, (uint32_t)keys.size(), (uint32_t)keys.size()};
case Fragment::WRAP_S:
case Fragment::WRAP_C:
case Fragment::WRAP_N: return {1 + subs[0]->ops.count, subs[0]->ops.sat, subs[0]->ops.dsat};
case Fragment::WRAP_A: return {2 + subs[0]->ops.count, subs[0]->ops.sat, subs[0]->ops.dsat};
case Fragment::WRAP_D: return {3 + subs[0]->ops.count, subs[0]->ops.sat, 0};
case Fragment::WRAP_J: return {4 + subs[0]->ops.count, subs[0]->ops.sat, 0};
case Fragment::WRAP_V: return {subs[0]->ops.count + (subs[0]->GetType() << "x"_mst), subs[0]->ops.sat, {}};
case Fragment::THRESH: {
uint32_t count = 0;
auto sats = Vector(internal::MaxInt<uint32_t>(0));
for (const auto& sub : subs) {
count += sub->ops.count + 1;
auto next_sats = Vector(sats[0] + sub->ops.dsat);
for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + sub->ops.dsat) | (sats[j - 1] + sub->ops.sat));
next_sats.push_back(sats[sats.size() - 1] + sub->ops.sat);
sats = std::move(next_sats);
}
assert(k <= sats.size());
return {count, sats[k], sats[0]};
}
}
assert(false);
}
internal::StackSize CalcStackSize() const {
switch (fragment) {
case Fragment::JUST_0: return {{}, 0};
case Fragment::JUST_1:
case Fragment::OLDER:
case Fragment::AFTER: return {0, {}};
case Fragment::PK_K: return {1, 1};
case Fragment::PK_H: return {2, 2};
case Fragment::SHA256:
case Fragment::RIPEMD160:
case Fragment::HASH256:
case Fragment::HASH160: return {1, {}};
case Fragment::ANDOR: {
const auto sat{(subs[0]->ss.sat + subs[1]->ss.sat) | (subs[0]->ss.dsat + subs[2]->ss.sat)};
const auto dsat{subs[0]->ss.dsat + subs[2]->ss.dsat};
return {sat, dsat};
}
case Fragment::AND_V: return {subs[0]->ss.sat + subs[1]->ss.sat, {}};
case Fragment::AND_B: return {subs[0]->ss.sat + subs[1]->ss.sat, subs[0]->ss.dsat + subs[1]->ss.dsat};
case Fragment::OR_B: {
const auto sat{(subs[0]->ss.dsat + subs[1]->ss.sat) | (subs[0]->ss.sat + subs[1]->ss.dsat)};
const auto dsat{subs[0]->ss.dsat + subs[1]->ss.dsat};
return {sat, dsat};
}
case Fragment::OR_C: return {subs[0]->ss.sat | (subs[0]->ss.dsat + subs[1]->ss.sat), {}};
case Fragment::OR_D: return {subs[0]->ss.sat | (subs[0]->ss.dsat + subs[1]->ss.sat), subs[0]->ss.dsat + subs[1]->ss.dsat};
case Fragment::OR_I: return {(subs[0]->ss.sat + 1) | (subs[1]->ss.sat + 1), (subs[0]->ss.dsat + 1) | (subs[1]->ss.dsat + 1)};
case Fragment::MULTI: return {k + 1, k + 1};
case Fragment::WRAP_A:
case Fragment::WRAP_N:
case Fragment::WRAP_S:
case Fragment::WRAP_C: return subs[0]->ss;
case Fragment::WRAP_D: return {1 + subs[0]->ss.sat, 1};
case Fragment::WRAP_V: return {subs[0]->ss.sat, {}};
case Fragment::WRAP_J: return {subs[0]->ss.sat, 1};
case Fragment::THRESH: {
auto sats = Vector(internal::MaxInt<uint32_t>(0));
for (const auto& sub : subs) {
auto next_sats = Vector(sats[0] + sub->ss.dsat);
for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + sub->ss.dsat) | (sats[j - 1] + sub->ss.sat));
next_sats.push_back(sats[sats.size() - 1] + sub->ss.sat);
sats = std::move(next_sats);
}
assert(k <= sats.size());
return {sats[k], sats[0]};
}
}
assert(false);
}
template<typename Ctx>
internal::InputResult ProduceInput(const Ctx& ctx) const {
using namespace internal;
// Internal function which is invoked for every tree node, constructing satisfaction/dissatisfactions
// given those of its subnodes.
auto helper = [&ctx](const Node& node, Span<InputResult> subres) -> InputResult {
switch (node.fragment) {
case Fragment::PK_K: {
std::vector<unsigned char> sig;
Availability avail = ctx.Sign(node.keys[0], sig);
return {ZERO, InputStack(std::move(sig)).SetWithSig().SetAvailable(avail)};
}
case Fragment::PK_H: {
std::vector<unsigned char> key = ctx.ToPKBytes(node.keys[0]), sig;
Availability avail = ctx.Sign(node.keys[0], sig);
return {ZERO + InputStack(key), (InputStack(std::move(sig)).SetWithSig() + InputStack(key)).SetAvailable(avail)};
}
case Fragment::MULTI: {
// sats[j] represents the best stack containing j valid signatures (out of the first i keys).
// In the loop below, these stacks are built up using a dynamic programming approach.
// sats[0] starts off being {0}, due to the CHECKMULTISIG bug that pops off one element too many.
std::vector<InputStack> sats = Vector(ZERO);
for (size_t i = 0; i < node.keys.size(); ++i) {
std::vector<unsigned char> sig;
Availability avail = ctx.Sign(node.keys[i], sig);
// Compute signature stack for just the i'th key.
auto sat = InputStack(std::move(sig)).SetWithSig().SetAvailable(avail);
// Compute the next sats vector: next_sats[0] is a copy of sats[0] (no signatures). All further
// next_sats[j] are equal to either the existing sats[j], or sats[j-1] plus a signature for the
// current (i'th) key. The very last element needs all signatures filled.
std::vector<InputStack> next_sats;
next_sats.push_back(sats[0]);
for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back(sats[j] | (std::move(sats[j - 1]) + sat));
next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(sat));
// Switch over.
sats = std::move(next_sats);
}
// The dissatisfaction consists of k+1 stack elements all equal to 0.
InputStack nsat = ZERO;
for (size_t i = 0; i < node.k; ++i) nsat = std::move(nsat) + ZERO;
assert(node.k <= sats.size());
return {std::move(nsat), std::move(sats[node.k])};
}
case Fragment::THRESH: {
// sats[k] represents the best stack that satisfies k out of the *last* i subexpressions.
// In the loop below, these stacks are built up using a dynamic programming approach.
// sats[0] starts off empty.
std::vector<InputStack> sats = Vector(EMPTY);
for (size_t i = 0; i < subres.size(); ++i) {
// Introduce an alias for the i'th last satisfaction/dissatisfaction.
auto& res = subres[subres.size() - i - 1];
// Compute the next sats vector: next_sats[0] is sats[0] plus res.nsat (thus containing all dissatisfactions
// so far. next_sats[j] is either sats[j] + res.nsat (reusing j earlier satisfactions) or sats[j-1] + res.sat
// (reusing j-1 earlier satisfactions plus a new one). The very last next_sats[j] is all satisfactions.
std::vector<InputStack> next_sats;
next_sats.push_back(sats[0] + res.nsat);
for (size_t j = 1; j < sats.size(); ++j) next_sats.push_back((sats[j] + res.nsat) | (std::move(sats[j - 1]) + res.sat));
next_sats.push_back(std::move(sats[sats.size() - 1]) + std::move(res.sat));
// Switch over.
sats = std::move(next_sats);
}
// At this point, sats[k].sat is the best satisfaction for the overall thresh() node. The best dissatisfaction
// is computed by gathering all sats[i].nsat for i != k.
InputStack nsat = INVALID;
for (size_t i = 0; i < sats.size(); ++i) {
// i==k is the satisfaction; i==0 is the canonical dissatisfaction;
// the rest are non-canonical (a no-signature dissatisfaction - the i=0
// form - is always available) and malleable (due to overcompleteness).
// Marking the solutions malleable here is not strictly necessary, as they
// should already never be picked in non-malleable solutions due to the
// availability of the i=0 form.
if (i != 0 && i != node.k) sats[i].SetMalleable().SetNonCanon();
// Include all dissatisfactions (even these non-canonical ones) in nsat.
if (i != node.k) nsat = std::move(nsat) | std::move(sats[i]);
}
assert(node.k <= sats.size());
return {std::move(nsat), std::move(sats[node.k])};
}
case Fragment::OLDER: {
return {INVALID, ctx.CheckOlder(node.k) ? EMPTY : INVALID};
}
case Fragment::AFTER: {
return {INVALID, ctx.CheckAfter(node.k) ? EMPTY : INVALID};
}
case Fragment::SHA256: {
std::vector<unsigned char> preimage;
Availability avail = ctx.SatSHA256(node.data, preimage);
return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
}
case Fragment::RIPEMD160: {
std::vector<unsigned char> preimage;
Availability avail = ctx.SatRIPEMD160(node.data, preimage);
return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
}
case Fragment::HASH256: {
std::vector<unsigned char> preimage;
Availability avail = ctx.SatHASH256(node.data, preimage);
return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
}
case Fragment::HASH160: {
std::vector<unsigned char> preimage;
Availability avail = ctx.SatHASH160(node.data, preimage);
return {ZERO32, InputStack(std::move(preimage)).SetAvailable(avail)};
}
case Fragment::AND_V: {
auto& x = subres[0], &y = subres[1];
// As the dissatisfaction here only consist of a single option, it doesn't
// actually need to be listed (it's not required for reasoning about malleability of
// other options), and is never required (no valid miniscript relies on the ability
// to satisfy the type V left subexpression). It's still listed here for
// completeness, as a hypothetical (not currently implemented) satisfier that doesn't
// care about malleability might in some cases prefer it still.
return {(y.nsat + x.sat).SetNonCanon(), y.sat + x.sat};
}
case Fragment::AND_B: {
auto& x = subres[0], &y = subres[1];
// Note that it is not strictly necessary to mark the 2nd and 3rd dissatisfaction here
// as malleable. While they are definitely malleable, they are also non-canonical due
// to the guaranteed existence of a no-signature other dissatisfaction (the 1st)
// option. Because of that, the 2nd and 3rd option will never be chosen, even if they
// weren't marked as malleable.
return {(y.nsat + x.nsat) | (y.sat + x.nsat).SetMalleable().SetNonCanon() | (y.nsat + x.sat).SetMalleable().SetNonCanon(), y.sat + x.sat};
}
case Fragment::OR_B: {
auto& x = subres[0], &z = subres[1];
// The (sat(Z) sat(X)) solution is overcomplete (attacker can change either into dsat).
return {z.nsat + x.nsat, (z.nsat + x.sat) | (z.sat + x.nsat) | (z.sat + x.sat).SetMalleable().SetNonCanon()};
}
case Fragment::OR_C: {
auto& x = subres[0], &z = subres[1];
return {INVALID, std::move(x.sat) | (z.sat + x.nsat)};
}
case Fragment::OR_D: {
auto& x = subres[0], &z = subres[1];
return {z.nsat + x.nsat, std::move(x.sat) | (z.sat + x.nsat)};
}
case Fragment::OR_I: {
auto& x = subres[0], &z = subres[1];
return {(x.nsat + ONE) | (z.nsat + ZERO), (x.sat + ONE) | (z.sat + ZERO)};
}
case Fragment::ANDOR: {
auto& x = subres[0], &y = subres[1], &z = subres[2];
return {(y.nsat + x.sat).SetNonCanon() | (z.nsat + x.nsat), (y.sat + x.sat) | (z.sat + x.nsat)};
}
case Fragment::WRAP_A:
case Fragment::WRAP_S:
case Fragment::WRAP_C:
case Fragment::WRAP_N:
return std::move(subres[0]);
case Fragment::WRAP_D: {
auto &x = subres[0];