Skip to content

Commit ac76ce0

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 b9dea66 commit ac76ce0

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
@@ -607,6 +607,23 @@ impl DescriptorPublicKey {
607607
}
608608
}
609609

610+
/// Whether or not the key has a wildcard
611+
pub fn has_hardened_step(&self) -> bool {
612+
let paths = match self {
613+
DescriptorPublicKey::Single(..) => &[],
614+
DescriptorPublicKey::XPub(xpub) => core::slice::from_ref(&xpub.derivation_path),
615+
DescriptorPublicKey::MultiXPub(xpub) => &xpub.derivation_paths.paths()[..],
616+
};
617+
for p in paths {
618+
for step in p.into_iter() {
619+
if step.is_hardened() {
620+
return true;
621+
}
622+
}
623+
}
624+
false
625+
}
626+
610627
#[deprecated(note = "use at_derivation_index instead")]
611628
/// Deprecated name for [`Self::at_derivation_index`].
612629
pub fn derive(self, index: u32) -> Result<DefiniteDescriptorKey, ConversionError> {
@@ -1055,7 +1072,7 @@ impl DefiniteDescriptorKey {
10551072
///
10561073
/// Returns `None` if the key contains a wildcard
10571074
fn new(key: DescriptorPublicKey) -> Option<Self> {
1058-
if key.has_wildcard() || key.is_multipath() {
1075+
if key.has_wildcard() || key.is_multipath() || key.has_hardened_step() {
10591076
None
10601077
} else {
10611078
Some(Self(key))
@@ -1089,7 +1106,7 @@ impl FromStr for DefiniteDescriptorKey {
10891106
fn from_str(s: &str) -> Result<Self, Self::Err> {
10901107
let inner = DescriptorPublicKey::from_str(s)?;
10911108
DefiniteDescriptorKey::new(inner).ok_or(DescriptorKeyParseError(
1092-
"cannot parse multi-path keys or keys with a wilcard as a DerivedDescriptorKey",
1109+
"cannot parse multi-path keys, keys with a wildcard or keys with hardened derivation steps as a DerivedDescriptorKey",
10931110
))
10941111
}
10951112
}
@@ -1587,5 +1604,10 @@ mod test {
15871604
.parse::<DescriptorPublicKey>()
15881605
.unwrap();
15891606
assert!(DefiniteDescriptorKey::new(desc).is_none());
1607+
// xpub with hardened path
1608+
let desc = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8/1'/2"
1609+
.parse::<DescriptorPublicKey>()
1610+
.unwrap();
1611+
assert!(DefiniteDescriptorKey::new(desc).is_none());
15901612
}
15911613
}

0 commit comments

Comments
 (0)