Skip to content

Commit 6c96ddc

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 de74dc0 commit 6c96ddc

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
@@ -431,28 +431,38 @@ impl DescriptorPublicKey {
431431
}
432432
}
433433

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

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

0 commit comments

Comments
 (0)