forked from rust-bitcoin/rust-miniscript
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcompiler.rs
1712 lines (1563 loc) · 65 KB
/
compiler.rs
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
// SPDX-License-Identifier: CC0-1.0
//! # Policy Compiler
//!
//! Optimizing compiler from concrete policies to Miniscript
//!
use core::{cmp, f64, fmt, hash, mem};
#[cfg(feature = "std")]
use std::error;
use sync::Arc;
use crate::miniscript::context::SigType;
use crate::miniscript::limits::{MAX_PUBKEYS_IN_CHECKSIGADD, MAX_PUBKEYS_PER_MULTISIG};
use crate::miniscript::types::{self, ErrorKind, ExtData, Type};
use crate::miniscript::ScriptContext;
use crate::policy::Concrete;
use crate::prelude::*;
use crate::{policy, Miniscript, MiniscriptKey, Terminal};
type PolicyCache<Pk, Ctx> =
BTreeMap<(Concrete<Pk>, OrdF64, Option<OrdF64>), BTreeMap<CompilationKey, AstElemExt<Pk, Ctx>>>;
/// Ordered f64 for comparison.
#[derive(Copy, Clone, PartialEq, Debug)]
pub(crate) struct OrdF64(pub f64);
impl Eq for OrdF64 {}
// We could derive PartialOrd, but we can't derive Ord, and clippy wants us
// to derive both or neither. Better to be explicit.
impl PartialOrd for OrdF64 {
fn partial_cmp(&self, other: &OrdF64) -> Option<cmp::Ordering> { Some(self.cmp(other)) }
}
impl Ord for OrdF64 {
fn cmp(&self, other: &OrdF64) -> cmp::Ordering {
// will panic if given NaN
self.0.partial_cmp(&other.0).unwrap()
}
}
/// Detailed error type for compiler.
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub enum CompilerError {
/// Compiler has non-safe input policy.
TopLevelNonSafe,
/// Non-Malleable compilation does exists for the given sub-policy.
ImpossibleNonMalleableCompilation,
/// At least one satisfaction path in the optimal Miniscript has exceeded
/// the consensus or standardness limits.
/// There may exist other miniscripts which are under these limits but the
/// compiler currently does not find them.
LimitsExceeded,
///Policy related errors
PolicyError(policy::concrete::PolicyError),
}
impl fmt::Display for CompilerError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
CompilerError::TopLevelNonSafe => {
f.write_str("Top Level script is not safe on some spendpath")
}
CompilerError::ImpossibleNonMalleableCompilation => {
f.write_str("The compiler could not find any non-malleable compilation")
}
CompilerError::LimitsExceeded => f.write_str(
"At least one spending path has exceeded the standardness or consensus limits",
),
CompilerError::PolicyError(ref e) => fmt::Display::fmt(e, f),
}
}
}
#[cfg(feature = "std")]
impl error::Error for CompilerError {
fn cause(&self) -> Option<&dyn error::Error> {
use self::CompilerError::*;
match self {
TopLevelNonSafe | ImpossibleNonMalleableCompilation | LimitsExceeded => None,
PolicyError(e) => Some(e),
}
}
}
#[doc(hidden)]
impl From<policy::concrete::PolicyError> for CompilerError {
fn from(e: policy::concrete::PolicyError) -> CompilerError { CompilerError::PolicyError(e) }
}
/// Hash required for using OrdF64 as key for hashmap
impl hash::Hash for OrdF64 {
fn hash<H: hash::Hasher>(&self, state: &mut H) { self.0.to_bits().hash(state); }
}
/// Compilation key: This represents the state of the best possible compilation
/// of a given policy(implicitly keyed).
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
struct CompilationKey {
/// The type of the compilation result
ty: Type,
/// Whether that result cannot be easily converted into verify form.
/// This is exactly the opposite of has_free_verify in the data-types.
/// This is required in cases where it is important to distinguish between
/// two Compilation of the same-type: one of which is expensive to verify
/// and the other is not.
expensive_verify: bool,
/// The probability of dissatisfaction of the compilation of the policy. Note
/// that all possible compilations of a (sub)policy have the same sat-prob
/// and only differ in dissat_prob.
dissat_prob: Option<OrdF64>,
}
impl CompilationKey {
/// A Compilation key subtype of another if the type if subtype and other
/// attributes are equal
fn is_subtype(self, other: Self) -> bool {
self.ty.is_subtype(other.ty)
&& self.expensive_verify == other.expensive_verify
&& self.dissat_prob == other.dissat_prob
}
/// Helper to create compilation key from components
fn from_type(ty: Type, expensive_verify: bool, dissat_prob: Option<f64>) -> CompilationKey {
CompilationKey { ty, expensive_verify, dissat_prob: dissat_prob.map(OrdF64) }
}
}
#[derive(Copy, Clone, Debug)]
struct CompilerExtData {
/// If this node is the direct child of a disjunction, this field must
/// have the probability of its branch being taken. Otherwise it is ignored.
/// All functions initialize it to `None`.
branch_prob: Option<f64>,
/// The number of bytes needed to satisfy the fragment in segwit format
/// (total length of all witness pushes, plus their own length prefixes)
sat_cost: f64,
/// The number of bytes needed to dissatisfy the fragment in segwit format
/// (total length of all witness pushes, plus their own length prefixes)
/// for fragments that can be dissatisfied without failing the script.
dissat_cost: Option<f64>,
}
impl CompilerExtData {
const TRUE: Self = CompilerExtData { branch_prob: None, sat_cost: 0.0, dissat_cost: None };
const FALSE: Self =
CompilerExtData { branch_prob: None, sat_cost: f64::MAX, dissat_cost: Some(0.0) };
fn pk_k<Ctx: ScriptContext>() -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: match Ctx::sig_type() {
SigType::Ecdsa => 73.0,
SigType::Schnorr => 1.0 /* <var_int> */ + 64.0 /* sig */ + 1.0, /* <sighash_type> */
},
dissat_cost: Some(1.0),
}
}
fn pk_h<Ctx: ScriptContext>() -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: match Ctx::sig_type() {
SigType::Ecdsa => 73.0 + 34.0,
SigType::Schnorr => 66.0 + 33.0,
},
dissat_cost: Some(
1.0 + match Ctx::sig_type() {
SigType::Ecdsa => 34.0,
SigType::Schnorr => 33.0,
},
),
}
}
fn multi(k: usize, _n: usize) -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: 1.0 + 73.0 * k as f64,
dissat_cost: Some(1.0 * (k + 1) as f64),
}
}
fn multi_a(k: usize, n: usize) -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: 66.0 * k as f64 + (n - k) as f64,
dissat_cost: Some(n as f64), /* <w_n> ... <w_1> := 0x00 ... 0x00 (n times) */
}
}
fn hash() -> Self {
CompilerExtData { branch_prob: None, sat_cost: 33.0, dissat_cost: Some(33.0) }
}
fn time() -> Self { CompilerExtData { branch_prob: None, sat_cost: 0.0, dissat_cost: None } }
fn cast_alt(self) -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: self.sat_cost,
dissat_cost: self.dissat_cost,
}
}
fn cast_swap(self) -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: self.sat_cost,
dissat_cost: self.dissat_cost,
}
}
fn cast_check(self) -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: self.sat_cost,
dissat_cost: self.dissat_cost,
}
}
fn cast_dupif(self) -> Self {
CompilerExtData { branch_prob: None, sat_cost: 2.0 + self.sat_cost, dissat_cost: Some(1.0) }
}
fn cast_verify(self) -> Self {
CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: None }
}
fn cast_nonzero(self) -> Self {
CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: Some(1.0) }
}
fn cast_zeronotequal(self) -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: self.sat_cost,
dissat_cost: self.dissat_cost,
}
}
fn cast_true(self) -> Self {
CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: None }
}
fn cast_unlikely(self) -> Self {
CompilerExtData { branch_prob: None, sat_cost: 2.0 + self.sat_cost, dissat_cost: Some(1.0) }
}
fn cast_likely(self) -> Self {
CompilerExtData { branch_prob: None, sat_cost: 1.0 + self.sat_cost, dissat_cost: Some(2.0) }
}
fn and_b(left: Self, right: Self) -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: left.sat_cost + right.sat_cost,
dissat_cost: match (left.dissat_cost, right.dissat_cost) {
(Some(l), Some(r)) => Some(l + r),
_ => None,
},
}
}
fn and_v(left: Self, right: Self) -> Self {
CompilerExtData {
branch_prob: None,
sat_cost: left.sat_cost + right.sat_cost,
dissat_cost: None,
}
}
fn or_b(l: Self, r: Self) -> Self {
let lprob = l
.branch_prob
.expect("BUG: left branch prob must be set for disjunctions");
let rprob = r
.branch_prob
.expect("BUG: right branch prob must be set for disjunctions");
CompilerExtData {
branch_prob: None,
sat_cost: lprob * (l.sat_cost + r.dissat_cost.unwrap())
+ rprob * (r.sat_cost + l.dissat_cost.unwrap()),
dissat_cost: Some(l.dissat_cost.unwrap() + r.dissat_cost.unwrap()),
}
}
fn or_d(l: Self, r: Self) -> Self {
let lprob = l
.branch_prob
.expect("BUG: left branch prob must be set for disjunctions");
let rprob = r
.branch_prob
.expect("BUG: right branch prob must be set for disjunctions");
CompilerExtData {
branch_prob: None,
sat_cost: lprob * l.sat_cost + rprob * (r.sat_cost + l.dissat_cost.unwrap()),
dissat_cost: r.dissat_cost.map(|rd| l.dissat_cost.unwrap() + rd),
}
}
fn or_c(l: Self, r: Self) -> Self {
let lprob = l
.branch_prob
.expect("BUG: left branch prob must be set for disjunctions");
let rprob = r
.branch_prob
.expect("BUG: right branch prob must be set for disjunctions");
CompilerExtData {
branch_prob: None,
sat_cost: lprob * l.sat_cost + rprob * (r.sat_cost + l.dissat_cost.unwrap()),
dissat_cost: None,
}
}
#[allow(clippy::manual_map)] // Complex if/let is better as is.
fn or_i(l: Self, r: Self) -> Self {
let lprob = l
.branch_prob
.expect("BUG: left branch prob must be set for disjunctions");
let rprob = r
.branch_prob
.expect("BUG: right branch prob must be set for disjunctions");
CompilerExtData {
branch_prob: None,
sat_cost: lprob * (2.0 + l.sat_cost) + rprob * (1.0 + r.sat_cost),
dissat_cost: if let (Some(ldis), Some(rdis)) = (l.dissat_cost, r.dissat_cost) {
if (2.0 + ldis) > (1.0 + rdis) {
Some(1.0 + rdis)
} else {
Some(2.0 + ldis)
}
} else if let Some(ldis) = l.dissat_cost {
Some(2.0 + ldis)
} else if let Some(rdis) = r.dissat_cost {
Some(1.0 + rdis)
} else {
None
},
}
}
fn and_or(a: Self, b: Self, c: Self) -> Result<Self, types::ErrorKind> {
if a.dissat_cost.is_none() {
return Err(ErrorKind::LeftNotDissatisfiable);
}
let aprob = a.branch_prob.expect("andor, a prob must be set");
let bprob = b.branch_prob.expect("andor, b prob must be set");
let cprob = c.branch_prob.expect("andor, c prob must be set");
let adis = a
.dissat_cost
.expect("BUG: and_or first arg(a) must be dissatisfiable");
debug_assert_eq!(aprob, bprob); //A and B must have same branch prob.
Ok(CompilerExtData {
branch_prob: None,
sat_cost: aprob * (a.sat_cost + b.sat_cost) + cprob * (adis + c.sat_cost),
dissat_cost: c.dissat_cost.map(|cdis| adis + cdis),
})
}
fn threshold<S>(k: usize, n: usize, mut sub_ck: S) -> Result<Self, types::ErrorKind>
where
S: FnMut(usize) -> Result<Self, types::ErrorKind>,
{
let k_over_n = k as f64 / n as f64;
let mut sat_cost = 0.0;
let mut dissat_cost = 0.0;
for i in 0..n {
let sub = sub_ck(i)?;
sat_cost += sub.sat_cost;
dissat_cost += sub.dissat_cost.unwrap();
}
Ok(CompilerExtData {
branch_prob: None,
sat_cost: sat_cost * k_over_n + dissat_cost * (1.0 - k_over_n),
dissat_cost: Some(dissat_cost),
})
}
}
impl CompilerExtData {
/// Compute the type of a fragment, given a function to look up
/// the types of its children.
fn type_check_with_child<Pk, Ctx, C>(
fragment: &Terminal<Pk, Ctx>,
child: C,
) -> Result<Self, types::Error>
where
C: Fn(usize) -> Self,
Pk: MiniscriptKey,
Ctx: ScriptContext,
{
let get_child = |_sub, n| Ok(child(n));
Self::type_check_common(fragment, get_child)
}
/// Compute the type of a fragment.
fn type_check<Pk, Ctx>(fragment: &Terminal<Pk, Ctx>) -> Result<Self, types::Error>
where
Pk: MiniscriptKey,
Ctx: ScriptContext,
{
let check_child = |sub, _n| Self::type_check(sub);
Self::type_check_common(fragment, check_child)
}
/// Compute the type of a fragment, given a function to look up
/// the types of its children, if available and relevant for the
/// given fragment
fn type_check_common<'a, Pk, Ctx, C>(
fragment: &'a Terminal<Pk, Ctx>,
get_child: C,
) -> Result<Self, types::Error>
where
C: Fn(&'a Terminal<Pk, Ctx>, usize) -> Result<Self, types::Error>,
Pk: MiniscriptKey,
Ctx: ScriptContext,
{
match *fragment {
Terminal::True => Ok(Self::TRUE),
Terminal::False => Ok(Self::FALSE),
Terminal::PkK(..) => Ok(Self::pk_k::<Ctx>()),
Terminal::PkH(..) | Terminal::RawPkH(..) => Ok(Self::pk_h::<Ctx>()),
Terminal::Multi(k, ref pks) | Terminal::MultiA(k, ref pks) => {
if k == 0 {
return Err(types::Error {
fragment_string: fragment.to_string(),
error: types::ErrorKind::ZeroThreshold,
});
}
if k > pks.len() {
return Err(types::Error {
fragment_string: fragment.to_string(),
error: types::ErrorKind::OverThreshold(k, pks.len()),
});
}
match *fragment {
Terminal::Multi(..) => Ok(Self::multi(k, pks.len())),
Terminal::MultiA(..) => Ok(Self::multi_a(k, pks.len())),
_ => unreachable!(),
}
}
Terminal::After(_) => Ok(Self::time()),
Terminal::Older(_) => Ok(Self::time()),
Terminal::Sha256(..) => Ok(Self::hash()),
Terminal::Hash256(..) => Ok(Self::hash()),
Terminal::Ripemd160(..) => Ok(Self::hash()),
Terminal::Hash160(..) => Ok(Self::hash()),
Terminal::Alt(ref sub) => Ok(Self::cast_alt(get_child(&sub.node, 0)?)),
Terminal::Swap(ref sub) => Ok(Self::cast_swap(get_child(&sub.node, 0)?)),
Terminal::Check(ref sub) => Ok(Self::cast_check(get_child(&sub.node, 0)?)),
Terminal::DupIf(ref sub) => Ok(Self::cast_dupif(get_child(&sub.node, 0)?)),
Terminal::Verify(ref sub) => Ok(Self::cast_verify(get_child(&sub.node, 0)?)),
Terminal::NonZero(ref sub) => Ok(Self::cast_nonzero(get_child(&sub.node, 0)?)),
Terminal::ZeroNotEqual(ref sub) => {
Ok(Self::cast_zeronotequal(get_child(&sub.node, 0)?))
}
Terminal::AndB(ref l, ref r) => {
let ltype = get_child(&l.node, 0)?;
let rtype = get_child(&r.node, 1)?;
Ok(Self::and_b(ltype, rtype))
}
Terminal::AndV(ref l, ref r) => {
let ltype = get_child(&l.node, 0)?;
let rtype = get_child(&r.node, 1)?;
Ok(Self::and_v(ltype, rtype))
}
Terminal::OrB(ref l, ref r) => {
let ltype = get_child(&l.node, 0)?;
let rtype = get_child(&r.node, 1)?;
Ok(Self::or_b(ltype, rtype))
}
Terminal::OrD(ref l, ref r) => {
let ltype = get_child(&l.node, 0)?;
let rtype = get_child(&r.node, 1)?;
Ok(Self::or_d(ltype, rtype))
}
Terminal::OrC(ref l, ref r) => {
let ltype = get_child(&l.node, 0)?;
let rtype = get_child(&r.node, 1)?;
Ok(Self::or_c(ltype, rtype))
}
Terminal::OrI(ref l, ref r) => {
let ltype = get_child(&l.node, 0)?;
let rtype = get_child(&r.node, 1)?;
Ok(Self::or_i(ltype, rtype))
}
Terminal::AndOr(ref a, ref b, ref c) => {
let atype = get_child(&a.node, 0)?;
let btype = get_child(&b.node, 1)?;
let ctype = get_child(&c.node, 2)?;
Self::and_or(atype, btype, ctype).map_err(|kind| types::Error {
fragment_string: fragment.to_string(),
error: kind,
})
}
Terminal::Thresh(k, ref subs) => {
if k == 0 {
return Err(types::Error {
fragment_string: fragment.to_string(),
error: types::ErrorKind::ZeroThreshold,
});
}
if k > subs.len() {
return Err(types::Error {
fragment_string: fragment.to_string(),
error: types::ErrorKind::OverThreshold(k, subs.len()),
});
}
let mut last_err_frag = None;
Self::threshold(k, subs.len(), |n| match get_child(&subs[n].node, n) {
Ok(x) => Ok(x),
Err(e) => {
last_err_frag = Some(e.fragment_string);
Err(e.error)
}
})
.map_err(|kind| types::Error { fragment_string: fragment.to_string(), error: kind })
}
}
}
}
/// Miniscript AST fragment with additional data needed by the compiler
#[derive(Clone, Debug)]
struct AstElemExt<Pk: MiniscriptKey, Ctx: ScriptContext> {
/// The actual Miniscript fragment with type information
ms: Arc<Miniscript<Pk, Ctx>>,
/// Its "type" in terms of compiler data
comp_ext_data: CompilerExtData,
}
impl<Pk: MiniscriptKey, Ctx: ScriptContext> AstElemExt<Pk, Ctx> {
/// Compute a 1-dimensional cost, given a probability of satisfaction
/// and a probability of dissatisfaction; if `dissat_prob` is `None`
/// then it is assumed that dissatisfaction never occurs
fn cost_1d(&self, sat_prob: f64, dissat_prob: Option<f64>) -> f64 {
self.ms.ext.pk_cost as f64
+ self.comp_ext_data.sat_cost * sat_prob
+ match (dissat_prob, self.comp_ext_data.dissat_cost) {
(Some(prob), Some(cost)) => prob * cost,
(Some(_), None) => f64::INFINITY,
(None, Some(_)) => 0.0,
(None, None) => 0.0,
}
}
}
impl<Pk: MiniscriptKey, Ctx: ScriptContext> AstElemExt<Pk, Ctx> {
fn terminal(ast: Terminal<Pk, Ctx>) -> AstElemExt<Pk, Ctx> {
AstElemExt {
comp_ext_data: CompilerExtData::type_check(&ast).unwrap(),
ms: Arc::new(Miniscript::from_ast(ast).expect("Terminal creation must always succeed")),
}
}
fn binary(
ast: Terminal<Pk, Ctx>,
l: &AstElemExt<Pk, Ctx>,
r: &AstElemExt<Pk, Ctx>,
) -> Result<AstElemExt<Pk, Ctx>, types::Error> {
let lookup_ext = |n| match n {
0 => l.comp_ext_data,
1 => r.comp_ext_data,
_ => unreachable!(),
};
//Types and ExtData are already cached and stored in children. So, we can
//type_check without cache. For Compiler extra data, we supply a cache.
let ty = types::Type::type_check(&ast)?;
let ext = types::ExtData::type_check(&ast)?;
let comp_ext_data = CompilerExtData::type_check_with_child(&ast, lookup_ext)?;
Ok(AstElemExt {
ms: Arc::new(Miniscript::from_components_unchecked(ast, ty, ext)),
comp_ext_data,
})
}
fn ternary(
ast: Terminal<Pk, Ctx>,
a: &AstElemExt<Pk, Ctx>,
b: &AstElemExt<Pk, Ctx>,
c: &AstElemExt<Pk, Ctx>,
) -> Result<AstElemExt<Pk, Ctx>, types::Error> {
let lookup_ext = |n| match n {
0 => a.comp_ext_data,
1 => b.comp_ext_data,
2 => c.comp_ext_data,
_ => unreachable!(),
};
//Types and ExtData are already cached and stored in children. So, we can
//type_check without cache. For Compiler extra data, we supply a cache.
let ty = types::Type::type_check(&ast)?;
let ext = types::ExtData::type_check(&ast)?;
let comp_ext_data = CompilerExtData::type_check_with_child(&ast, lookup_ext)?;
Ok(AstElemExt {
ms: Arc::new(Miniscript::from_components_unchecked(ast, ty, ext)),
comp_ext_data,
})
}
}
/// Different types of casts possible for each node.
#[allow(clippy::type_complexity)]
#[derive(Copy, Clone)]
struct Cast<Pk: MiniscriptKey, Ctx: ScriptContext> {
node: fn(Arc<Miniscript<Pk, Ctx>>) -> Terminal<Pk, Ctx>,
ast_type: fn(types::Type) -> Result<types::Type, ErrorKind>,
ext_data: fn(types::ExtData) -> types::ExtData,
comp_ext_data: fn(CompilerExtData) -> CompilerExtData,
}
impl<Pk: MiniscriptKey, Ctx: ScriptContext> Cast<Pk, Ctx> {
fn cast(&self, ast: &AstElemExt<Pk, Ctx>) -> Result<AstElemExt<Pk, Ctx>, ErrorKind> {
Ok(AstElemExt {
ms: Arc::new(Miniscript::from_components_unchecked(
(self.node)(Arc::clone(&ast.ms)),
(self.ast_type)(ast.ms.ty)?,
(self.ext_data)(ast.ms.ext),
)),
comp_ext_data: (self.comp_ext_data)(ast.comp_ext_data),
})
}
}
fn all_casts<Pk: MiniscriptKey, Ctx: ScriptContext>() -> [Cast<Pk, Ctx>; 10] {
[
Cast {
ext_data: types::ExtData::cast_check,
node: Terminal::Check,
ast_type: types::Type::cast_check,
comp_ext_data: CompilerExtData::cast_check,
},
Cast {
ext_data: types::ExtData::cast_dupif,
node: Terminal::DupIf,
ast_type: types::Type::cast_dupif,
comp_ext_data: CompilerExtData::cast_dupif,
},
Cast {
ext_data: types::ExtData::cast_likely,
node: |ms| Terminal::OrI(Arc::new(Miniscript::FALSE), ms),
ast_type: types::Type::cast_likely,
comp_ext_data: CompilerExtData::cast_likely,
},
Cast {
ext_data: types::ExtData::cast_unlikely,
node: |ms| Terminal::OrI(ms, Arc::new(Miniscript::FALSE)),
ast_type: types::Type::cast_unlikely,
comp_ext_data: CompilerExtData::cast_unlikely,
},
Cast {
ext_data: types::ExtData::cast_verify,
node: Terminal::Verify,
ast_type: types::Type::cast_verify,
comp_ext_data: CompilerExtData::cast_verify,
},
Cast {
ext_data: types::ExtData::cast_nonzero,
node: Terminal::NonZero,
ast_type: types::Type::cast_nonzero,
comp_ext_data: CompilerExtData::cast_nonzero,
},
Cast {
ext_data: types::ExtData::cast_true,
node: |ms| Terminal::AndV(ms, Arc::new(Miniscript::TRUE)),
ast_type: types::Type::cast_true,
comp_ext_data: CompilerExtData::cast_true,
},
Cast {
ext_data: types::ExtData::cast_swap,
node: Terminal::Swap,
ast_type: types::Type::cast_swap,
comp_ext_data: CompilerExtData::cast_swap,
},
Cast {
node: Terminal::Alt,
ast_type: types::Type::cast_alt,
ext_data: types::ExtData::cast_alt,
comp_ext_data: CompilerExtData::cast_alt,
},
Cast {
ext_data: types::ExtData::cast_zeronotequal,
node: Terminal::ZeroNotEqual,
ast_type: types::Type::cast_zeronotequal,
comp_ext_data: CompilerExtData::cast_zeronotequal,
},
]
}
/// Insert an element into the global map and return whether it got inserted
/// If there is any element which is already better than current element
/// (by subtyping rules), then don't process the element and return `False`.
/// Otherwise, if the element got inserted into the map, return `True` to inform
/// the caller that the cast closure of this element must also be inserted into
/// the map.
/// In general, we maintain the invariant that if anything is inserted into the
/// map, it's cast closure must also be considered for best compilations.
fn insert_elem<Pk: MiniscriptKey, Ctx: ScriptContext>(
map: &mut BTreeMap<CompilationKey, AstElemExt<Pk, Ctx>>,
elem: AstElemExt<Pk, Ctx>,
sat_prob: f64,
dissat_prob: Option<f64>,
) -> bool {
// return malleable types directly. If a elem is malleable under current context,
// all the casts to it are also going to be malleable
if !elem.ms.ty.mall.non_malleable && Ctx::check_terminal_non_malleable(&elem.ms.node).is_ok() {
return false;
}
if Ctx::check_local_validity(&elem.ms).is_err() {
return false;
}
let elem_cost = elem.cost_1d(sat_prob, dissat_prob);
let elem_key = CompilationKey::from_type(elem.ms.ty, elem.ms.ext.has_free_verify, dissat_prob);
// Check whether the new element is worse than any existing element. If there
// is an element which is a subtype of the current element and has better
// cost, don't consider this element.
let is_worse = map
.iter()
.map(|(existing_key, existing_elem)| {
let existing_elem_cost = existing_elem.cost_1d(sat_prob, dissat_prob);
existing_key.is_subtype(elem_key) && existing_elem_cost <= elem_cost
})
.any(|x| x);
if !is_worse {
// If the element is not worse any element in the map, remove elements
// whose subtype is the current element and have worse cost.
*map = mem::take(map)
.into_iter()
.filter(|(existing_key, existing_elem)| {
let existing_elem_cost = existing_elem.cost_1d(sat_prob, dissat_prob);
!(elem_key.is_subtype(*existing_key) && existing_elem_cost >= elem_cost)
})
.collect();
map.insert(elem_key, elem);
}
!is_worse
}
/// Insert the cast-closure of in the `astelem_ext`. The cast_stack
/// has all the elements whose closure is yet to inserted in the map.
/// A cast-closure refers to trying all possible casts on a particular element
/// if they are better than the current elements in the global map.
///
/// At the start and end of this function, we maintain that the invariant that
/// all map is smallest possible closure of all compilations of a policy with
/// given sat and dissat probabilities.
fn insert_elem_closure<Pk: MiniscriptKey, Ctx: ScriptContext>(
map: &mut BTreeMap<CompilationKey, AstElemExt<Pk, Ctx>>,
astelem_ext: AstElemExt<Pk, Ctx>,
sat_prob: f64,
dissat_prob: Option<f64>,
) {
let mut cast_stack: VecDeque<AstElemExt<Pk, Ctx>> = VecDeque::new();
if insert_elem(map, astelem_ext.clone(), sat_prob, dissat_prob) {
cast_stack.push_back(astelem_ext);
}
let casts: [Cast<Pk, Ctx>; 10] = all_casts::<Pk, Ctx>();
while !cast_stack.is_empty() {
let current = cast_stack.pop_front().unwrap();
for c in &casts {
if let Ok(new_ext) = c.cast(¤t) {
if insert_elem(map, new_ext.clone(), sat_prob, dissat_prob) {
cast_stack.push_back(new_ext);
}
}
}
}
}
/// Insert the best wrapped compilations of a particular Terminal. If the
/// dissat probability is None, then we directly get the closure of the element
/// Otherwise, some wrappers require the compilation of the policy with dissat
/// `None` because they convert it into a dissat around it.
/// For example, `l` wrapper should it argument it dissat. `None` because it can
/// always dissatisfy the policy outside and it find the better inner compilation
/// given that it may be not be necessary to dissatisfy. For these elements, we
/// apply the wrappers around the element once and bring them into the same
/// dissat probability map and get their closure.
fn insert_best_wrapped<Pk: MiniscriptKey, Ctx: ScriptContext>(
policy_cache: &mut PolicyCache<Pk, Ctx>,
policy: &Concrete<Pk>,
map: &mut BTreeMap<CompilationKey, AstElemExt<Pk, Ctx>>,
data: AstElemExt<Pk, Ctx>,
sat_prob: f64,
dissat_prob: Option<f64>,
) -> Result<(), CompilerError> {
insert_elem_closure(map, data, sat_prob, dissat_prob);
if dissat_prob.is_some() {
let casts: [Cast<Pk, Ctx>; 10] = all_casts::<Pk, Ctx>();
for c in &casts {
for x in best_compilations(policy_cache, policy, sat_prob, None)?.values() {
if let Ok(new_ext) = c.cast(x) {
insert_elem_closure(map, new_ext, sat_prob, dissat_prob);
}
}
}
}
Ok(())
}
/// Get the best compilations of a policy with a given sat and dissat
/// probabilities. This functions caches the results into a global policy cache.
fn best_compilations<Pk, Ctx>(
policy_cache: &mut PolicyCache<Pk, Ctx>,
policy: &Concrete<Pk>,
sat_prob: f64,
dissat_prob: Option<f64>,
) -> Result<BTreeMap<CompilationKey, AstElemExt<Pk, Ctx>>, CompilerError>
where
Pk: MiniscriptKey,
Ctx: ScriptContext,
{
//Check the cache for hits
let ord_sat_prob = OrdF64(sat_prob);
let ord_dissat_prob = dissat_prob.map(OrdF64);
if let Some(ret) = policy_cache.get(&(policy.clone(), ord_sat_prob, ord_dissat_prob)) {
return Ok(ret.clone());
}
let mut ret = BTreeMap::new();
//handy macro for good looking code
macro_rules! insert_wrap {
($x:expr) => {
insert_best_wrapped(policy_cache, policy, &mut ret, $x, sat_prob, dissat_prob)?
};
}
macro_rules! compile_binary {
($l:expr, $r:expr, $w: expr, $f: expr) => {
compile_binary(policy_cache, policy, &mut ret, $l, $r, $w, sat_prob, dissat_prob, $f)?
};
}
macro_rules! compile_tern {
($a:expr, $b:expr, $c: expr, $w: expr) => {
compile_tern(policy_cache, policy, &mut ret, $a, $b, $c, $w, sat_prob, dissat_prob)?
};
}
match *policy {
Concrete::Unsatisfiable => {
insert_wrap!(AstElemExt::terminal(Terminal::False));
}
Concrete::Trivial => {
insert_wrap!(AstElemExt::terminal(Terminal::True));
}
Concrete::Key(ref pk) => {
insert_wrap!(AstElemExt::terminal(Terminal::PkH(pk.clone())));
insert_wrap!(AstElemExt::terminal(Terminal::PkK(pk.clone())));
}
Concrete::After(n) => insert_wrap!(AstElemExt::terminal(Terminal::After(n))),
Concrete::Older(n) => insert_wrap!(AstElemExt::terminal(Terminal::Older(n))),
Concrete::Sha256(ref hash) => {
insert_wrap!(AstElemExt::terminal(Terminal::Sha256(hash.clone())))
}
// Satisfaction-cost + script-cost
Concrete::Hash256(ref hash) => {
insert_wrap!(AstElemExt::terminal(Terminal::Hash256(hash.clone())))
}
Concrete::Ripemd160(ref hash) => {
insert_wrap!(AstElemExt::terminal(Terminal::Ripemd160(hash.clone())))
}
Concrete::Hash160(ref hash) => {
insert_wrap!(AstElemExt::terminal(Terminal::Hash160(hash.clone())))
}
Concrete::And(ref subs) => {
assert_eq!(subs.len(), 2, "and takes 2 args");
let mut left =
best_compilations(policy_cache, subs[0].as_ref(), sat_prob, dissat_prob)?;
let mut right =
best_compilations(policy_cache, subs[1].as_ref(), sat_prob, dissat_prob)?;
let mut q_zero_right =
best_compilations(policy_cache, subs[1].as_ref(), sat_prob, None)?;
let mut q_zero_left =
best_compilations(policy_cache, subs[0].as_ref(), sat_prob, None)?;
compile_binary!(&mut left, &mut right, [1.0, 1.0], Terminal::AndB);
compile_binary!(&mut right, &mut left, [1.0, 1.0], Terminal::AndB);
compile_binary!(&mut left, &mut right, [1.0, 1.0], Terminal::AndV);
compile_binary!(&mut right, &mut left, [1.0, 1.0], Terminal::AndV);
let mut zero_comp = BTreeMap::new();
zero_comp.insert(
CompilationKey::from_type(Type::FALSE, ExtData::FALSE.has_free_verify, dissat_prob),
AstElemExt::terminal(Terminal::False),
);
compile_tern!(&mut left, &mut q_zero_right, &mut zero_comp, [1.0, 0.0]);
compile_tern!(&mut right, &mut q_zero_left, &mut zero_comp, [1.0, 0.0]);
}
Concrete::Or(ref subs) => {
let total = (subs[0].0 + subs[1].0) as f64;
let lw = subs[0].0 as f64 / total;
let rw = subs[1].0 as f64 / total;
//and-or
if let (Concrete::And(x), _) = (subs[0].1.as_ref(), subs[1].1.as_ref()) {
let mut a1 = best_compilations(
policy_cache,
x[0].as_ref(),
lw * sat_prob,
Some(dissat_prob.unwrap_or(0 as f64) + rw * sat_prob),
)?;
let mut a2 = best_compilations(policy_cache, x[0].as_ref(), lw * sat_prob, None)?;
let mut b1 = best_compilations(
policy_cache,
x[1].as_ref(),
lw * sat_prob,
Some(dissat_prob.unwrap_or(0 as f64) + rw * sat_prob),
)?;
let mut b2 = best_compilations(policy_cache, x[1].as_ref(), lw * sat_prob, None)?;
let mut c = best_compilations(
policy_cache,
subs[1].1.as_ref(),
rw * sat_prob,
dissat_prob,
)?;
compile_tern!(&mut a1, &mut b2, &mut c, [lw, rw]);
compile_tern!(&mut b1, &mut a2, &mut c, [lw, rw]);
};
if let (_, Concrete::And(x)) = (&subs[0].1.as_ref(), subs[1].1.as_ref()) {
let mut a1 = best_compilations(
policy_cache,
x[0].as_ref(),
rw * sat_prob,
Some(dissat_prob.unwrap_or(0 as f64) + lw * sat_prob),
)?;
let mut a2 = best_compilations(policy_cache, x[0].as_ref(), rw * sat_prob, None)?;
let mut b1 = best_compilations(
policy_cache,
x[1].as_ref(),
rw * sat_prob,
Some(dissat_prob.unwrap_or(0 as f64) + lw * sat_prob),
)?;
let mut b2 = best_compilations(policy_cache, x[1].as_ref(), rw * sat_prob, None)?;
let mut c = best_compilations(
policy_cache,
subs[0].1.as_ref(),
lw * sat_prob,
dissat_prob,
)?;
compile_tern!(&mut a1, &mut b2, &mut c, [rw, lw]);
compile_tern!(&mut b1, &mut a2, &mut c, [rw, lw]);
};
let dissat_probs = |w: f64| -> Vec<Option<f64>> {
vec![
Some(dissat_prob.unwrap_or(0 as f64) + w * sat_prob),
Some(w * sat_prob),
dissat_prob,
None,
]
};
let mut l_comp = vec![];
let mut r_comp = vec![];
for dissat_prob in dissat_probs(rw).iter() {
let l = best_compilations(
policy_cache,
subs[0].1.as_ref(),
lw * sat_prob,
*dissat_prob,
)?;
l_comp.push(l);
}
for dissat_prob in dissat_probs(lw).iter() {
let r = best_compilations(
policy_cache,
subs[1].1.as_ref(),
rw * sat_prob,
*dissat_prob,
)?;
r_comp.push(r);
}
// or(sha256, pk)
compile_binary!(&mut l_comp[0], &mut r_comp[0], [lw, rw], Terminal::OrB);
compile_binary!(&mut r_comp[0], &mut l_comp[0], [rw, lw], Terminal::OrB);
compile_binary!(&mut l_comp[0], &mut r_comp[2], [lw, rw], Terminal::OrD);
compile_binary!(&mut r_comp[0], &mut l_comp[2], [rw, lw], Terminal::OrD);