1use core::str::FromStr;
18use core::{fmt, str};
19
20use bitcoin::{LockTime, PackedLockTime, Sequence};
21
22use super::concrete::PolicyError;
23use super::ENTAILMENT_MAX_TERMINALS;
24use crate::prelude::*;
25use crate::{errstr, expression, Error, ForEachKey, MiniscriptKey, Translator};
26
27#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
34pub enum Policy<Pk: MiniscriptKey> {
35 Unsatisfiable,
37 Trivial,
39 Key(Pk),
41 After(PackedLockTime),
43 Older(Sequence),
45 Sha256(Pk::Sha256),
47 Hash256(Pk::Hash256),
49 Ripemd160(Pk::Ripemd160),
51 Hash160(Pk::Hash160),
53 Threshold(usize, Vec<Policy<Pk>>),
55}
56
57impl<Pk> Policy<Pk>
58where
59 Pk: MiniscriptKey,
60{
61 pub fn after(n: u32) -> Policy<Pk> {
64 Policy::After(PackedLockTime::from(LockTime::from_consensus(n)))
65 }
66
67 pub fn older(n: u32) -> Policy<Pk> {
70 Policy::Older(Sequence::from_consensus(n))
71 }
72}
73
74impl<Pk: MiniscriptKey> ForEachKey<Pk> for Policy<Pk> {
75 fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool
76 where
77 Pk: 'a,
78 {
79 match *self {
80 Policy::Unsatisfiable | Policy::Trivial => true,
81 Policy::Key(ref _pkh) => todo!("Semantic Policy KeyHash must store Pk"),
82 Policy::Sha256(..)
83 | Policy::Hash256(..)
84 | Policy::Ripemd160(..)
85 | Policy::Hash160(..)
86 | Policy::After(..)
87 | Policy::Older(..) => true,
88 Policy::Threshold(_, ref subs) => subs.iter().all(|sub| sub.for_each_key(&mut pred)),
89 }
90 }
91}
92
93impl<Pk: MiniscriptKey> Policy<Pk> {
94 pub fn translate_pk<Q, E, T>(&self, t: &mut T) -> Result<Policy<Q>, E>
137 where
138 T: Translator<Pk, Q, E>,
139 Q: MiniscriptKey,
140 {
141 self._translate_pk(t)
142 }
143
144 fn _translate_pk<Q, E, T>(&self, t: &mut T) -> Result<Policy<Q>, E>
145 where
146 T: Translator<Pk, Q, E>,
147 Q: MiniscriptKey,
148 {
149 match *self {
150 Policy::Unsatisfiable => Ok(Policy::Unsatisfiable),
151 Policy::Trivial => Ok(Policy::Trivial),
152 Policy::Key(ref pk) => t.pk(pk).map(Policy::Key),
153 Policy::Sha256(ref h) => t.sha256(h).map(Policy::Sha256),
154 Policy::Hash256(ref h) => t.hash256(h).map(Policy::Hash256),
155 Policy::Ripemd160(ref h) => t.ripemd160(h).map(Policy::Ripemd160),
156 Policy::Hash160(ref h) => t.hash160(h).map(Policy::Hash160),
157 Policy::After(n) => Ok(Policy::After(n)),
158 Policy::Older(n) => Ok(Policy::Older(n)),
159 Policy::Threshold(k, ref subs) => {
160 let new_subs: Result<Vec<Policy<Q>>, _> =
161 subs.iter().map(|sub| sub._translate_pk(t)).collect();
162 new_subs.map(|ok| Policy::Threshold(k, ok))
163 }
164 }
165 }
166
167 pub fn entails(self, other: Policy<Pk>) -> Result<bool, PolicyError> {
175 if self.n_terminals() > ENTAILMENT_MAX_TERMINALS {
176 return Err(PolicyError::EntailmentMaxTerminals);
177 }
178 match (self, other) {
179 (Policy::Unsatisfiable, _) => Ok(true),
180 (Policy::Trivial, Policy::Trivial) => Ok(true),
181 (Policy::Trivial, _) => Ok(false),
182 (_, Policy::Unsatisfiable) => Ok(false),
183 (a, b) => {
184 let (a_norm, b_norm) = (a.normalized(), b.normalized());
185 let first_constraint = a_norm.first_constraint();
186 let (a1, b1) = (
187 a_norm.clone().satisfy_constraint(&first_constraint, true),
188 b_norm.clone().satisfy_constraint(&first_constraint, true),
189 );
190 let (a2, b2) = (
191 a_norm.satisfy_constraint(&first_constraint, false),
192 b_norm.satisfy_constraint(&first_constraint, false),
193 );
194 Ok(Policy::entails(a1, b1)? && Policy::entails(a2, b2)?)
195 }
196 }
197 }
198
199 fn n_terminals(&self) -> usize {
201 match self {
202 &Policy::Threshold(_k, ref subs) => subs.iter().map(|sub| sub.n_terminals()).sum(),
203 &Policy::Trivial | &Policy::Unsatisfiable => 0,
204 _leaf => 1,
205 }
206 }
207
208 fn first_constraint(&self) -> Policy<Pk> {
212 debug_assert!(self.clone().normalized() == self.clone());
213 match self {
214 &Policy::Threshold(_k, ref subs) => subs[0].first_constraint(),
215 first => first.clone(),
216 }
217 }
218
219 pub(crate) fn satisfy_constraint(self, witness: &Policy<Pk>, available: bool) -> Policy<Pk> {
225 debug_assert!(self.clone().normalized() == self);
226 match *witness {
227 Policy::Threshold(..) => unreachable!(),
229 _ => {}
230 };
231 let ret = match self {
232 Policy::Threshold(k, subs) => {
233 let mut ret_subs = vec![];
234 for sub in subs {
235 ret_subs.push(sub.satisfy_constraint(witness, available));
236 }
237 Policy::Threshold(k, ret_subs)
238 }
239 ref leaf if leaf == witness => {
240 if available {
241 Policy::Trivial
242 } else {
243 Policy::Unsatisfiable
244 }
245 }
246 x => x,
247 };
248 ret.normalized()
249 }
250}
251
252impl<Pk: MiniscriptKey> fmt::Debug for Policy<Pk> {
253 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
254 match *self {
255 Policy::Unsatisfiable => f.write_str("UNSATISFIABLE()"),
256 Policy::Trivial => f.write_str("TRIVIAL()"),
257 Policy::Key(ref pkh) => write!(f, "pk({:?})", pkh),
258 Policy::After(n) => write!(f, "after({})", n),
259 Policy::Older(n) => write!(f, "older({})", n),
260 Policy::Sha256(ref h) => write!(f, "sha256({})", h),
261 Policy::Hash256(ref h) => write!(f, "hash256({})", h),
262 Policy::Ripemd160(ref h) => write!(f, "ripemd160({})", h),
263 Policy::Hash160(ref h) => write!(f, "hash160({})", h),
264 Policy::Threshold(k, ref subs) => {
265 if k == subs.len() {
266 write!(f, "and(")?;
267 } else if k == 1 {
268 write!(f, "or(")?;
269 } else {
270 write!(f, "thresh({},", k)?;
271 }
272 for (i, sub) in subs.iter().enumerate() {
273 if i == 0 {
274 write!(f, "{}", sub)?;
275 } else {
276 write!(f, ",{}", sub)?;
277 }
278 }
279 f.write_str(")")
280 }
281 }
282 }
283}
284
285impl<Pk: MiniscriptKey> fmt::Display for Policy<Pk> {
286 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
287 match *self {
288 Policy::Unsatisfiable => f.write_str("UNSATISFIABLE"),
289 Policy::Trivial => f.write_str("TRIVIAL"),
290 Policy::Key(ref pkh) => write!(f, "pk({})", pkh),
291 Policy::After(n) => write!(f, "after({})", n),
292 Policy::Older(n) => write!(f, "older({})", n),
293 Policy::Sha256(ref h) => write!(f, "sha256({})", h),
294 Policy::Hash256(ref h) => write!(f, "hash256({})", h),
295 Policy::Ripemd160(ref h) => write!(f, "ripemd160({})", h),
296 Policy::Hash160(ref h) => write!(f, "hash160({})", h),
297 Policy::Threshold(k, ref subs) => {
298 if k == subs.len() {
299 write!(f, "and(")?;
300 } else if k == 1 {
301 write!(f, "or(")?;
302 } else {
303 write!(f, "thresh({},", k)?;
304 }
305 for (i, sub) in subs.iter().enumerate() {
306 if i == 0 {
307 write!(f, "{}", sub)?;
308 } else {
309 write!(f, ",{}", sub)?;
310 }
311 }
312 f.write_str(")")
313 }
314 }
315 }
316}
317
318impl_from_str!(
319 Policy<Pk>,
320 type Err = Error;,
321 fn from_str(s: &str) -> Result<Policy<Pk>, Error> {
322 for ch in s.as_bytes() {
323 if *ch < 20 || *ch > 127 {
324 return Err(Error::Unprintable(*ch));
325 }
326 }
327
328 let tree = expression::Tree::from_str(s)?;
329 expression::FromTree::from_tree(&tree)
330 }
331);
332
333serde_string_impl_pk!(Policy, "a miniscript semantic policy");
334
335impl_from_tree!(
336 Policy<Pk>,
337 fn from_tree(top: &expression::Tree) -> Result<Policy<Pk>, Error> {
338 match (top.name, top.args.len()) {
339 ("UNSATISFIABLE", 0) => Ok(Policy::Unsatisfiable),
340 ("TRIVIAL", 0) => Ok(Policy::Trivial),
341 ("pk", 1) => expression::terminal(&top.args[0], |pk| Pk::from_str(pk).map(Policy::Key)),
342 ("after", 1) => expression::terminal(&top.args[0], |x| {
343 expression::parse_num(x).map(|x| Policy::after(x))
344 }),
345 ("older", 1) => expression::terminal(&top.args[0], |x| {
346 expression::parse_num(x).map(|x| Policy::older(x))
347 }),
348 ("sha256", 1) => expression::terminal(&top.args[0], |x| {
349 Pk::Sha256::from_str(x).map(Policy::Sha256)
350 }),
351 ("hash256", 1) => expression::terminal(&top.args[0], |x| {
352 Pk::Hash256::from_str(x).map(Policy::Hash256)
353 }),
354 ("ripemd160", 1) => expression::terminal(&top.args[0], |x| {
355 Pk::Ripemd160::from_str(x).map(Policy::Ripemd160)
356 }),
357 ("hash160", 1) => expression::terminal(&top.args[0], |x| {
358 Pk::Hash160::from_str(x).map(Policy::Hash160)
359 }),
360 ("and", nsubs) => {
361 if nsubs < 2 {
362 return Err(Error::PolicyError(PolicyError::InsufficientArgsforAnd));
363 }
364 let mut subs = Vec::with_capacity(nsubs);
365 for arg in &top.args {
366 subs.push(Policy::from_tree(arg)?);
367 }
368 Ok(Policy::Threshold(nsubs, subs))
369 }
370 ("or", nsubs) => {
371 if nsubs < 2 {
372 return Err(Error::PolicyError(PolicyError::InsufficientArgsforOr));
373 }
374 let mut subs = Vec::with_capacity(nsubs);
375 for arg in &top.args {
376 subs.push(Policy::from_tree(arg)?);
377 }
378 Ok(Policy::Threshold(1, subs))
379 }
380 ("thresh", nsubs) => {
381 if nsubs == 0 || nsubs == 1 {
382 return Err(errstr("thresh without args"));
384 }
385 if !top.args[0].args.is_empty() {
386 return Err(errstr(top.args[0].args[0].name));
387 }
388
389 let thresh = expression::parse_num(top.args[0].name)?;
390
391 if thresh <= 1 || thresh >= (nsubs as u32 - 1) {
393 return Err(errstr(
394 "Semantic Policy thresh cannot have k = 1 or k =n, use `and`/`or` instead",
395 ));
396 }
397 if thresh >= (nsubs as u32) {
398 return Err(errstr(top.args[0].name));
399 }
400
401 let mut subs = Vec::with_capacity(top.args.len() - 1);
402 for arg in &top.args[1..] {
403 subs.push(Policy::from_tree(arg)?);
404 }
405 Ok(Policy::Threshold(thresh as usize, subs))
406 }
407 _ => Err(errstr(top.name)),
408 }
409 }
410);
411
412impl<Pk: MiniscriptKey> Policy<Pk> {
413 pub fn normalized(self) -> Policy<Pk> {
416 match self {
417 Policy::Threshold(k, subs) => {
418 let mut ret_subs = Vec::with_capacity(subs.len());
419
420 let subs: Vec<_> = subs.into_iter().map(|sub| sub.normalized()).collect();
421 let trivial_count = subs.iter().filter(|&pol| *pol == Policy::Trivial).count();
422 let unsatisfied_count = subs
423 .iter()
424 .filter(|&pol| *pol == Policy::Unsatisfiable)
425 .count();
426
427 let n = subs.len() - unsatisfied_count - trivial_count; let m = k.checked_sub(trivial_count).map_or(0, |x| x); let is_and = m == n;
431 let is_or = m == 1;
432 for sub in subs {
433 match sub {
434 Policy::Trivial | Policy::Unsatisfiable => {}
435 Policy::Threshold(k, subs) => {
436 match (is_and, is_or) {
437 (true, true) => {
438 ret_subs.push(Policy::Threshold(k, subs));
440 }
441 (true, false) if k == subs.len() => ret_subs.extend(subs), (false, true) if k == 1 => ret_subs.extend(subs), _ => ret_subs.push(Policy::Threshold(k, subs)),
444 }
445 }
446 x => ret_subs.push(x),
447 }
448 }
449 if m == 0 {
451 Policy::Trivial
452 } else if m > ret_subs.len() {
453 Policy::Unsatisfiable
454 } else if ret_subs.len() == 1 {
455 ret_subs.pop().unwrap()
456 } else if is_and {
457 Policy::Threshold(ret_subs.len(), ret_subs)
458 } else if is_or {
459 Policy::Threshold(1, ret_subs)
460 } else {
461 Policy::Threshold(m, ret_subs)
462 }
463 }
464 x => x,
465 }
466 }
467
468 pub fn is_trivial(&self) -> bool {
473 match *self {
474 Policy::Trivial => true,
475 _ => false,
476 }
477 }
478
479 pub fn is_unsatisfiable(&self) -> bool {
484 match *self {
485 Policy::Unsatisfiable => true,
486 _ => false,
487 }
488 }
489
490 fn real_relative_timelocks(&self) -> Vec<u32> {
492 match *self {
493 Policy::Unsatisfiable
494 | Policy::Trivial
495 | Policy::Key(..)
496 | Policy::Sha256(..)
497 | Policy::Hash256(..)
498 | Policy::Ripemd160(..)
499 | Policy::Hash160(..) => vec![],
500 Policy::After(..) => vec![],
501 Policy::Older(t) => vec![t.to_consensus_u32()],
502 Policy::Threshold(_, ref subs) => subs.iter().fold(vec![], |mut acc, x| {
503 acc.extend(x.real_relative_timelocks());
504 acc
505 }),
506 }
507 }
508
509 pub fn relative_timelocks(&self) -> Vec<u32> {
512 let mut ret = self.real_relative_timelocks();
513 ret.sort_unstable();
514 ret.dedup();
515 ret
516 }
517
518 fn real_absolute_timelocks(&self) -> Vec<u32> {
520 match *self {
521 Policy::Unsatisfiable
522 | Policy::Trivial
523 | Policy::Key(..)
524 | Policy::Sha256(..)
525 | Policy::Hash256(..)
526 | Policy::Ripemd160(..)
527 | Policy::Hash160(..) => vec![],
528 Policy::Older(..) => vec![],
529 Policy::After(t) => vec![t.0],
530 Policy::Threshold(_, ref subs) => subs.iter().fold(vec![], |mut acc, x| {
531 acc.extend(x.real_absolute_timelocks());
532 acc
533 }),
534 }
535 }
536
537 pub fn absolute_timelocks(&self) -> Vec<u32> {
540 let mut ret = self.real_absolute_timelocks();
541 ret.sort_unstable();
542 ret.dedup();
543 ret
544 }
545
546 pub fn at_age(mut self, age: Sequence) -> Policy<Pk> {
549 self = match self {
550 Policy::Older(t) => {
551 if t.is_height_locked() && age.is_time_locked()
552 || t.is_time_locked() && age.is_height_locked()
553 {
554 Policy::Unsatisfiable
555 } else if t.to_consensus_u32() > age.to_consensus_u32() {
556 Policy::Unsatisfiable
557 } else {
558 Policy::Older(t)
559 }
560 }
561 Policy::Threshold(k, subs) => {
562 Policy::Threshold(k, subs.into_iter().map(|sub| sub.at_age(age)).collect())
563 }
564 x => x,
565 };
566 self.normalized()
567 }
568
569 pub fn at_lock_time(mut self, n: LockTime) -> Policy<Pk> {
572 use LockTime::*;
573
574 self = match self {
575 Policy::After(t) => {
576 let t = LockTime::from(t);
577 let is_satisfied_by = match (t, n) {
578 (Blocks(t), Blocks(n)) => t <= n,
579 (Seconds(t), Seconds(n)) => t <= n,
580 _ => false,
581 };
582 if !is_satisfied_by {
583 Policy::Unsatisfiable
584 } else {
585 Policy::After(t.into())
586 }
587 }
588 Policy::Threshold(k, subs) => {
589 Policy::Threshold(k, subs.into_iter().map(|sub| sub.at_lock_time(n)).collect())
590 }
591 x => x,
592 };
593 self.normalized()
594 }
595
596 pub fn n_keys(&self) -> usize {
599 match *self {
600 Policy::Unsatisfiable | Policy::Trivial => 0,
601 Policy::Key(..) => 1,
602 Policy::After(..)
603 | Policy::Older(..)
604 | Policy::Sha256(..)
605 | Policy::Hash256(..)
606 | Policy::Ripemd160(..)
607 | Policy::Hash160(..) => 0,
608 Policy::Threshold(_, ref subs) => subs.iter().map(|sub| sub.n_keys()).sum::<usize>(),
609 }
610 }
611
612 pub fn minimum_n_keys(&self) -> Option<usize> {
616 match *self {
617 Policy::Unsatisfiable => None,
618 Policy::Trivial => Some(0),
619 Policy::Key(..) => Some(1),
620 Policy::After(..)
621 | Policy::Older(..)
622 | Policy::Sha256(..)
623 | Policy::Hash256(..)
624 | Policy::Ripemd160(..)
625 | Policy::Hash160(..) => Some(0),
626 Policy::Threshold(k, ref subs) => {
627 let mut sublens: Vec<usize> =
628 subs.iter().filter_map(Policy::minimum_n_keys).collect();
629 if sublens.len() < k {
630 None
632 } else {
633 sublens.sort_unstable();
634 Some(sublens[0..k].iter().cloned().sum::<usize>())
635 }
636 }
637 }
638 }
639}
640
641impl<Pk: MiniscriptKey> Policy<Pk> {
642 pub fn sorted(self) -> Policy<Pk> {
647 match self {
648 Policy::Threshold(k, subs) => {
649 let mut new_subs: Vec<_> = subs.into_iter().map(Policy::sorted).collect();
650 new_subs.sort();
651 Policy::Threshold(k, new_subs)
652 }
653 x => x,
654 }
655 }
656}
657
658#[cfg(test)]
659mod tests {
660 use core::str::FromStr;
661
662 use bitcoin::PublicKey;
663
664 use super::*;
665
666 type StringPolicy = Policy<String>;
667
668 #[test]
669 fn parse_policy_err() {
670 assert!(StringPolicy::from_str("(").is_err());
671 assert!(StringPolicy::from_str("(x()").is_err());
672 assert!(StringPolicy::from_str("(\u{7f}()3").is_err());
673 assert!(StringPolicy::from_str("pk()").is_ok());
674
675 assert!(StringPolicy::from_str("or(or)").is_err());
676
677 assert!(Policy::<PublicKey>::from_str("pk()").is_err());
678 assert!(Policy::<PublicKey>::from_str(
679 "pk(\
680 0200000000000000000000000000000000000002\
681 )"
682 )
683 .is_err());
684 assert!(Policy::<PublicKey>::from_str(
685 "pk(\
686 02c79ef3ede6d14f72a00d0e49b4becfb152197b64c0707425c4f231df29500ee7\
687 )"
688 )
689 .is_ok());
690 }
691
692 #[test]
693 fn semantic_analysis() {
694 let policy = StringPolicy::from_str("pk()").unwrap();
695 assert_eq!(policy, Policy::Key("".to_owned()));
696 assert_eq!(policy.relative_timelocks(), vec![]);
697 assert_eq!(policy.absolute_timelocks(), vec![]);
698 assert_eq!(policy.clone().at_age(Sequence::ZERO), policy.clone());
699 assert_eq!(
700 policy.clone().at_age(Sequence::from_height(10000)),
701 policy.clone()
702 );
703 assert_eq!(policy.n_keys(), 1);
704 assert_eq!(policy.minimum_n_keys(), Some(1));
705
706 let policy = StringPolicy::from_str("older(1000)").unwrap();
707 assert_eq!(policy, Policy::Older(Sequence::from_height(1000)));
708 assert_eq!(policy.absolute_timelocks(), vec![]);
709 assert_eq!(policy.relative_timelocks(), vec![1000]);
710 assert_eq!(policy.clone().at_age(Sequence::ZERO), Policy::Unsatisfiable);
711 assert_eq!(
712 policy.clone().at_age(Sequence::from_height(999)),
713 Policy::Unsatisfiable
714 );
715 assert_eq!(
716 policy.clone().at_age(Sequence::from_height(1000)),
717 policy.clone()
718 );
719 assert_eq!(
720 policy.clone().at_age(Sequence::from_height(10000)),
721 policy.clone()
722 );
723 assert_eq!(policy.n_keys(), 0);
724 assert_eq!(policy.minimum_n_keys(), Some(0));
725
726 let policy = StringPolicy::from_str("or(pk(),older(1000))").unwrap();
727 assert_eq!(
728 policy,
729 Policy::Threshold(
730 1,
731 vec![
732 Policy::Key("".to_owned()),
733 Policy::Older(Sequence::from_height(1000)),
734 ]
735 )
736 );
737 assert_eq!(policy.relative_timelocks(), vec![1000]);
738 assert_eq!(policy.absolute_timelocks(), vec![]);
739 assert_eq!(
740 policy.clone().at_age(Sequence::ZERO),
741 Policy::Key("".to_owned())
742 );
743 assert_eq!(
744 policy.clone().at_age(Sequence::from_height(999)),
745 Policy::Key("".to_owned())
746 );
747 assert_eq!(
748 policy.clone().at_age(Sequence::from_height(1000)),
749 policy.clone().normalized()
750 );
751 assert_eq!(
752 policy.clone().at_age(Sequence::from_height(10000)),
753 policy.clone().normalized()
754 );
755 assert_eq!(policy.n_keys(), 1);
756 assert_eq!(policy.minimum_n_keys(), Some(0));
757
758 let policy = StringPolicy::from_str("or(pk(),UNSATISFIABLE)").unwrap();
759 assert_eq!(
760 policy,
761 Policy::Threshold(1, vec![Policy::Key("".to_owned()), Policy::Unsatisfiable,])
762 );
763 assert_eq!(policy.relative_timelocks(), vec![]);
764 assert_eq!(policy.absolute_timelocks(), vec![]);
765 assert_eq!(policy.n_keys(), 1);
766 assert_eq!(policy.minimum_n_keys(), Some(1));
767
768 let policy = StringPolicy::from_str("and(pk(),UNSATISFIABLE)").unwrap();
769 assert_eq!(
770 policy,
771 Policy::Threshold(2, vec![Policy::Key("".to_owned()), Policy::Unsatisfiable,])
772 );
773 assert_eq!(policy.relative_timelocks(), vec![]);
774 assert_eq!(policy.absolute_timelocks(), vec![]);
775 assert_eq!(policy.n_keys(), 1);
776 assert_eq!(policy.minimum_n_keys(), None);
777
778 let policy = StringPolicy::from_str(
779 "thresh(\
780 2,older(1000),older(10000),older(1000),older(2000),older(2000)\
781 )",
782 )
783 .unwrap();
784 assert_eq!(
785 policy,
786 Policy::Threshold(
787 2,
788 vec![
789 Policy::Older(Sequence::from_height(1000)),
790 Policy::Older(Sequence::from_height(10000)),
791 Policy::Older(Sequence::from_height(1000)),
792 Policy::Older(Sequence::from_height(2000)),
793 Policy::Older(Sequence::from_height(2000)),
794 ]
795 )
796 );
797 assert_eq!(
798 policy.relative_timelocks(),
799 vec![1000, 2000, 10000] );
801
802 let policy = StringPolicy::from_str(
803 "thresh(\
804 2,older(1000),older(10000),older(1000),UNSATISFIABLE,UNSATISFIABLE\
805 )",
806 )
807 .unwrap();
808 assert_eq!(
809 policy,
810 Policy::Threshold(
811 2,
812 vec![
813 Policy::Older(Sequence::from_height(1000)),
814 Policy::Older(Sequence::from_height(10000)),
815 Policy::Older(Sequence::from_height(1000)),
816 Policy::Unsatisfiable,
817 Policy::Unsatisfiable,
818 ]
819 )
820 );
821 assert_eq!(
822 policy.relative_timelocks(),
823 vec![1000, 10000] );
825 assert_eq!(policy.n_keys(), 0);
826 assert_eq!(policy.minimum_n_keys(), Some(0));
827
828 let policy = StringPolicy::from_str("after(1000)").unwrap();
830 assert_eq!(policy, Policy::after(1000));
831 assert_eq!(policy.absolute_timelocks(), vec![1000]);
832 assert_eq!(policy.relative_timelocks(), vec![]);
833 assert_eq!(
834 policy.clone().at_lock_time(LockTime::ZERO),
835 Policy::Unsatisfiable
836 );
837 assert_eq!(
838 policy
839 .clone()
840 .at_lock_time(LockTime::from_height(999).expect("valid block height")),
841 Policy::Unsatisfiable
842 );
843 assert_eq!(
844 policy
845 .clone()
846 .at_lock_time(LockTime::from_height(1000).expect("valid block height")),
847 policy.clone()
848 );
849 assert_eq!(
850 policy
851 .clone()
852 .at_lock_time(LockTime::from_height(10000).expect("valid block height")),
853 policy.clone()
854 );
855 assert_eq!(
857 policy
858 .clone()
859 .at_lock_time(LockTime::from_time(500_000_001).expect("valid timestamp")),
860 Policy::Unsatisfiable
861 );
862 assert_eq!(policy.n_keys(), 0);
863 assert_eq!(policy.minimum_n_keys(), Some(0));
864
865 let policy = StringPolicy::from_str("after(500000010)").unwrap();
867 assert_eq!(policy, Policy::after(500_000_010));
868 assert_eq!(policy.absolute_timelocks(), vec![500_000_010]);
869 assert_eq!(policy.relative_timelocks(), vec![]);
870 assert_eq!(
872 policy.clone().at_lock_time(LockTime::ZERO),
873 Policy::Unsatisfiable
874 );
875 assert_eq!(
876 policy
877 .clone()
878 .at_lock_time(LockTime::from_height(999).expect("valid block height")),
879 Policy::Unsatisfiable
880 );
881 assert_eq!(
882 policy
883 .clone()
884 .at_lock_time(LockTime::from_height(1000).expect("valid block height")),
885 Policy::Unsatisfiable
886 );
887 assert_eq!(
888 policy
889 .clone()
890 .at_lock_time(LockTime::from_height(10000).expect("valid block height")),
891 Policy::Unsatisfiable
892 );
893 assert_eq!(
895 policy
896 .clone()
897 .at_lock_time(LockTime::from_time(500_000_000).expect("valid timestamp")),
898 Policy::Unsatisfiable
899 );
900 assert_eq!(
901 policy
902 .clone()
903 .at_lock_time(LockTime::from_time(500_000_001).expect("valid timestamp")),
904 Policy::Unsatisfiable
905 );
906 assert_eq!(
907 policy
908 .clone()
909 .at_lock_time(LockTime::from_time(500_000_010).expect("valid timestamp")),
910 policy.clone()
911 );
912 assert_eq!(
913 policy
914 .clone()
915 .at_lock_time(LockTime::from_time(500_000_012).expect("valid timestamp")),
916 policy.clone()
917 );
918 assert_eq!(policy.n_keys(), 0);
919 assert_eq!(policy.minimum_n_keys(), Some(0));
920 }
921
922 #[test]
923 fn entailment_liquid_test() {
924 let liquid_pol = StringPolicy::from_str(
926 "or(and(older(4096),thresh(2,pk(A),pk(B),pk(C))),thresh(11,pk(F1),pk(F2),pk(F3),pk(F4),pk(F5),pk(F6),pk(F7),pk(F8),pk(F9),pk(F10),pk(F11),pk(F12),pk(F13),pk(F14)))").unwrap();
927 let master_key = StringPolicy::from_str("and(older(50000000),pk(master))").unwrap();
929 let new_liquid_pol = Policy::Threshold(1, vec![liquid_pol.clone(), master_key]);
930
931 assert!(liquid_pol.clone().entails(new_liquid_pol.clone()).unwrap());
932 assert!(!new_liquid_pol.entails(liquid_pol.clone()).unwrap());
933
934 let backup_policy = StringPolicy::from_str("thresh(2,pk(A),pk(B),pk(C))").unwrap();
936 assert!(!backup_policy
937 .clone()
938 .entails(liquid_pol.clone().at_age(Sequence::from_height(4095)))
939 .unwrap());
940
941 let fed_pol = StringPolicy::from_str("thresh(11,pk(F1),pk(F2),pk(F3),pk(F4),pk(F5),pk(F6),pk(F7),pk(F8),pk(F9),pk(F10),pk(F11),pk(F12),pk(F13),pk(F14))").unwrap();
943 let backup_policy_after_expiry =
944 StringPolicy::from_str("and(older(4096),thresh(2,pk(A),pk(B),pk(C)))").unwrap();
945 assert!(fed_pol.entails(liquid_pol.clone()).unwrap());
946 assert!(backup_policy_after_expiry
947 .entails(liquid_pol.clone())
948 .unwrap());
949 }
950
951 #[test]
952 fn entailment_escrow() {
953 let escrow_pol = StringPolicy::from_str("thresh(2,pk(Alice),pk(Bob),pk(Judge))").unwrap();
955 let auth_alice = StringPolicy::from_str("and(pk(Alice),pk(Judge))").unwrap();
959
960 let control_alice = StringPolicy::from_str("or(pk(Alice),and(pk(Judge),pk(Bob)))").unwrap();
965
966 assert!(auth_alice.entails(escrow_pol.clone()).unwrap());
969 assert!(escrow_pol.entails(control_alice).unwrap());
970
971 let h = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
974 let htlc_pol = StringPolicy::from_str(&format!(
975 "or(and(pk(Alice),older(100)),and(pk(Bob),sha256({})))",
976 h
977 ))
978 .unwrap();
979 let auth_alice = StringPolicy::from_str("and(pk(Alice),older(100))").unwrap();
984
985 let control_alice =
990 StringPolicy::from_str(&format!("or(pk(Alice),sha256({}))", h)).unwrap();
991
992 assert!(auth_alice.entails(htlc_pol.clone()).unwrap());
995 assert!(htlc_pol.entails(control_alice).unwrap());
996 }
997}