logo
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
// Bitcoin Dev Kit
// Written in 2020 by Alekos Filini <alekos.filini@gmail.com>
//
// Copyright (c) 2020-2021 Bitcoin Dev Kit Developers
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.

//! Descriptor policy
//!
//! This module implements the logic to extract and represent the spending policies of a descriptor
//! in a more human-readable format.
//!
//! This is an **EXPERIMENTAL** feature, API and other major changes are expected.
//!
//! ## Example
//!
//! ```
//! # use std::sync::Arc;
//! # use bdk::descriptor::*;
//! # use bdk::bitcoin::secp256k1::Secp256k1;
//! use bdk::descriptor::policy::BuildSatisfaction;
//! let secp = Secp256k1::new();
//! let desc = "wsh(and_v(v:pk(cV3oCth6zxZ1UVsHLnGothsWNsaoxRhC6aeNi5VbSdFpwUkgkEci),or_d(pk(cVMTy7uebJgvFaSBwcgvwk8qn8xSLc97dKow4MBetjrrahZoimm2),older(12960))))";
//!
//! let (extended_desc, key_map) = ExtendedDescriptor::parse_descriptor(&secp, desc)?;
//! println!("{:?}", extended_desc);
//!
//! let signers = Arc::new(key_map.into());
//! let policy = extended_desc.extract_policy(&signers, BuildSatisfaction::None, &secp)?;
//! println!("policy: {}", serde_json::to_string(&policy)?);
//! # Ok::<(), bdk::Error>(())
//! ```

use std::cmp::max;
use std::collections::{BTreeMap, HashSet, VecDeque};
use std::fmt;

use serde::ser::SerializeMap;
use serde::{Serialize, Serializer};

use bitcoin::hashes::*;
use bitcoin::util::bip32::Fingerprint;
use bitcoin::PublicKey;

use miniscript::descriptor::{DescriptorPublicKey, ShInner, SortedMultiVec, WshInner};
use miniscript::{Descriptor, Miniscript, MiniscriptKey, Satisfier, ScriptContext, Terminal};

#[allow(unused_imports)]
use log::{debug, error, info, trace};

use crate::descriptor::ExtractPolicy;
use crate::wallet::signer::{SignerId, SignersContainer};
use crate::wallet::utils::{self, After, Older, SecpCtx};

use super::checksum::get_checksum;
use super::error::Error;
use super::XKeyUtils;
use bitcoin::util::psbt::PartiallySignedTransaction as Psbt;
use miniscript::psbt::PsbtInputSatisfier;

/// Raw public key or extended key fingerprint
#[derive(Debug, Clone, Default, Serialize)]
pub struct PkOrF {
    #[serde(skip_serializing_if = "Option::is_none")]
    pubkey: Option<PublicKey>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pubkey_hash: Option<hash160::Hash>,
    #[serde(skip_serializing_if = "Option::is_none")]
    fingerprint: Option<Fingerprint>,
}

impl PkOrF {
    fn from_key(k: &DescriptorPublicKey, secp: &SecpCtx) -> Self {
        match k {
            DescriptorPublicKey::SinglePub(pubkey) => PkOrF {
                pubkey: Some(pubkey.key),
                ..Default::default()
            },
            DescriptorPublicKey::XPub(xpub) => PkOrF {
                fingerprint: Some(xpub.root_fingerprint(secp)),
                ..Default::default()
            },
        }
    }
}

/// An item that needs to be satisfied
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "UPPERCASE")]
pub enum SatisfiableItem {
    // Leaves
    /// Signature for a raw public key
    Signature(PkOrF),
    /// Signature for an extended key fingerprint
    SignatureKey(PkOrF),
    /// SHA256 preimage hash
    Sha256Preimage {
        /// The digest value
        hash: sha256::Hash,
    },
    /// Double SHA256 preimage hash
    Hash256Preimage {
        /// The digest value
        hash: sha256d::Hash,
    },
    /// RIPEMD160 preimage hash
    Ripemd160Preimage {
        /// The digest value
        hash: ripemd160::Hash,
    },
    /// SHA256 then RIPEMD160 preimage hash
    Hash160Preimage {
        /// The digest value
        hash: hash160::Hash,
    },
    /// Absolute timeclock timestamp
    AbsoluteTimelock {
        /// The timestamp value
        value: u32,
    },
    /// Relative timelock locktime
    RelativeTimelock {
        /// The locktime value
        value: u32,
    },
    /// Multi-signature public keys with threshold count
    Multisig {
        /// The raw public key or extended key fingerprint
        keys: Vec<PkOrF>,
        /// The required threshold count
        threshold: usize,
    },

    // Complex item
    /// Threshold items with threshold count
    Thresh {
        /// The policy items
        items: Vec<Policy>,
        /// The required threshold count
        threshold: usize,
    },
}

impl SatisfiableItem {
    /// Returns whether the [`SatisfiableItem`] is a leaf item
    pub fn is_leaf(&self) -> bool {
        !matches!(
            self,
            SatisfiableItem::Thresh {
                items: _,
                threshold: _,
            }
        )
    }

    /// Returns a unique id for the [`SatisfiableItem`]
    pub fn id(&self) -> String {
        get_checksum(&serde_json::to_string(self).expect("Failed to serialize a SatisfiableItem"))
            .expect("Failed to compute a SatisfiableItem id")
    }
}

fn combinations(vec: &[usize], size: usize) -> Vec<Vec<usize>> {
    assert!(vec.len() >= size);

    let mut answer = Vec::new();

    let mut queue = VecDeque::new();
    for (index, val) in vec.iter().enumerate() {
        let mut new_vec = Vec::with_capacity(size);
        new_vec.push(*val);
        queue.push_back((index, new_vec));
    }

    while let Some((index, vals)) = queue.pop_front() {
        if vals.len() >= size {
            answer.push(vals);
        } else {
            for (new_index, val) in vec.iter().skip(index + 1).enumerate() {
                let mut cloned = vals.clone();
                cloned.push(*val);
                queue.push_front((new_index, cloned));
            }
        }
    }

    answer
}

fn mix<T: Clone>(vec: Vec<Vec<T>>) -> Vec<Vec<T>> {
    if vec.is_empty() || vec.iter().any(Vec::is_empty) {
        return vec![];
    }

    let mut answer = Vec::new();
    let size = vec.len();

    let mut queue = VecDeque::new();
    for i in &vec[0] {
        let mut new_vec = Vec::with_capacity(size);
        new_vec.push(i.clone());
        queue.push_back(new_vec);
    }

    while let Some(vals) = queue.pop_front() {
        if vals.len() >= size {
            answer.push(vals);
        } else {
            let level = vals.len();
            for i in &vec[level] {
                let mut cloned = vals.clone();
                cloned.push(i.clone());
                queue.push_front(cloned);
            }
        }
    }

    answer
}

/// Type for a map of sets of [`Condition`] items keyed by each set's index
pub type ConditionMap = BTreeMap<usize, HashSet<Condition>>;
/// Type for a map of folded sets of [`Condition`] items keyed by a vector of the combined set's indexes
pub type FoldedConditionMap = BTreeMap<Vec<usize>, HashSet<Condition>>;

fn serialize_folded_cond_map<S>(
    input_map: &FoldedConditionMap,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    let mut map = serializer.serialize_map(Some(input_map.len()))?;
    for (k, v) in input_map {
        let k_string = format!("{:?}", k);
        map.serialize_entry(&k_string, v)?;
    }
    map.end()
}

