@@ -35,35 +35,35 @@ use crate::{errstr, AbsLockTime, Error, ForEachKey, MiniscriptKey, Translator};
35
35
#[ cfg( feature = "compiler" ) ]
36
36
const MAX_COMPILATION_LEAVES : usize = 1024 ;
37
37
38
- /// Concrete policy which corresponds directly to a Miniscript structure,
38
+ /// Concrete policy which corresponds directly to a miniscript structure,
39
39
/// and whose disjunctions are annotated with satisfaction probabilities
40
- /// to assist the compiler
40
+ /// to assist the compiler.
41
41
#[ derive( Clone , PartialEq , Eq , PartialOrd , Ord , Hash ) ]
42
42
pub enum Policy < Pk : MiniscriptKey > {
43
- /// Unsatisfiable
43
+ /// Unsatisfiable.
44
44
Unsatisfiable ,
45
- /// Trivially satisfiable
45
+ /// Trivially satisfiable.
46
46
Trivial ,
47
- /// A public key which must sign to satisfy the descriptor
47
+ /// A public key which must sign to satisfy the descriptor.
48
48
Key ( Pk ) ,
49
- /// An absolute locktime restriction
49
+ /// An absolute locktime restriction.
50
50
After ( AbsLockTime ) ,
51
- /// A relative locktime restriction
51
+ /// A relative locktime restriction.
52
52
Older ( Sequence ) ,
53
- /// A SHA256 whose preimage must be provided to satisfy the descriptor
53
+ /// A SHA256 whose preimage must be provided to satisfy the descriptor.
54
54
Sha256 ( Pk :: Sha256 ) ,
55
- /// A SHA256d whose preimage must be provided to satisfy the descriptor
55
+ /// A SHA256d whose preimage must be provided to satisfy the descriptor.
56
56
Hash256 ( Pk :: Hash256 ) ,
57
- /// A RIPEMD160 whose preimage must be provided to satisfy the descriptor
57
+ /// A RIPEMD160 whose preimage must be provided to satisfy the descriptor.
58
58
Ripemd160 ( Pk :: Ripemd160 ) ,
59
- /// A HASH160 whose preimage must be provided to satisfy the descriptor
59
+ /// A HASH160 whose preimage must be provided to satisfy the descriptor.
60
60
Hash160 ( Pk :: Hash160 ) ,
61
- /// A list of sub-policies, all of which must be satisfied
61
+ /// A list of sub-policies, all of which must be satisfied.
62
62
And ( Vec < Policy < Pk > > ) ,
63
63
/// A list of sub-policies, one of which must be satisfied, along with
64
- /// relative probabilities for each one
64
+ /// relative probabilities for each one.
65
65
Or ( Vec < ( usize , Policy < Pk > ) > ) ,
66
- /// A set of descriptors, satisfactions must be provided for `k` of them
66
+ /// A set of descriptors, satisfactions must be provided for `k` of them.
67
67
Threshold ( usize , Vec < Policy < Pk > > ) ,
68
68
}
69
69
@@ -183,29 +183,28 @@ impl<Pk: MiniscriptKey> From<Policy<Pk>> for PolicyArc<Pk> {
183
183
}
184
184
}
185
185
186
- /// Detailed Error type for Policies
186
+ /// Detailed error type for concrete policies.
187
187
#[ derive( Copy , Clone , PartialEq , Eq , Debug ) ]
188
188
pub enum PolicyError {
189
- /// `And` fragments only support two args
189
+ /// `And` fragments only support two args.
190
190
NonBinaryArgAnd ,
191
- /// `Or` fragments only support two args
191
+ /// `Or` fragments only support two args.
192
192
NonBinaryArgOr ,
193
- /// `Thresh` fragment can only have `1<=k<=n`
193
+ /// `Thresh` fragment can only have `1<=k<=n`.
194
194
IncorrectThresh ,
195
- /// `older` or `after` fragment can only have `n = 0`
195
+ /// `older` or `after` fragment can only have `n = 0`.
196
196
ZeroTime ,
197
- /// `after` fragment can only have ` n < 2^31`
197
+ /// `after` fragment can only have `n < 2^31`.
198
198
TimeTooFar ,
199
- /// Semantic Policy Error: `And` `Or` fragments must take args: k > 1
199
+ /// Semantic Policy Error: `And` `Or` fragments must take args: ` k > 1`.
200
200
InsufficientArgsforAnd ,
201
- /// Semantic Policy Error : `And` `Or` fragments must take args: k > 1
201
+ /// Semantic policy error : `And` `Or` fragments must take args: ` k > 1`.
202
202
InsufficientArgsforOr ,
203
- /// Entailment max terminals exceeded
203
+ /// Entailment max terminals exceeded.
204
204
EntailmentMaxTerminals ,
205
- /// lifting error: Cannot lift policies that have
206
- /// a combination of height and timelocks.
205
+ /// Cannot lift policies that have a combination of height and timelocks.
207
206
HeightTimelockCombination ,
208
- /// Duplicate Public Keys
207
+ /// Duplicate Public Keys.
209
208
DuplicatePubKeys ,
210
209
}
211
210
@@ -278,8 +277,8 @@ impl error::Error for PolicyError {
278
277
}
279
278
280
279
impl < Pk : MiniscriptKey > Policy < Pk > {
281
- /// Flatten the [`Policy`] tree structure into a Vector of tuple `(leaf script, leaf probability)`
282
- /// with leaf probabilities corresponding to odds for sub-branch in the policy.
280
+ /// Flattens the [`Policy`] tree structure into a vector of tuples `(leaf script, leaf probability)`
281
+ /// with leaf probabilities corresponding to odds for each sub-branch in the policy.
283
282
/// We calculate the probability of selecting the sub-branch at every level and calculate the
284
283
/// leaf probabilities as the probability of traversing through required branches to reach the
285
284
/// leaf node, i.e. multiplication of the respective probabilities.
@@ -298,7 +297,7 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
298
297
///
299
298
/// ## Constraints
300
299
///
301
- /// Since this splitting might lead to exponential blow-up, we constraint the number of
300
+ /// Since this splitting might lead to exponential blow-up, we constrain the number of
302
301
/// leaf-nodes to [`MAX_COMPILATION_LEAVES`].
303
302
#[ cfg( feature = "compiler" ) ]
304
303
fn to_tapleaf_prob_vec ( & self , prob : f64 ) -> Vec < ( f64 , Policy < Pk > ) > {
@@ -323,7 +322,7 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
323
322
}
324
323
}
325
324
326
- /// Extract the internal_key from policy tree.
325
+ /// Extracts the internal_key from this policy tree.
327
326
#[ cfg( feature = "compiler" ) ]
328
327
fn extract_key ( self , unspendable_key : Option < Pk > ) -> Result < ( Pk , Policy < Pk > ) , Error > {
329
328
let mut internal_key: Option < Pk > = None ;
@@ -366,13 +365,14 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
366
365
}
367
366
}
368
367
369
- /// Compile the [`Policy`] into a [`Descriptor::Tr`].
368
+ /// Compiles the [`Policy`] into a [`Descriptor::Tr`].
370
369
///
371
370
/// ### TapTree compilation
372
371
///
373
- /// The policy tree constructed by root-level disjunctions over [`Or`][` Policy::Or`] and
374
- /// [`Thresh`][` Policy::Threshold`](1, ..) which is flattened into a vector (with respective
372
+ /// The policy tree constructed by root-level disjunctions over [`Policy::Or`] and
373
+ /// [`Policy::Threshold`](1, ..) which is flattened into a vector (with respective
375
374
/// probabilities derived from odds) of policies.
375
+ ///
376
376
/// For example, the policy `thresh(1,or(pk(A),pk(B)),and(or(pk(C),pk(D)),pk(E)))` gives the
377
377
/// vector `[pk(A),pk(B),and(or(pk(C),pk(D)),pk(E)))]`. Each policy in the vector is compiled
378
378
/// into the respective miniscripts. A Huffman Tree is created from this vector which optimizes
@@ -424,7 +424,7 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
424
424
/// ### TapTree compilation
425
425
///
426
426
/// The policy tree constructed by root-level disjunctions over [`Policy::Or`] and
427
- /// [`Policy::Threshold`] (k, ..n..) which is flattened into a vector (with respective
427
+ /// [`Policy::Threshold`](k, ..n..) which is flattened into a vector (with respective
428
428
/// probabilities derived from odds) of policies. For example, the policy
429
429
/// `thresh(1,or(pk(A),pk(B)),and(or(pk(C),pk(D)),pk(E)))` gives the vector
430
430
/// `[pk(A),pk(B),and(or(pk(C),pk(D)),pk(E)))]`.
@@ -437,8 +437,6 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
437
437
/// enumeration or limits exceed. For a given [`Policy`], we maintain an [ordered
438
438
/// set](`BTreeSet`) of `(prob, policy)` (ordered by probability) to maintain the list of
439
439
/// enumerated sub-policies whose disjunction is isomorphic to initial policy (*invariant*).
440
- ///
441
- /// [`Policy`]: crate::policy::concrete::Policy
442
440
#[ cfg( feature = "compiler" ) ]
443
441
pub fn compile_tr_private_experimental (
444
442
& self ,
@@ -480,16 +478,16 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
480
478
}
481
479
}
482
480
483
- /// Compile the [`Policy`] into desc_ctx [`Descriptor`]
481
+ /// Compiles the [`Policy`] into ` desc_ctx` [`Descriptor`]
484
482
///
485
- /// In case of [Tr][ `DescriptorCtx::Tr`], `internal_key` is used for the Taproot comilation when
483
+ /// In case of [`DescriptorCtx::Tr`], `internal_key` is used for the taproot compilation when
486
484
/// no public key can be inferred from the given policy.
487
485
///
488
486
/// # NOTE:
489
487
///
490
- /// It is **not recommended** to use policy as a stable identifier for a miniscript.
491
- /// You should use the policy compiler once, and then use the miniscript output as a stable identifier.
492
- /// See the compiler document in doc/compiler.md for more details.
488
+ /// It is **not recommended** to use policy as a stable identifier for a miniscript. You should
489
+ /// use the policy compiler once, and then use the miniscript output as a stable identifier. See
490
+ /// the compiler document in [` doc/compiler.md`] for more details.
493
491
#[ cfg( feature = "compiler" ) ]
494
492
pub fn compile_to_descriptor < Ctx : ScriptContext > (
495
493
& self ,
@@ -511,13 +509,13 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
511
509
}
512
510
}
513
511
514
- /// Compile the descriptor into an optimized `Miniscript` representation
512
+ /// Compiles the descriptor into an optimized `Miniscript` representation.
515
513
///
516
514
/// # NOTE:
517
515
///
518
- /// It is **not recommended** to use policy as a stable identifier for a miniscript.
519
- /// You should use the policy compiler once, and then use the miniscript output as a stable identifier.
520
- /// See the compiler document in doc/compiler.md for more details.
516
+ /// It is **not recommended** to use policy as a stable identifier for a miniscript. You should
517
+ /// use the policy compiler once, and then use the miniscript output as a stable identifier. See
518
+ /// the compiler document in doc/compiler.md for more details.
521
519
#[ cfg( feature = "compiler" ) ]
522
520
pub fn compile < Ctx : ScriptContext > ( & self ) -> Result < Miniscript < Pk , Ctx > , CompilerError > {
523
521
self . is_valid ( ) ?;
@@ -531,10 +529,11 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
531
529
532
530
#[ cfg( feature = "compiler" ) ]
533
531
impl < Pk : MiniscriptKey > PolicyArc < Pk > {
534
- /// Given a [`Policy`], return a vector of policies whose disjunction is isomorphic to the initial one.
535
- /// This function is supposed to incrementally expand i.e. represent the policy as disjunction over
536
- /// sub-policies output by it. The probability calculations are similar as
537
- /// [to_tapleaf_prob_vec][`Policy::to_tapleaf_prob_vec`]
532
+ /// Returns a vector of policies whose disjunction is isomorphic to the initial one.
533
+ ///
534
+ /// This function is supposed to incrementally expand i.e. represent the policy as
535
+ /// disjunction over sub-policies output by it. The probability calculations are similar
536
+ /// to [`Policy::to_tapleaf_prob_vec`].
538
537
#[ cfg( feature = "compiler" ) ]
539
538
fn enumerate_pol ( & self , prob : f64 ) -> Vec < ( f64 , Arc < Self > ) > {
540
539
match self {
@@ -563,8 +562,6 @@ impl<Pk: MiniscriptKey> PolicyArc<Pk> {
563
562
/// enumeration or limits exceed. For a given [`Policy`], we maintain an [ordered
564
563
/// set](`BTreeSet`) of `(prob, policy)` (ordered by probability) to maintain the list of
565
564
/// enumerated sub-policies whose disjunction is isomorphic to initial policy (*invariant*).
566
- ///
567
- /// [`Policy`]: crate::policy::concrete::Policy
568
565
#[ cfg( feature = "compiler" ) ]
569
566
fn enumerate_policy_tree ( self , prob : f64 ) -> Vec < ( f64 , Arc < Self > ) > {
570
567
let mut tapleaf_prob_vec = BTreeSet :: < ( Reverse < OrdF64 > , Arc < Self > ) > :: new ( ) ;
@@ -689,49 +686,9 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
689
686
}
690
687
}
691
688
692
- /// Convert a policy using one kind of public key to another
693
- /// type of public key
694
- ///
695
- /// # Example
696
- ///
697
- /// ```
698
- /// use miniscript::{bitcoin::PublicKey, policy::concrete::Policy, Translator, hash256};
699
- /// use std::str::FromStr;
700
- /// use miniscript::translate_hash_fail;
701
- /// use std::collections::HashMap;
702
- /// use miniscript::bitcoin::hashes::{sha256, hash160, ripemd160};
703
- /// let alice_key = "0270cf3c71f65a3d93d285d9149fddeeb638f87a2d4d8cf16c525f71c417439777";
704
- /// let bob_key = "02f43b15c50a436f5335dbea8a64dd3b4e63e34c3b50c42598acb5f4f336b5d2fb";
705
- /// let placeholder_policy = Policy::<String>::from_str("and(pk(alice_key),pk(bob_key))").unwrap();
706
- ///
707
- /// // Information to translator abstract String type keys to concrete bitcoin::PublicKey.
708
- /// // In practice, wallets would map from String key names to BIP32 keys
709
- /// struct StrPkTranslator {
710
- /// pk_map: HashMap<String, bitcoin::PublicKey>
711
- /// }
712
- ///
713
- /// // If we also wanted to provide mapping of other associated types(sha256, older etc),
714
- /// // we would use the general Translator Trait.
715
- /// impl Translator<String, bitcoin::PublicKey, ()> for StrPkTranslator {
716
- /// // Provides the translation public keys P -> Q
717
- /// fn pk(&mut self, pk: &String) -> Result<bitcoin::PublicKey, ()> {
718
- /// self.pk_map.get(pk).copied().ok_or(()) // Dummy Err
719
- /// }
720
- ///
721
- /// // Fail for hash types
722
- /// translate_hash_fail!(String, bitcoin::PublicKey, ());
723
- /// }
689
+ /// Converts a policy using one kind of public key to another type of public key.
724
690
///
725
- /// let mut pk_map = HashMap::new();
726
- /// pk_map.insert(String::from("alice_key"), bitcoin::PublicKey::from_str(alice_key).unwrap());
727
- /// pk_map.insert(String::from("bob_key"), bitcoin::PublicKey::from_str(bob_key).unwrap());
728
- /// let mut t = StrPkTranslator { pk_map: pk_map };
729
- ///
730
- /// let real_policy = placeholder_policy.translate_pk(&mut t).unwrap();
731
- ///
732
- /// let expected_policy = Policy::from_str(&format!("and(pk({}),pk({}))", alice_key, bob_key)).unwrap();
733
- /// assert_eq!(real_policy, expected_policy);
734
- /// ```
691
+ /// For example usage please see [`crate::policy::semantic::Policy::translate_pk`].
735
692
pub fn translate_pk < Q , E , T > ( & self , t : & mut T ) -> Result < Policy < Q > , E >
736
693
where
737
694
T : Translator < Pk , Q , E > ,
@@ -773,7 +730,7 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
773
730
}
774
731
}
775
732
776
- /// Translate `Concrete::Key(key)` to `Concrete::Unsatisfiable` when extracting TapKey
733
+ /// Translates `Concrete::Key(key)` to `Concrete::Unsatisfiable` when extracting ` TapKey`.
777
734
pub fn translate_unsatisfiable_pk ( self , key : & Pk ) -> Policy < Pk > {
778
735
match self {
779
736
Policy :: Key ( ref k) if k. clone ( ) == * key => Policy :: Unsatisfiable ,
@@ -797,7 +754,7 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
797
754
}
798
755
}
799
756
800
- /// Get all keys in the policy
757
+ /// Gets all keys in the policy.
801
758
pub fn keys ( & self ) -> Vec < & Pk > {
802
759
match * self {
803
760
Policy :: Key ( ref pk) => vec ! [ pk] ,
@@ -814,8 +771,8 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
814
771
}
815
772
}
816
773
817
- /// Get the number of [TapLeaf][ `TapTree::Leaf`] considering exhaustive root-level [OR] [`Policy::Or`]
818
- /// and [Thresh][ `Policy::Threshold`] disjunctions for the TapTree.
774
+ /// Gets the number of [TapLeaf]( `TapTree::Leaf`)s considering exhaustive root-level [`Policy::Or`]
775
+ /// and [`Policy::Threshold`] disjunctions for the ` TapTree` .
819
776
#[ cfg( feature = "compiler" ) ]
820
777
fn num_tap_leaves ( & self ) -> usize {
821
778
match self {
@@ -827,7 +784,7 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
827
784
}
828
785
}
829
786
830
- /// Check on the number of TapLeaves
787
+ /// Does checks on the number of `TapLeaf`s.
831
788
#[ cfg( feature = "compiler" ) ]
832
789
fn check_num_tapleaves ( & self ) -> Result < ( ) , Error > {
833
790
if self . num_tap_leaves ( ) > MAX_COMPILATION_LEAVES {
@@ -836,7 +793,7 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
836
793
Ok ( ( ) )
837
794
}
838
795
839
- /// Check whether the policy contains duplicate public keys
796
+ /// Checks whether the policy contains duplicate public keys.
840
797
pub fn check_duplicate_keys ( & self ) -> Result < ( ) , PolicyError > {
841
798
let pks = self . keys ( ) ;
842
799
let pks_len = pks. len ( ) ;
@@ -851,8 +808,11 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
851
808
852
809
/// Checks whether the given concrete policy contains a combination of
853
810
/// timelocks and heightlocks.
811
+ ///
812
+ /// # Returns
813
+ ///
854
814
/// Returns an error if there is at least one satisfaction that contains
855
- /// a combination of hieghtlock and timelock.
815
+ /// a combination of heightlock and timelock.
856
816
pub fn check_timelocks ( & self ) -> Result < ( ) , PolicyError > {
857
817
let timelocks = self . check_timelocks_helper ( ) ;
858
818
if timelocks. contains_combination {
@@ -962,11 +922,14 @@ impl<Pk: MiniscriptKey> Policy<Pk> {
962
922
_ => Ok ( ( ) ) ,
963
923
}
964
924
}
965
- /// This returns whether any possible compilation of the policy could be
966
- /// compiled as non-malleable and safe. Note that this returns a tuple
967
- /// (safe, non-malleable) to avoid because the non-malleability depends on
968
- /// safety and we would like to cache results.
925
+
926
+ /// Checks if any possible compilation of the policy could be compiled
927
+ /// as non-malleable and safe.
928
+ ///
929
+ /// # Returns
969
930
///
931
+ /// Returns a tuple `(safe, non-malleable)` to avoid the fact that
932
+ /// non-malleability depends on safety and we would like to cache results.
970
933
pub fn is_safe_nonmalleable ( & self ) -> ( bool , bool ) {
971
934
match * self {
972
935
Policy :: Unsatisfiable | Policy :: Trivial => ( true , true ) ,
@@ -1232,7 +1195,7 @@ impl_from_tree!(
1232
1195
}
1233
1196
) ;
1234
1197
1235
- /// Create a Huffman Tree from compiled [Miniscript] nodes
1198
+ /// Creates a Huffman Tree from compiled [` Miniscript` ] nodes.
1236
1199
#[ cfg( feature = "compiler" ) ]
1237
1200
fn with_huffman_tree < Pk : MiniscriptKey > (
1238
1201
ms : Vec < ( OrdF64 , Miniscript < Pk , Tap > ) > ,
@@ -1263,7 +1226,7 @@ fn with_huffman_tree<Pk: MiniscriptKey>(
1263
1226
Ok ( node)
1264
1227
}
1265
1228
1266
- /// Enumerate a [Thresh][ `Policy::Threshold`] (k, ..n..) into `n` different thresh.
1229
+ /// Enumerates a [`Policy::Threshold(k, ..n..)`] into `n` different thresh's .
1267
1230
///
1268
1231
/// ## Strategy
1269
1232
///
0 commit comments