Skip to content

Commit ca3282c

Browse files
committed
key: fix DefiniteDescriptorKey construction from key with hardened step
Our current API allows constructing a DefiniteDescriptorKey with hardened steps, which means that you can't actually derive a public key. However, the point of this type is to provide a DescriptorPublicKey which implements the ToPublicKey trait. This is a backport, so it introduces the `has_hardened_steps` helper function but does *not* make it pub, in the interest of avoiding gratuitious API changes.
1 parent b54a0b3 commit ca3282c

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

src/descriptor/key.rs

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -610,6 +610,23 @@ impl DescriptorPublicKey {
610610
}
611611
}
612612

613+
/// Whether or not the key has a wildcard
614+
pub fn has_hardened_step(&self) -> bool {
615+
let paths = match self {
616+
DescriptorPublicKey::Single(..) => &[],
617+
DescriptorPublicKey::XPub(xpub) => core::slice::from_ref(&xpub.derivation_path),
618+
DescriptorPublicKey::MultiXPub(xpub) => &xpub.derivation_paths.paths()[..],
619+
};
620+
for p in paths {
621+
for step in p.into_iter() {
622+
if step.is_hardened() {
623+
return true;
624+
}
625+
}
626+
}
627+
false
628+
}
629+
613630
#[deprecated(note = "use at_derivation_index instead")]
614631
/// Deprecated name for [`Self::at_derivation_index`].
615632
pub fn derive(self, index: u32) -> Result<DefiniteDescriptorKey, ConversionError> {
@@ -1038,7 +1055,7 @@ impl DefiniteDescriptorKey {
10381055
///
10391056
/// Returns `None` if the key contains a wildcard
10401057
fn new(key: DescriptorPublicKey) -> Option<Self> {
1041-
if key.has_wildcard() || key.is_multipath() {
1058+
if key.has_wildcard() || key.is_multipath() || key.has_hardened_step() {
10421059
None
10431060
} else {
10441061
Some(Self(key))
@@ -1072,7 +1089,7 @@ impl FromStr for DefiniteDescriptorKey {
10721089
fn from_str(s: &str) -> Result<Self, Self::Err> {
10731090
let inner = DescriptorPublicKey::from_str(s)?;
10741091
DefiniteDescriptorKey::new(inner).ok_or(DescriptorKeyParseError(
1075-
"cannot parse multi-path keys or keys with a wilcard as a DerivedDescriptorKey",
1092+
"cannot parse multi-path keys, keys with a wildcard or keys with hardened derivation steps as a DerivedDescriptorKey",
10761093
))
10771094
}
10781095
}
@@ -1517,5 +1534,10 @@ mod test {
15171534
.parse::<DescriptorPublicKey>()
15181535
.unwrap();
15191536
assert!(DefiniteDescriptorKey::new(desc).is_none());
1537+
// xpub with hardened path
1538+
let desc = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/1'/2"
1539+
.parse::<DescriptorPublicKey>()
1540+
.unwrap();
1541+
assert!(DefiniteDescriptorKey::new(desc).is_none());
15201542
}
15211543
}

0 commit comments

Comments
 (0)