/// Represent if and how much a policy item is satisfied by the wallet's descriptor
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "UPPERCASE")]
pub enum Satisfaction {
    /// Only a partial satisfaction of some kind of threshold policy
    Partial {
        /// Total number of items
        n: usize,
        /// Threshold
        m: usize,
        /// The items that can be satisfied by the descriptor or are satisfied in the PSBT
        items: Vec<usize>,
        #[serde(skip_serializing_if = "Option::is_none")]
        /// Whether the items are sorted in lexicographic order (used by `sortedmulti`)
        sorted: Option<bool>,
        #[serde(skip_serializing_if = "BTreeMap::is_empty")]
        /// Extra conditions that also need to be satisfied
        conditions: ConditionMap,
    },
    /// Can reach the threshold of some kind of threshold policy
    PartialComplete {
        /// Total number of items
        n: usize,
        /// Threshold
        m: usize,
        /// The items that can be satisfied by the descriptor
        items: Vec<usize>,
        #[serde(skip_serializing_if = "Option::is_none")]
        /// Whether the items are sorted in lexicographic order (used by `sortedmulti`)
        sorted: Option<bool>,
        #[serde(
            serialize_with = "serialize_folded_cond_map",
            skip_serializing_if = "BTreeMap::is_empty"
        )]
        /// Extra conditions that also need to be satisfied
        conditions: FoldedConditionMap,
    },

    /// Can satisfy the policy item
    Complete {
        /// Extra conditions that also need to be satisfied
        condition: Condition,
    },
    /// Cannot satisfy or contribute to the policy item
    None,
}

impl Satisfaction {
    /// Returns whether the [`Satisfaction`] is a leaf item
    pub fn is_leaf(&self) -> bool {
        match self {
            Satisfaction::None | Satisfaction::Complete { .. } => true,
            Satisfaction::PartialComplete { .. } | Satisfaction::Partial { .. } => false,
        }
    }

    // add `inner` as one of self's partial items. this only makes sense on partials
    fn add(&mut self, inner: &Satisfaction, inner_index: usize) -> Result<(), PolicyError> {
        match self {
            Satisfaction::None | Satisfaction::Complete { .. } => Err(PolicyError::AddOnLeaf),
            Satisfaction::PartialComplete { .. } => Err(PolicyError::AddOnPartialComplete),
            Satisfaction::Partial {
                n,
                ref mut conditions,
                ref mut items,
                ..
            } => {
                if inner_index >= *n || items.contains(&inner_index) {
                    return Err(PolicyError::IndexOutOfRange(inner_index));
                }

                match inner {
                    // not relevant if not completed yet
                    Satisfaction::None | Satisfaction::Partial { .. } => return Ok(()),
                    Satisfaction::Complete { condition } => {
                        items.push(inner_index);
                        conditions.insert(inner_index, vec![*condition].into_iter().collect());
                    }
                    Satisfaction::PartialComplete {
                        conditions: other_conditions,
                        ..
                    } => {
                        items.push(inner_index);
                        let conditions_set = other_conditions
                            .values()
                            .fold(HashSet::new(), |set, i| set.union(i).cloned().collect());
                        conditions.insert(inner_index, conditions_set);
                    }
                }

                Ok(())
            }
        }
    }

    fn finalize(&mut self) {
        // if partial try to bump it to a partialcomplete
        if let Satisfaction::Partial {
            n,
            m,
            items,
            conditions,
            sorted,
        } = self
        {
            if items.len() >= *m {
                let mut map = BTreeMap::new();
                let indexes = combinations(items, *m);
                // `indexes` at this point is a Vec<Vec<usize>>, with the "n choose k" of items (m of n)
                indexes
                    .into_iter()
                    // .inspect(|x| println!("--- orig --- {:?}", x))
                    // we map each of the combinations of elements into a tuple of ([chosen items], [conditions]). unfortunately, those items have potentially more than one
                    // condition (think about ORs), so we also use `mix` to expand those, i.e. [[0], [1, 2]] becomes [[0, 1], [0, 2]]. This is necessary to make sure that we
                    // consider every possible options and check whether or not they are compatible.
                    .map(|i_vec| {
                        mix(i_vec
                            .iter()
                            .map(|i| {
                                conditions
                                    .get(i)
                                    .map(|set| set.clone().into_iter().collect())
                                    .unwrap_or_default()
                            })
                            .collect())
                        .into_iter()
                        .map(|x| (i_vec.clone(), x))
                        .collect::<Vec<(Vec<usize>, Vec<Condition>)>>()
                    })
                    // .inspect(|x: &Vec<(Vec<usize>, Vec<Condition>)>| println!("fetch {:?}", x))
                    // since the previous step can turn one item of the iterator into multiple ones, we call flatten to expand them out
                    .flatten()
                    // .inspect(|x| println!("flat {:?}", x))
                    // try to fold all the conditions for this specific combination of indexes/options. if they are not compatible, try_fold will be Err
                    .map(|(key, val)| {
                        (
                            key,
                            val.into_iter()
                                .try_fold(Condition::default(), |acc, v| acc.merge(&v)),
                        )
                    })
                    // .inspect(|x| println!("try_fold {:?}", x))
                    // filter out all the incompatible combinations
                    .filter(|(_, val)| val.is_ok())
                    // .inspect(|x| println!("filter {:?}", x))
                    // push them into the map
                    .for_each(|(key, val)| {
                        map.entry(key)
                            .or_insert_with(HashSet::new)
                            .insert(val.unwrap());
                    });
                // TODO: if the map is empty, the conditions are not compatible, return an error?
                *self = Satisfaction::PartialComplete {
                    n: *n,
                    m: *m,
                    items: items.clone(),
                    conditions: map,
                    sorted: *sorted,
                };
            }
        }
    }
}

impl From<bool> for Satisfaction {
    fn from(other: bool) -> Self {
        if other {
            Satisfaction::Complete {
                condition: Default::default(),
            }
        } else {
            Satisfaction::None
        }
    }
}

/// Descriptor spending policy
#[derive(Debug, Clone, Serialize)]
pub struct Policy {
    /// Identifier for this policy node
    pub id: String,

    /// Type of this policy node
    #[serde(flatten)]
    pub item: SatisfiableItem,
    /// How much a given PSBT already satisfies this policy node in terms of signatures
    pub satisfaction: Satisfaction,
    /// How the wallet's descriptor can satisfy this policy node
    pub contribution: Satisfaction,
}

/// An extra condition that must be satisfied but that is out of control of the user
#[derive(Hash, Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Default, Serialize)]
pub struct Condition {
    /// Optional CheckSequenceVerify condition
    #[serde(skip_serializing_if = "Option::is_none")]
    pub csv: Option<u32>,
    /// Optional timelock condition
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timelock: Option<u32>,
}

impl Condition {
    fn merge_nlocktime(a: u32, b: u32) -> Result<u32, PolicyError> {
        if (a < utils::BLOCKS_TIMELOCK_THRESHOLD) != (b < utils::BLOCKS_TIMELOCK_THRESHOLD) {
            Err(PolicyError::MixedTimelockUnits)
        } else {
            Ok(max(a, b))
        }
    }

    fn merge_nsequence(a: u32, b: u32) -> Result<u32, PolicyError> {
        let mask = utils::SEQUENCE_LOCKTIME_TYPE_FLAG | utils::SEQUENCE_LOCKTIME_MASK;

        let a = a & mask;
        let b = b & mask;

        if (a < utils::SEQUENCE_LOCKTIME_TYPE_FLAG) != (b < utils::SEQUENCE_LOCKTIME_TYPE_FLAG) {
            Err(PolicyError::MixedTimelockUnits)
        } else {
            Ok(max(a, b))
        }
    }

