Skip to content

Commit f38b2e5

Browse files
committed
Refactor DescriptorPublicKey::derive method
There is no need to mutate the `self` variable, doing so makes the code subjectively harder to read. Refactor the `derive` method to not use mutable variables.
1 parent dcc9d0f commit f38b2e5

File tree

1 file changed

+27
-17
lines changed

1 file changed

+27
-17
lines changed

src/descriptor/key.rs

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -435,28 +435,38 @@ impl DescriptorPublicKey {
435435
}
436436
}
437437

438-
/// If this public key has a wildcard, replace it by the given index
438+
/// Derives the [`DescriptorPublicKey`] at `index` if this key is an xpub and has a wildcard.
439439
///
440-
/// Panics if given an index ≥ 2^31
441-
pub fn derive(mut self, index: u32) -> DescriptorPublicKey {
442-
if let DescriptorPublicKey::XPub(mut xpub) = self {
443-
match xpub.wildcard {
444-
Wildcard::None => {}
445-
Wildcard::Unhardened => {
446-
xpub.derivation_path = xpub
440+
/// # Returns
441+
///
442+
/// - If this key is not an xpub, returns `self`.
443+
/// - If this key is an xpub but does not have a wildcard, returns `self`.
444+
/// - Otherwise, returns the derived xpub at `index` (removing the wildcard).
445+
///
446+
/// # Panics
447+
///
448+
/// If `index` ≥ 2^31
449+
pub fn derive(self, index: u32) -> DescriptorPublicKey {
450+
match self {
451+
DescriptorPublicKey::SinglePub(_) => self,
452+
DescriptorPublicKey::XPub(xpub) => {
453+
let derivation_path = match xpub.wildcard {
454+
Wildcard::None => xpub.derivation_path,
455+
Wildcard::Unhardened => xpub
447456
.derivation_path
448-
.into_child(bip32::ChildNumber::from_normal_idx(index).unwrap())
449-
}
450-
Wildcard::Hardened => {
451-
xpub.derivation_path = xpub
457+
.into_child(bip32::ChildNumber::from_normal_idx(index).unwrap()),
458+
Wildcard::Hardened => xpub
452459
.derivation_path
453-
.into_child(bip32::ChildNumber::from_hardened_idx(index).unwrap())
454-
}
460+
.into_child(bip32::ChildNumber::from_hardened_idx(index).unwrap()),
461+
};
462+
DescriptorPublicKey::XPub(DescriptorXKey {
463+
origin: xpub.origin,
464+
xkey: xpub.xkey,
465+
derivation_path: derivation_path,
466+
wildcard: Wildcard::None,
467+
})
455468
}
456-
xpub.wildcard = Wildcard::None;
457-
self = DescriptorPublicKey::XPub(xpub);
458469
}
459-
self
460470
}
461471

462472
/// Computes the public key corresponding to this descriptor key.

0 commit comments

Comments
 (0)