Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve XprivAccount APIs #36

Merged
merged 9 commits into from
Aug 26, 2024
26 changes: 26 additions & 0 deletions derive/src/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ use std::str::FromStr;
/// is treated as hardened
pub const HARDENED_INDEX_BOUNDARY: u32 = 1 << 31;

#[macro_export]
macro_rules! h {
($idx:literal) => {
HardenedIndex::from($idx as u16)
};
[$( $idx:literal ),+] => {
[$( HardenedIndex::from($idx as u16) ),+]
};
}

#[derive(Copy, Clone, Eq, PartialEq, Debug, Display, Error)]
#[display("provided {what} {invalid} is invalid: it lies outside allowed range {start}..={end}")]
pub struct IndexError {
Expand Down Expand Up @@ -580,3 +590,19 @@ impl FromStr for DerivationIndex {
}
}
}

#[cfg(test)]
mod test {
use super::*;

#[test]
fn macro_h_index() {
assert_eq!(h!(1), HardenedIndex::ONE);
}

#[test]
fn macro_h_path() {
let path = [HardenedIndex::from(86u8), HardenedIndex::from(1u8), HardenedIndex::from(0u8)];
assert_eq!(h![86, 1, 0], path);
}
}
6 changes: 3 additions & 3 deletions derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ pub use taptree::{
TapTreeBuilder, UnfinalizedTree,
};
pub use xkey::{
ChainCode, KeyOrigin, OriginParseError, XkeyDecodeError, XkeyMeta, XkeyOrigin, XkeyParseError,
Xpriv, XprivAccount, XprivCore, Xpub, XpubAccount, XpubCore, XpubDerivable, XpubFp, XpubId,
XPRIV_MAINNET_MAGIC, XPRIV_TESTNET_MAGIC,
ChainCode, KeyOrigin, OriginParseError, XkeyAccountError, XkeyDecodeError, XkeyMeta,
XkeyOrigin, XkeyParseError, Xpriv, XprivAccount, XprivCore, Xpub, XpubAccount, XpubCore,
XpubDerivable, XpubFp, XpubId, XPRIV_MAINNET_MAGIC, XPRIV_TESTNET_MAGIC,
};
6 changes: 6 additions & 0 deletions derive/src/path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,10 @@ where
)]
pub struct DerivationPath<I = DerivationIndex>(Vec<I>);

impl<I: Clone, const LEN: usize> From<[I; LEN]> for DerivationPath<I> {
fn from(path: [I; LEN]) -> Self { Self(path.to_vec()) }
}

impl<I: Clone> From<&[I]> for DerivationPath<I> {
fn from(path: &[I]) -> Self { Self(path.to_vec()) }
}
Expand Down Expand Up @@ -239,6 +243,8 @@ impl<I: Idx> DerivationPath<I> {
/// Constructs empty derivation path.
pub fn new() -> Self { Self(vec![]) }

pub fn with_capacity(capacity: usize) -> Self { Self(Vec::with_capacity(capacity)) }

pub fn terminal(&self) -> Option<Terminal> {
let mut iter = self.iter().rev();
let index = iter.next()?;
Expand Down
Loading
Loading