    pub(crate) fn merge(mut self, other: &Condition) -> Result<Self, PolicyError> {
        match (self.csv, other.csv) {
            (Some(a), Some(b)) => self.csv = Some(Self::merge_nsequence(a, b)?),
            (None, any) => self.csv = any,
            _ => {}
        }

        match (self.timelock, other.timelock) {
            (Some(a), Some(b)) => self.timelock = Some(Self::merge_nlocktime(a, b)?),
            (None, any) => self.timelock = any,
            _ => {}
        }

        Ok(self)
    }

    /// Returns `true` if there are no extra conditions to verify
    pub fn is_null(&self) -> bool {
        self.csv.is_none() && self.timelock.is_none()
    }
}

/// Errors that can happen while extracting and manipulating policies
#[derive(Debug, PartialEq, Eq)]
pub enum PolicyError {
    /// Not enough items are selected to satisfy a [`SatisfiableItem::Thresh`] or a [`SatisfiableItem::Multisig`]
    NotEnoughItemsSelected(String),
    /// Index out of range for an item to satisfy a [`SatisfiableItem::Thresh`] or a [`SatisfiableItem::Multisig`]
    IndexOutOfRange(usize),
    /// Can not add to an item that is [`Satisfaction::None`] or [`Satisfaction::Complete`]
    AddOnLeaf,
    /// Can not add to an item that is [`Satisfaction::PartialComplete`]
    AddOnPartialComplete,
    /// Can not merge CSV or timelock values unless both are less than or both are equal or greater than 500_000_000
    MixedTimelockUnits,
    /// Incompatible conditions (not currently used)
    IncompatibleConditions,
}

impl fmt::Display for PolicyError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl std::error::Error for PolicyError {}

impl Policy {
    fn new(item: SatisfiableItem) -> Self {
        Policy {
            id: item.id(),
            item,
            satisfaction: Satisfaction::None,
            contribution: Satisfaction::None,
        }
    }

    fn make_and(a: Option<Policy>, b: Option<Policy>) -> Result<Option<Policy>, PolicyError> {
        match (a, b) {
            (None, None) => Ok(None),
            (Some(x), None) | (None, Some(x)) => Ok(Some(x)),
            (Some(a), Some(b)) => Self::make_thresh(vec![a, b], 2),
        }
    }

    fn make_or(a: Option<Policy>, b: Option<Policy>) -> Result<Option<Policy>, PolicyError> {
        match (a, b) {
            (None, None) => Ok(None),
            (Some(x), None) | (None, Some(x)) => Ok(Some(x)),
            (Some(a), Some(b)) => Self::make_thresh(vec![a, b], 1),
        }
    }

    fn make_thresh(items: Vec<Policy>, threshold: usize) -> Result<Option<Policy>, PolicyError> {
        if threshold == 0 {
            return Ok(None);
        }

        let mut contribution = Satisfaction::Partial {
            n: items.len(),
            m: threshold,
            items: vec![],
            conditions: Default::default(),
            sorted: None,
        };
        let mut satisfaction = contribution.clone();
        for (index, item) in items.iter().enumerate() {
            contribution.add(&item.contribution, index)?;
            satisfaction.add(&item.satisfaction, index)?;
        }

        contribution.finalize();
        satisfaction.finalize();

        let mut policy: Policy = SatisfiableItem::Thresh { items, threshold }.into();
        policy.contribution = contribution;
        policy.satisfaction = satisfaction;

        Ok(Some(policy))
    }

    fn make_multisig(
        keys: &[DescriptorPublicKey],
        signers: &SignersContainer,
        build_sat: BuildSatisfaction,
        threshold: usize,
        sorted: bool,
        secp: &SecpCtx,
    ) -> Result<Option<Policy>, PolicyError> {
        if threshold == 0 {
            return Ok(None);
        }

        let parsed_keys = keys.iter().map(|k| PkOrF::from_key(k, secp)).collect();

        let mut contribution = Satisfaction::Partial {
            n: keys.len(),
            m: threshold,
            items: vec![],
            conditions: Default::default(),
            sorted: Some(sorted),
        };
        let mut satisfaction = contribution.clone();

        for (index, key) in keys.iter().enumerate() {
            if signers.find(signer_id(key, secp)).is_some() {
                contribution.add(
                    &Satisfaction::Complete {
                        condition: Default::default(),
                    },
                    index,
                )?;
            }

            if let Some(psbt) = build_sat.psbt() {
                if signature_in_psbt(psbt, key, secp) {
                    satisfaction.add(
                        &Satisfaction::Complete {
                            condition: Default::default(),
                        },
                        index,
                    )?;
                }
            }
        }
        satisfaction.finalize();
        contribution.finalize();

        let mut policy: Policy = SatisfiableItem::Multisig {
            keys: parsed_keys,
            threshold,
        }
        .into();
        policy.contribution = contribution;
        policy.satisfaction = satisfaction;

        Ok(Some(policy))
    }

    /// Return whether or not a specific path in the policy tree is required to unambiguously
    /// create a transaction
    ///
    /// What this means is that for some spending policies the user should select which paths in
    /// the tree it intends to satisfy while signing, because the transaction must be created differently based
    /// on that.
    pub fn requires_path(&self) -> bool {
        self.get_condition(&BTreeMap::new()).is_err()
    }

    /// Return the conditions that are set by the spending policy for a given path in the
    /// policy tree
    pub fn get_condition(
        &self,
        path: &BTreeMap<String, Vec<usize>>,
    ) -> Result<Condition, PolicyError> {
        // if items.len() == threshold, selected can be omitted and we take all of them by default
        let default = match &self.item {
            SatisfiableItem::Thresh { items, threshold } if items.len() == *threshold => {
                (0..*threshold).collect()
            }
            SatisfiableItem::Multisig { keys, .. } => (0..keys.len()).collect(),
            _ => vec![],
        };
        let selected = match path.get(&self.id) {
            Some(arr) => arr,
            _ => &default,
        };

        match &self.item {
            SatisfiableItem::Thresh { items, threshold } => {
                let mapped_req = items
                    .iter()
                    .map(|i| i.get_condition(path))
                    .collect::<Result<Vec<_>, _>>()?;

                // if all the requirements are null we don't care about `selected` because there
                // are no requirements
                if mapped_req.iter().all(Condition::is_null) {
                    return Ok(Condition::default());
                }

                // if we have something, make sure we have enough items. note that the user can set
                // an empty value for this step in case of n-of-n, because `selected` is set to all
                // the elements above
                if selected.len() < *threshold {
                    return Err(PolicyError::NotEnoughItemsSelected(self.id.clone()));
                }

                // check the selected items, see if there are conflicting requirements
                let mut requirements = Condition::default();
                for item_index in selected {
                    requirements = requirements.merge(
                        mapped_req
                            .get(*item_index)
                            .ok_or(PolicyError::IndexOutOfRange(*item_index))?,
                    )?;
                }

                Ok(requirements)
            }
            SatisfiableItem::Multisig { keys, threshold } => {
                if selected.len() < *threshold {
                    return Err(PolicyError::NotEnoughItemsSelected(self.id.clone()));
                }
                if let Some(item) = selected.iter().find(|i| **i >= keys.len()) {
                    return Err(PolicyError::IndexOutOfRange(*item));
                }

                Ok(Condition::default())
            }
            SatisfiableItem::AbsoluteTimelock { value } => Ok(Condition {
                csv: None,
                timelock: Some(*value),
            }),
            SatisfiableItem::RelativeTimelock { value } => Ok(Condition {
                csv: Some(*value),
                timelock: None,
            }),
            _ => Ok(Condition::default()),
        }
    }
}

