Skip to content

Commit f2de24b

Browse files
Merge pull request #99 from Foundation-Devices/SFT-6076
SFT-6076: Sort multisig descriptor keys.
2 parents ef53556 + 8119f1d commit f2de24b

File tree

3 files changed

+25
-2
lines changed

3 files changed

+25
-2
lines changed

src/psbt.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use bdk_wallet::bitcoin::{
1919
};
2020
use bdk_wallet::descriptor::ExtendedDescriptor;
2121
use bdk_wallet::keys::{DescriptorPublicKey, SinglePub, SinglePubKey};
22+
use std::cmp::Ordering;
2223
use std::collections::{BTreeMap, HashSet};
2324
use thiserror::Error;
2425

@@ -850,3 +851,19 @@ where
850851
key: SinglePubKey::FullKey(derived_xpub.to_pub().into()),
851852
})
852853
}
854+
855+
pub(crate) fn sort_keys(keys: &mut [DescriptorPublicKey]) {
856+
fn to_public_key(pk: &DescriptorPublicKey) -> Option<PublicKey> {
857+
match pk {
858+
DescriptorPublicKey::XPub(xpub) => Some(xpub.xkey.public_key),
859+
_ => None,
860+
}
861+
}
862+
863+
keys.sort_by(|a, b| {
864+
to_public_key(a)
865+
.and_then(|a| to_public_key(b).map(|b| (a.serialize(), b.serialize())))
866+
.map(|(a, b)| a.cmp(&b))
867+
.unwrap_or(Ordering::Equal)
868+
});
869+
}

src/psbt/p2sh.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::bip32::NgAccountPath;
22
use crate::psbt::{
3-
Error, OutputKind, PsbtOutput, derive_account_xpub, derive_full_descriptor_pubkey,
3+
Error, OutputKind, PsbtOutput, derive_account_xpub, derive_full_descriptor_pubkey, sort_keys,
44
};
55
use bdk_wallet::bitcoin::bip32::{ChildNumber, DerivationPath, KeySource, Xpriv, Xpub};
66
use bdk_wallet::bitcoin::psbt;
@@ -224,6 +224,9 @@ pub fn wsh_multisig_descriptor(
224224
internal_keys.push(internal_key);
225225
}
226226

227+
sort_keys(&mut external_keys);
228+
sort_keys(&mut internal_keys);
229+
227230
let external_descriptor =
228231
ExtendedDescriptor::new_sh_wsh_sortedmulti(usize::from(required_signers), external_keys)
229232
.unwrap();

src/psbt/p2wsh.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::bip32::NgAccountPath;
2-
use crate::psbt::{Error, OutputKind, PsbtOutput};
2+
use crate::psbt::{Error, OutputKind, PsbtOutput, sort_keys};
33
use bdk_wallet::bitcoin::bip32::{ChildNumber, DerivationPath, KeySource, Xpub};
44
use bdk_wallet::bitcoin::psbt;
55
use bdk_wallet::bitcoin::secp256k1::PublicKey;
@@ -140,6 +140,9 @@ pub fn multisig_descriptor(
140140
internal_keys.push(internal_key);
141141
}
142142

143+
sort_keys(&mut external_keys);
144+
sort_keys(&mut internal_keys);
145+
143146
let external_descriptor =
144147
ExtendedDescriptor::new_wsh_sortedmulti(usize::from(required_signers), external_keys)
145148
.unwrap();

0 commit comments

Comments
 (0)