impl From<SatisfiableItem> for Policy {
    fn from(other: SatisfiableItem) -> Self {
        Self::new(other)
    }
}

fn signer_id(key: &DescriptorPublicKey, secp: &SecpCtx) -> SignerId {
    match key {
        DescriptorPublicKey::SinglePub(pubkey) => pubkey.key.to_pubkeyhash().into(),
        DescriptorPublicKey::XPub(xpub) => xpub.root_fingerprint(secp).into(),
    }
}

fn signature(
    key: &DescriptorPublicKey,
    signers: &SignersContainer,
    build_sat: BuildSatisfaction,
    secp: &SecpCtx,
) -> Policy {
    let mut policy: Policy = SatisfiableItem::Signature(PkOrF::from_key(key, secp)).into();

    policy.contribution = if signers.find(signer_id(key, secp)).is_some() {
        Satisfaction::Complete {
            condition: Default::default(),
        }
    } else {
        Satisfaction::None
    };

    if let Some(psbt) = build_sat.psbt() {
        policy.satisfaction = if signature_in_psbt(psbt, key, secp) {
            Satisfaction::Complete {
                condition: Default::default(),
            }
        } else {
            Satisfaction::None
        };
    }

    policy
}

fn signature_in_psbt(psbt: &Psbt, key: &DescriptorPublicKey, secp: &SecpCtx) -> bool {
    //TODO check signature validity
    psbt.inputs.iter().all(|input| match key {
        DescriptorPublicKey::SinglePub(key) => input.partial_sigs.contains_key(&key.key),
        DescriptorPublicKey::XPub(xpub) => {
            let pubkey = input
                .bip32_derivation
                .iter()
                .find(|(_, (f, _))| *f == xpub.root_fingerprint(secp))
                .map(|(p, _)| p);
            //TODO check actual derivation matches
            match pubkey {
                Some(pubkey) => input.partial_sigs.contains_key(pubkey),
                None => false,
            }
        }
    })
}

impl<Ctx: ScriptContext> ExtractPolicy for Miniscript<DescriptorPublicKey, Ctx> {
    fn extract_policy(
        &self,
        signers: &SignersContainer,
        build_sat: BuildSatisfaction,
        secp: &SecpCtx,
    ) -> Result<Option<Policy>, Error> {
        Ok(match &self.node {
            // Leaves
            Terminal::True | Terminal::False => None,
            Terminal::PkK(pubkey) => Some(signature(pubkey, signers, build_sat, secp)),
            Terminal::PkH(pubkey_hash) => Some(signature(pubkey_hash, signers, build_sat, secp)),
            Terminal::After(value) => {
                let mut policy: Policy = SatisfiableItem::AbsoluteTimelock { value: *value }.into();
                policy.contribution = Satisfaction::Complete {
                    condition: Condition {
                        timelock: Some(*value),
                        csv: None,
                    },
                };
                if let BuildSatisfaction::PsbtTimelocks {
                    current_height,
                    psbt,
                    ..
                } = build_sat
                {
                    let after = After::new(Some(current_height), false);
                    let after_sat = Satisfier::<bitcoin::PublicKey>::check_after(&after, *value);
                    let inputs_sat = psbt_inputs_sat(psbt)
                        .all(|sat| Satisfier::<bitcoin::PublicKey>::check_after(&sat, *value));
                    if after_sat && inputs_sat {
                        policy.satisfaction = policy.contribution.clone();
                    }
                }

                Some(policy)
            }
            Terminal::Older(value) => {
                let mut policy: Policy = SatisfiableItem::RelativeTimelock { value: *value }.into();
                policy.contribution = Satisfaction::Complete {
                    condition: Condition {
                        timelock: None,
                        csv: Some(*value),
                    },
                };
                if let BuildSatisfaction::PsbtTimelocks {
                    current_height,
                    input_max_height,
                    psbt,
                } = build_sat
                {
                    let older = Older::new(Some(current_height), Some(input_max_height), false);
                    let older_sat = Satisfier::<bitcoin::PublicKey>::check_older(&older, *value);
                    let inputs_sat = psbt_inputs_sat(psbt)
                        .all(|sat| Satisfier::<bitcoin::PublicKey>::check_older(&sat, *value));
                    if older_sat && inputs_sat {
                        policy.satisfaction = policy.contribution.clone();
                    }
                }

                Some(policy)
            }
            Terminal::Sha256(hash) => Some(SatisfiableItem::Sha256Preimage { hash: *hash }.into()),
            Terminal::Hash256(hash) => {
                Some(SatisfiableItem::Hash256Preimage { hash: *hash }.into())
            }
            Terminal::Ripemd160(hash) => {
                Some(SatisfiableItem::Ripemd160Preimage { hash: *hash }.into())
            }
            Terminal::Hash160(hash) => {
                Some(SatisfiableItem::Hash160Preimage { hash: *hash }.into())
            }
            Terminal::Multi(k, pks) => {
                Policy::make_multisig(pks, signers, build_sat, *k, false, secp)?
            }
            // Identities
            Terminal::Alt(inner)
            | Terminal::Swap(inner)
            | Terminal::Check(inner)
            | Terminal::DupIf(inner)
            | Terminal::Verify(inner)
            | Terminal::NonZero(inner)
            | Terminal::ZeroNotEqual(inner) => inner.extract_policy(signers, build_sat, secp)?,
            // Complex policies
            Terminal::AndV(a, b) | Terminal::AndB(a, b) => Policy::make_and(
                a.extract_policy(signers, build_sat, secp)?,
                b.extract_policy(signers, build_sat, secp)?,
            )?,
            Terminal::AndOr(x, y, z) => Policy::make_or(
                Policy::make_and(
                    x.extract_policy(signers, build_sat, secp)?,
                    y.extract_policy(signers, build_sat, secp)?,
                )?,
                z.extract_policy(signers, build_sat, secp)?,
            )?,
            Terminal::OrB(a, b)
            | Terminal::OrD(a, b)
            | Terminal::OrC(a, b)
            | Terminal::OrI(a, b) => Policy::make_or(
                a.extract_policy(signers, build_sat, secp)?,
                b.extract_policy(signers, build_sat, secp)?,
            )?,
            Terminal::Thresh(k, nodes) => {
                let mut threshold = *k;
                let mapped: Vec<_> = nodes
                    .iter()
                    .map(|n| n.extract_policy(signers, build_sat, secp))
                    .collect::<Result<Vec<_>, _>>()?
                    .into_iter()
                    .flatten()
                    .collect();

                if mapped.len() < nodes.len() {
                    threshold = match threshold.checked_sub(nodes.len() - mapped.len()) {
                        None => return Ok(None),
                        Some(x) => x,
                    };
                }

                Policy::make_thresh(mapped, threshold)?
            }
        })
    }
}

fn psbt_inputs_sat(psbt: &Psbt) -> impl Iterator<Item = PsbtInputSatisfier> {
    (0..psbt.inputs.len()).map(move |i| PsbtInputSatisfier::new(psbt, i))
}

/// Options to build the satisfaction field in the policy
#[derive(Debug, Clone, Copy)]
pub enum BuildSatisfaction<'a> {
    /// Don't generate `satisfaction` field
    None,
    /// Analyze the given PSBT to check for existing signatures
    Psbt(&'a Psbt),
    /// Like `Psbt` variant and also check for expired timelocks
    PsbtTimelocks {
        /// Given PSBT
        psbt: &'a Psbt,
        /// Current blockchain height
        current_height: u32,
        /// The highest confirmation height between the inputs
        /// CSV should consider different inputs, but we consider the worst condition for the tx as whole
        input_max_height: u32,
    },
}
impl<'a> BuildSatisfaction<'a> {
    fn psbt(&self) -> Option<&'a Psbt> {
        match self {
            BuildSatisfaction::None => None,
            BuildSatisfaction::Psbt(psbt) => Some(psbt),
            BuildSatisfaction::PsbtTimelocks { psbt, .. } => Some(psbt),
        }
    }
}

impl ExtractPolicy for Descriptor<DescriptorPublicKey> {
    fn extract_policy(
        &self,
        signers: &SignersContainer,
        build_sat: BuildSatisfaction,
        secp: &SecpCtx,
    ) -> Result<Option<Policy>, Error> {
        fn make_sortedmulti<Ctx: ScriptContext>(
            keys: &SortedMultiVec<DescriptorPublicKey, Ctx>,
            signers: &SignersContainer,
            build_sat: BuildSatisfaction,
            secp: &SecpCtx,
        ) -> Result<Option<Policy>, Error> {
            Ok(Policy::make_multisig(
                keys.pks.as_ref(),
                signers,
                build_sat,
                keys.k,
                true,
                secp,
            )?)
        }

        match self {
            Descriptor::Pkh(pk) => Ok(Some(signature(pk.as_inner(), signers, build_sat, secp))),
            Descriptor::Wpkh(pk) => Ok(Some(signature(pk.as_inner(), signers, build_sat, secp))),
            Descriptor::Sh(sh) => match sh.as_inner() {
                ShInner::Wpkh(pk) => Ok(Some(signature(pk.as_inner(), signers, build_sat, secp))),
                ShInner::Ms(ms) => Ok(ms.extract_policy(signers, build_sat, secp)?),
                ShInner::SortedMulti(ref keys) => make_sortedmulti(keys, signers, build_sat, secp),
                ShInner::Wsh(wsh) => match wsh.as_inner() {
                    WshInner::Ms(ms) => Ok(ms.extract_policy(signers, build_sat, secp)?),
                    WshInner::SortedMulti(ref keys) => {
                        make_sortedmulti(keys, signers, build_sat, secp)
                    }
                },
            },
            Descriptor::Wsh(wsh) => match wsh.as_inner() {
                WshInner::Ms(ms) => Ok(ms.extract_policy(signers, build_sat, secp)?),
                WshInner::SortedMulti(ref keys) => make_sortedmulti(keys, signers, build_sat, secp),
            },
            Descriptor::Bare(ms) => Ok(ms.as_inner().extract_policy(signers, build_sat, secp)?),
        }
    }
}

#[cfg(test)]
mod test {
    use crate::descriptor;
    use crate::descriptor::{ExtractPolicy, IntoWalletDescriptor};

    use super::*;
    use crate::descriptor::derived::AsDerived;
    use crate::descriptor::policy::SatisfiableItem::{Multisig, Signature, Thresh};
    use crate::keys::{DescriptorKey, IntoDescriptorKey};
    use crate::wallet::signer::SignersContainer;
    use bitcoin::secp256k1::Secp256k1;
    use bitcoin::util::bip32;
    use bitcoin::Network;
    use miniscript::DescriptorTrait;
    use std::str::FromStr;
    use std::sync::Arc;

    const TPRV0_STR:&str = "tprv8ZgxMBicQKsPdZXrcHNLf5JAJWFAoJ2TrstMRdSKtEggz6PddbuSkvHKM9oKJyFgZV1B7rw8oChspxyYbtmEXYyg1AjfWbL3ho3XHDpHRZf";
    const TPRV1_STR:&str = "tprv8ZgxMBicQKsPdpkqS7Eair4YxjcuuvDPNYmKX3sCniCf16tHEVrjjiSXEkFRnUH77yXc6ZcwHHcLNfjdi5qUvw3VDfgYiH5mNsj5izuiu2N";

    const PATH: &str = "m/44'/1'/0'/0";

    fn setup_keys<Ctx: ScriptContext>(
        tprv: &str,
        path: &str,
        secp: &SecpCtx,
    ) -> (DescriptorKey<Ctx>, DescriptorKey<Ctx>, Fingerprint) {
        let path = bip32::DerivationPath::from_str(path).unwrap();
        let tprv = bip32::ExtendedPrivKey::from_str(tprv).unwrap();
        let tpub = bip32::ExtendedPubKey::from_private(secp, &tprv);
        let fingerprint = tprv.fingerprint(secp);
        let prvkey = (tprv, path.clone()).into_descriptor_key().unwrap();
        let pubkey = (tpub, path).into_descriptor_key().unwrap();

        (prvkey, pubkey, fingerprint)
    }

    // test ExtractPolicy trait for simple descriptors; wpkh(), sh(multi())

    #[test]
    fn test_extract_policy_for_wpkh() {
        let secp = Secp256k1::new();

        let (prvkey, pubkey, fingerprint) = setup_keys(TPRV0_STR, PATH, &secp);
        let desc = descriptor!(wpkh(pubkey)).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Signature(pk_or_f) if pk_or_f.fingerprint.unwrap() == fingerprint)
        );
        assert!(matches!(&policy.contribution, Satisfaction::None));

        let desc = descriptor!(wpkh(prvkey)).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Signature(pk_or_f) if pk_or_f.fingerprint.unwrap() == fingerprint)
        );
        assert!(
            matches!(&policy.contribution, Satisfaction::Complete {condition} if condition.csv == None && condition.timelock == None)
        );
    }

    // 2 pub keys descriptor, required 2 prv keys
    #[test]
    fn test_extract_policy_for_sh_multi_partial_0of2() {
        let secp = Secp256k1::new();
        let (_prvkey0, pubkey0, fingerprint0) = setup_keys(TPRV0_STR, PATH, &secp);
        let (_prvkey1, pubkey1, fingerprint1) = setup_keys(TPRV1_STR, PATH, &secp);
        let desc = descriptor!(sh(multi(2, pubkey0, pubkey1))).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Multisig { keys, threshold } if threshold == &2usize
            && keys[0].fingerprint.unwrap() == fingerprint0
            && keys[1].fingerprint.unwrap() == fingerprint1)
        );
        // TODO should this be "Satisfaction::None" since we have no prv keys?
        // TODO should items and conditions not be empty?
        assert!(
            matches!(&policy.contribution, Satisfaction::Partial { n, m, items, conditions, ..} if n == &2usize
            && m == &2usize
            && items.is_empty()
            && conditions.is_empty()
            )
        );
    }

    // 1 prv and 1 pub key descriptor, required 2 prv keys
    #[test]
    fn test_extract_policy_for_sh_multi_partial_1of2() {
        let secp = Secp256k1::new();
        let (prvkey0, _pubkey0, fingerprint0) = setup_keys(TPRV0_STR, PATH, &secp);
        let (_prvkey1, pubkey1, fingerprint1) = setup_keys(TPRV1_STR, PATH, &secp);
        let desc = descriptor!(sh(multi(2, prvkey0, pubkey1))).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();
        assert!(
            matches!(&policy.item, Multisig { keys, threshold } if threshold == &2usize
            && keys[0].fingerprint.unwrap() == fingerprint0
            && keys[1].fingerprint.unwrap() == fingerprint1)
        );

        assert!(
            matches!(&policy.contribution, Satisfaction::Partial { n, m, items, conditions, ..} if n == &2usize
             && m == &2usize
             && items.len() == 1
             && conditions.contains_key(&0)
            )
        );
    }

    // 1 prv and 1 pub key descriptor, required 1 prv keys
    #[test]
    #[ignore] // see https://github.com/bitcoindevkit/bdk/issues/225
    fn test_extract_policy_for_sh_multi_complete_1of2() {
        let secp = Secp256k1::new();

        let (_prvkey0, pubkey0, fingerprint0) = setup_keys(TPRV0_STR, PATH, &secp);
        let (prvkey1, _pubkey1, fingerprint1) = setup_keys(TPRV1_STR, PATH, &secp);
        let desc = descriptor!(sh(multi(1, pubkey0, prvkey1))).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Multisig { keys, threshold } if threshold == &1
            && keys[0].fingerprint.unwrap() == fingerprint0
            && keys[1].fingerprint.unwrap() == fingerprint1)
        );
        assert!(
            matches!(&policy.contribution, Satisfaction::PartialComplete { n, m, items, conditions, .. } if n == &2
             && m == &1
             && items.len() == 2
             && conditions.contains_key(&vec![0])
             && conditions.contains_key(&vec![1])
            )
        );
    }

    // 2 prv keys descriptor, required 2 prv keys
    #[test]
    fn test_extract_policy_for_sh_multi_complete_2of2() {
        let secp = Secp256k1::new();

        let (prvkey0, _pubkey0, fingerprint0) = setup_keys(TPRV0_STR, PATH, &secp);
        let (prvkey1, _pubkey1, fingerprint1) = setup_keys(TPRV1_STR, PATH, &secp);
        let desc = descriptor!(sh(multi(2, prvkey0, prvkey1))).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Multisig { keys, threshold } if threshold == &2
            && keys[0].fingerprint.unwrap() == fingerprint0
            && keys[1].fingerprint.unwrap() == fingerprint1)
        );

        assert!(
            matches!(&policy.contribution, Satisfaction::PartialComplete { n, m, items, conditions, .. } if n == &2
             && m == &2
             && items.len() == 2
             && conditions.contains_key(&vec![0,1])
            )
        );
    }

    // test ExtractPolicy trait with extended and single keys

    #[test]
    fn test_extract_policy_for_single_wpkh() {
        let secp = Secp256k1::new();

        let (prvkey, pubkey, fingerprint) = setup_keys(TPRV0_STR, PATH, &secp);
        let desc = descriptor!(wpkh(pubkey)).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let single_key = wallet_desc.derive(0);
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = single_key
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Signature(pk_or_f) if pk_or_f.fingerprint.unwrap() == fingerprint)
        );
        assert!(matches!(&policy.contribution, Satisfaction::None));

        let desc = descriptor!(wpkh(prvkey)).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let single_key = wallet_desc.derive(0);
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = single_key
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Signature(pk_or_f) if pk_or_f.fingerprint.unwrap() == fingerprint)
        );
        assert!(
            matches!(&policy.contribution, Satisfaction::Complete {condition} if condition.csv == None && condition.timelock == None)
        );
    }

    // single key, 1 prv and 1 pub key descriptor, required 1 prv keys
    #[test]
    #[ignore] // see https://github.com/bitcoindevkit/bdk/issues/225
    fn test_extract_policy_for_single_wsh_multi_complete_1of2() {
        let secp = Secp256k1::new();

        let (_prvkey0, pubkey0, fingerprint0) = setup_keys(TPRV0_STR, PATH, &secp);
        let (prvkey1, _pubkey1, fingerprint1) = setup_keys(TPRV1_STR, PATH, &secp);
        let desc = descriptor!(sh(multi(1, pubkey0, prvkey1))).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let single_key = wallet_desc.derive(0);
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = single_key
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Multisig { keys, threshold } if threshold == &1
            && keys[0].fingerprint.unwrap() == fingerprint0
            && keys[1].fingerprint.unwrap() == fingerprint1)
        );
        assert!(
            matches!(&policy.contribution, Satisfaction::PartialComplete { n, m, items, conditions, .. } if n == &2
             && m == &1
             && items.len() == 2
             && conditions.contains_key(&vec![0])
             && conditions.contains_key(&vec![1])
            )
        );
    }

    // test ExtractPolicy trait with descriptors containing timelocks in a thresh()

    #[test]
    #[ignore] // see https://github.com/bitcoindevkit/bdk/issues/225
    fn test_extract_policy_for_wsh_multi_timelock() {
        let secp = Secp256k1::new();

        let (prvkey0, _pubkey0, _fingerprint0) = setup_keys(TPRV0_STR, PATH, &secp);
        let (_prvkey1, pubkey1, _fingerprint1) = setup_keys(TPRV1_STR, PATH, &secp);
        let sequence = 50;
        #[rustfmt::skip]
        let desc = descriptor!(wsh(thresh(
            2,
            pk(prvkey0),
            s:pk(pubkey1),
            s:d:v:older(sequence)
        )))
        .unwrap();

        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        assert!(
            matches!(&policy.item, Thresh { items, threshold } if items.len() == 3 && threshold == &2)
        );

        assert!(
            matches!(&policy.contribution, Satisfaction::PartialComplete { n, m, items, conditions, .. } if n == &3
             && m == &2
             && items.len() == 3
             && conditions.get(&vec![0,1]).unwrap().iter().next().unwrap().csv.is_none()
             && conditions.get(&vec![0,2]).unwrap().iter().next().unwrap().csv == Some(sequence)
             && conditions.get(&vec![1,2]).unwrap().iter().next().unwrap().csv == Some(sequence)
            )
        );
    }

    // - mixed timelocks should fail

    #[test]
    #[ignore]
    fn test_extract_policy_for_wsh_mixed_timelocks() {
        let secp = Secp256k1::new();
        let (prvkey0, _pubkey0, _fingerprint0) = setup_keys(TPRV0_STR, PATH, &secp);
        let locktime_threshold = 500000000; // if less than this means block number, else block time in seconds
        let locktime_blocks = 100;
        let locktime_seconds = locktime_blocks + locktime_threshold;
        let desc = descriptor!(sh(and_v(
            v: pk(prvkey0),
            and_v(v: after(locktime_seconds), after(locktime_blocks))
        )))
        .unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();
        println!("desc policy = {:?}", policy); // TODO remove
                                                // TODO how should this fail with mixed timelocks?
    }

    // - multiple timelocks of the same type should be correctly merged together
    #[test]
    #[ignore]
    fn test_extract_policy_for_multiple_same_timelocks() {
        let secp = Secp256k1::new();
        let (prvkey0, _pubkey0, _fingerprint0) = setup_keys(TPRV0_STR, PATH, &secp);
        let locktime_blocks0 = 100;
        let locktime_blocks1 = 200;
        let desc = descriptor!(sh(and_v(
            v: pk(prvkey0),
            and_v(v: after(locktime_blocks0), after(locktime_blocks1))
        )))
        .unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();
        println!("desc policy = {:?}", policy); // TODO remove
                                                // TODO how should this merge timelocks?
        let (prvkey1, _pubkey1, _fingerprint1) = setup_keys(TPRV0_STR, PATH, &secp);
        let locktime_seconds0 = 500000100;
        let locktime_seconds1 = 500000200;
        let desc = descriptor!(sh(and_v(
            v: pk(prvkey1),
            and_v(v: after(locktime_seconds0), after(locktime_seconds1))
        )))
        .unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));
        let policy = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        println!("desc policy = {:?}", policy); // TODO remove

        // TODO how should this merge timelocks?
    }

    #[test]
    fn test_get_condition_multisig() {
        let secp = Secp256k1::new();

        let (_, pk0, _) = setup_keys(TPRV0_STR, PATH, &secp);
        let (_, pk1, _) = setup_keys(TPRV1_STR, PATH, &secp);

        let desc = descriptor!(wsh(multi(1, pk0, pk1))).unwrap();
        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers = keymap.into();

        let policy = wallet_desc
            .extract_policy(&signers, BuildSatisfaction::None, &secp)
            .unwrap()
            .unwrap();

        // no args, choose the default
        let no_args = policy.get_condition(&vec![].into_iter().collect());
        assert_eq!(no_args, Ok(Condition::default()));

        // enough args
        let eq_thresh =
            policy.get_condition(&vec![(policy.id.clone(), vec![0])].into_iter().collect());
        assert_eq!(eq_thresh, Ok(Condition::default()));

        // more args, it doesn't really change anything
        let gt_thresh =
            policy.get_condition(&vec![(policy.id.clone(), vec![0, 1])].into_iter().collect());
        assert_eq!(gt_thresh, Ok(Condition::default()));

        // not enough args, error
        let lt_thresh =
            policy.get_condition(&vec![(policy.id.clone(), vec![])].into_iter().collect());
        assert_eq!(
            lt_thresh,
            Err(PolicyError::NotEnoughItemsSelected(policy.id.clone()))
        );

        // index out of range
        let out_of_range =
            policy.get_condition(&vec![(policy.id.clone(), vec![5])].into_iter().collect());
        assert_eq!(out_of_range, Err(PolicyError::IndexOutOfRange(5)));
    }

    const ALICE_TPRV_STR:&str = "tprv8ZgxMBicQKsPf6T5X327efHnvJDr45Xnb8W4JifNWtEoqXu9MRYS4v1oYe6DFcMVETxy5w3bqpubYRqvcVTqovG1LifFcVUuJcbwJwrhYzP";
    const BOB_TPRV_STR:&str = "tprv8ZgxMBicQKsPeinZ155cJAn117KYhbaN6MV3WeG6sWhxWzcvX1eg1awd4C9GpUN1ncLEM2rzEvunAg3GizdZD4QPPCkisTz99tXXB4wZArp";
    const CAROL_TPRV_STR:&str = "tprv8ZgxMBicQKsPdC3CicFifuLCEyVVdXVUNYorxUWj3iGZ6nimnLAYAY9SYB7ib8rKzRxrCKFcEytCt6szwd2GHnGPRCBLAEAoSVDefSNk4Bt";
    const ALICE_BOB_PATH: &str = "m/0'";

    #[test]
    fn test_extract_satisfaction() {
        const ALICE_SIGNED_PSBT: &str = "cHNidP8BAFMBAAAAAZb0njwT2wRS3AumaaP3yb7T4MxOePpSWih4Nq+jWChMAQAAAAD/////Af4lAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASuJJgAAAAAAACIAIERw5kTLo9DUH9QDJSClHQwPpC7VGJ+ZMDpa8U+2fzcYIgIDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZstHMEQCIBj0jLjUeVYXNQ6cqB+gbtvuKMjV54wSgWlm1cfcgpHVAiBa3DtC9l/1Mt4IDCvR7mmwQd3eAP/m5++81euhJNSrgQEBBUdSIQN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmyyEC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhSriIGAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIDBwu7j4AAACAAAAAACIGA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLDMkRfC4AAACAAAAAAAAA";
        const BOB_SIGNED_PSBT: &str =   "cHNidP8BAFMBAAAAAZb0njwT2wRS3AumaaP3yb7T4MxOePpSWih4Nq+jWChMAQAAAAD/////Af4lAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASuJJgAAAAAAACIAIERw5kTLo9DUH9QDJSClHQwPpC7VGJ+ZMDpa8U+2fzcYIgIC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhIMEUCIQD5zDtM5MwklurwJ5aW76RsO36Iqyu+6uMdVlhL6ws2GQIgesAiz4dbKS7UmhDsC/c1ezu0o6hp00UUtsCMfUZ4anYBAQVHUiEDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZsshAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIUq4iBgL4YT/L4um0jzGaJHqw5733wgbPJujHRB/Pj4FCXWeZiAwcLu4+AAAAgAAAAAAiBgN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmywzJEXwuAAAAgAAAAAAAAA==";
        const ALICE_BOB_SIGNED_PSBT: &str =   "cHNidP8BAFMBAAAAAZb0njwT2wRS3AumaaP3yb7T4MxOePpSWih4Nq+jWChMAQAAAAD/////Af4lAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASuJJgAAAAAAACIAIERw5kTLo9DUH9QDJSClHQwPpC7VGJ+ZMDpa8U+2fzcYIgIC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhIMEUCIQD5zDtM5MwklurwJ5aW76RsO36Iqyu+6uMdVlhL6ws2GQIgesAiz4dbKS7UmhDsC/c1ezu0o6hp00UUtsCMfUZ4anYBIgIDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZstHMEQCIBj0jLjUeVYXNQ6cqB+gbtvuKMjV54wSgWlm1cfcgpHVAiBa3DtC9l/1Mt4IDCvR7mmwQd3eAP/m5++81euhJNSrgQEBBUdSIQN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmyyEC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhSriIGAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIDBwu7j4AAACAAAAAACIGA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLDMkRfC4AAACAAAAAAAEHAAEI2wQARzBEAiAY9Iy41HlWFzUOnKgfoG7b7ijI1eeMEoFpZtXH3IKR1QIgWtw7QvZf9TLeCAwr0e5psEHd3gD/5ufvvNXroSTUq4EBSDBFAiEA+cw7TOTMJJbq8CeWlu+kbDt+iKsrvurjHVZYS+sLNhkCIHrAIs+HWyku1JoQ7Av3NXs7tKOoadNFFLbAjH1GeGp2AUdSIQN4C2NhCT9V+7h1vb7ryHIwqNzfz6RaXmw/lAfwvjZmyyEC+GE/y+LptI8xmiR6sOe998IGzybox0Qfz4+BQl1nmYhSrgAA";

        let secp = Secp256k1::new();

        let (prvkey_alice, _, _) = setup_keys(ALICE_TPRV_STR, ALICE_BOB_PATH, &secp);
        let (prvkey_bob, _, _) = setup_keys(BOB_TPRV_STR, ALICE_BOB_PATH, &secp);

        let desc = descriptor!(wsh(multi(2, prvkey_alice, prvkey_bob))).unwrap();

        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();

        let addr = wallet_desc
            .as_derived(0, &secp)
            .address(Network::Testnet)
            .unwrap();
        assert_eq!(
            "tb1qg3cwv3xt50gdg875qvjjpfgaps86gtk4rz0ejvp6ttc5ldnlxuvqlcn0xk",
            addr.to_string()
        );

        let signers_container = Arc::new(SignersContainer::from(keymap));

        let psbt = Psbt::from_str(ALICE_SIGNED_PSBT).unwrap();

        let policy_alice_psbt = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::Psbt(&psbt), &secp)
            .unwrap()
            .unwrap();
        //println!("{}", serde_json::to_string(&policy_alice_psbt).unwrap());

        assert!(
            matches!(&policy_alice_psbt.satisfaction, Satisfaction::Partial { n, m, items, .. } if n == &2
             && m == &2
             && items == &vec![0]
            )
        );

        let psbt = Psbt::from_str(BOB_SIGNED_PSBT).unwrap();
        let policy_bob_psbt = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::Psbt(&psbt), &secp)
            .unwrap()
            .unwrap();
        //println!("{}", serde_json::to_string(&policy_bob_psbt).unwrap());

        assert!(
            matches!(&policy_bob_psbt.satisfaction, Satisfaction::Partial { n, m, items, .. } if n == &2
             && m == &2
             && items == &vec![1]
            )
        );

        let psbt = Psbt::from_str(ALICE_BOB_SIGNED_PSBT).unwrap();
        let policy_alice_bob_psbt = wallet_desc
            .extract_policy(&signers_container, BuildSatisfaction::Psbt(&psbt), &secp)
            .unwrap()
            .unwrap();
        assert!(
            matches!(&policy_alice_bob_psbt.satisfaction, Satisfaction::PartialComplete { n, m, items, .. } if n == &2
             && m == &2
             && items == &vec![0, 1]
            )
        );
    }

    #[test]
    fn test_extract_satisfaction_timelock() {
        //const PSBT_POLICY_CONSIDER_TIMELOCK_NOT_EXPIRED: &str = "cHNidP8BAFMBAAAAAdld52uJFGT7Yde0YZdSVh2vL020Zm2exadH5R4GSNScAAAAAAD/////ATrcAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASvI3AAAAAAAACIAILhzvvcBzw/Zfnc9ispRK0PCahxn1F6RHXTZAmw5tqNPAQVSdmNSsmlofCEDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42Zsusk3whAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIrJNShyIGAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIDBwu7j4AAACAAAAAACIGA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLDMkRfC4AAACAAAAAAAAA";
        const PSBT_POLICY_CONSIDER_TIMELOCK_EXPIRED:     &str = "cHNidP8BAFMCAAAAAdld52uJFGT7Yde0YZdSVh2vL020Zm2exadH5R4GSNScAAAAAAACAAAAATrcAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASvI3AAAAAAAACIAILhzvvcBzw/Zfnc9ispRK0PCahxn1F6RHXTZAmw5tqNPAQVSdmNSsmlofCEDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42Zsusk3whAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIrJNShyIGAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIDBwu7j4AAACAAAAAACIGA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLDMkRfC4AAACAAAAAAAAA";
        const PSBT_POLICY_CONSIDER_TIMELOCK_EXPIRED_SIGNED: &str ="cHNidP8BAFMCAAAAAdld52uJFGT7Yde0YZdSVh2vL020Zm2exadH5R4GSNScAAAAAAACAAAAATrcAAAAAAAAF6kUXv2Fn+YemPP4PUpNR1ZbU16/eRCHAAAAAAABASvI3AAAAAAAACIAILhzvvcBzw/Zfnc9ispRK0PCahxn1F6RHXTZAmw5tqNPIgIDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42ZstIMEUCIQCtZxNm6H3Ux3pnc64DSpgohMdBj+57xhFHcURYt2BpPAIgG3OnI7bcj/3GtWX1HHyYGSI7QGa/zq5YnsmK1Cw29NABAQVSdmNSsmlofCEDeAtjYQk/Vfu4db2+68hyMKjc38+kWl5sP5QH8L42Zsusk3whAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIrJNShyIGAvhhP8vi6bSPMZokerDnvffCBs8m6MdEH8+PgUJdZ5mIDBwu7j4AAACAAAAAACIGA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLDMkRfC4AAACAAAAAAAEHAAEIoAQASDBFAiEArWcTZuh91Md6Z3OuA0qYKITHQY/ue8YRR3FEWLdgaTwCIBtzpyO23I/9xrVl9Rx8mBkiO0Bmv86uWJ7JitQsNvTQAQEBUnZjUrJpaHwhA3gLY2EJP1X7uHW9vuvIcjCo3N/PpFpebD+UB/C+NmbLrJN8IQL4YT/L4um0jzGaJHqw5733wgbPJujHRB/Pj4FCXWeZiKyTUocAAA==";

        let secp = Secp256k1::new();

        let (prvkey_alice, _, _) = setup_keys(ALICE_TPRV_STR, ALICE_BOB_PATH, &secp);
        let (prvkey_bob, _, _) = setup_keys(BOB_TPRV_STR, ALICE_BOB_PATH, &secp);

        let desc =
            descriptor!(wsh(thresh(2,d:v:older(2),s:pk(prvkey_alice),s:pk(prvkey_bob)))).unwrap();

        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));

        let addr = wallet_desc
            .as_derived(0, &secp)
            .address(Network::Testnet)
            .unwrap();
        assert_eq!(
            "tb1qhpemaacpeu8ajlnh8k9v55ftg0px58r8630fz8t5mypxcwdk5d8sum522g",
            addr.to_string()
        );

        let psbt = Psbt::from_str(PSBT_POLICY_CONSIDER_TIMELOCK_EXPIRED).unwrap();

        let build_sat = BuildSatisfaction::PsbtTimelocks {
            psbt: &psbt,
            current_height: 10,
            input_max_height: 9,
        };

        let policy = wallet_desc
            .extract_policy(&signers_container, build_sat, &secp)
            .unwrap()
            .unwrap();
        assert!(
            matches!(&policy.satisfaction, Satisfaction::Partial { n, m, items, .. } if n == &3
             && m == &2
             && items.is_empty()
            )
        );
        //println!("{}", serde_json::to_string(&policy).unwrap());

        let build_sat_expired = BuildSatisfaction::PsbtTimelocks {
            psbt: &psbt,
            current_height: 12,
            input_max_height: 9,
        };

        let policy_expired = wallet_desc
            .extract_policy(&signers_container, build_sat_expired, &secp)
            .unwrap()
            .unwrap();
        assert!(
            matches!(&policy_expired.satisfaction, Satisfaction::Partial { n, m, items, .. } if n == &3
             && m == &2
             && items == &vec![0]
            )
        );
        //println!("{}", serde_json::to_string(&policy_expired).unwrap());

        let psbt_signed = Psbt::from_str(PSBT_POLICY_CONSIDER_TIMELOCK_EXPIRED_SIGNED).unwrap();

        let build_sat_expired_signed = BuildSatisfaction::PsbtTimelocks {
            psbt: &psbt_signed,
            current_height: 12,
            input_max_height: 9,
        };

        let policy_expired_signed = wallet_desc
            .extract_policy(&signers_container, build_sat_expired_signed, &secp)
            .unwrap()
            .unwrap();
        assert!(
            matches!(&policy_expired_signed.satisfaction, Satisfaction::PartialComplete { n, m, items, .. } if n == &3
             && m == &2
             && items == &vec![0, 1]
            )
        );
        //println!("{}", serde_json::to_string(&policy_expired_signed).unwrap());
    }

    #[test]
    fn test_extract_pkh() {
        let secp = Secp256k1::new();

        let (prvkey_alice, _, _) = setup_keys(ALICE_TPRV_STR, ALICE_BOB_PATH, &secp);
        let (prvkey_bob, _, _) = setup_keys(BOB_TPRV_STR, ALICE_BOB_PATH, &secp);
        let (prvkey_carol, _, _) = setup_keys(CAROL_TPRV_STR, ALICE_BOB_PATH, &secp);

        let desc = descriptor!(wsh(c: andor(
            pk(prvkey_alice),
            pk_k(prvkey_bob),
            pk_h(prvkey_carol),
        )))
        .unwrap();

        let (wallet_desc, keymap) = desc
            .into_wallet_descriptor(&secp, Network::Testnet)
            .unwrap();
        let signers_container = Arc::new(SignersContainer::from(keymap));

        let policy = wallet_desc.extract_policy(&signers_container, BuildSatisfaction::None, &secp);
        assert!(policy.is_ok());
    }
}