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

Fix None derivation path index for custom currencies #464

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 20 additions & 4 deletions crates/cdk/src/mint/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -590,10 +590,7 @@ fn create_new_keyset<C: secp256k1::Signing>(
}

fn derivation_path_from_unit(unit: CurrencyUnit, index: u32) -> Option<DerivationPath> {
let unit_index = match unit.derivation_index() {
Some(index) => index,
None => return None,
};
let unit_index = unit.derivation_index();

Some(DerivationPath::from(vec![
ChildNumber::from_hardened_idx(0).expect("0 is a valid index"),
Expand Down Expand Up @@ -698,6 +695,25 @@ mod tests {
assert_eq!(amounts_and_pubkeys, expected_amounts_and_pubkeys);
}

#[test]
fn mint_mod_derivation_path_from_unit() {
// Test valid cases
let test_cases = vec![
(CurrencyUnit::Sat, 0, "0'/0'/0'"),
(CurrencyUnit::Usd, 21, "0'/2'/21'"),
(
CurrencyUnit::Custom("DOGE".to_string(), 69),
420,
"0'/69'/420'",
),
];

for (unit, index, expected) in test_cases {
let path = derivation_path_from_unit(unit, index).unwrap();
assert_eq!(path.to_string(), expected);
}
}

use cdk_database::mint_memory::MintMemoryDatabase;

#[derive(Default)]
Expand Down
118 changes: 103 additions & 15 deletions crates/cdk/src/nuts/nut00/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,45 +374,69 @@ pub enum CurrencyUnit {
/// Euro
Eur,
/// Custom currency unit
Custom(String),
Custom(String, u32),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would lead to the derivation path being included in the token I believe.

Copy link
Contributor Author

@vnprc vnprc Nov 20, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you mean in the ecash token? Is this a problem?

edit: guessing it's a problem because it's not in the spec so other mints using other implementations will not know how to handle these tokens

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since the serialize/deserialize implementation just use to/from string internally and this modifies those to include or expect the derivation path when the token (cashuB...) get serialized/desrialized it would include or expect the path.

}

impl CurrencyUnit {
/// Constructor for `CurrencyUnit::Custom`
pub fn new_custom(name: String, index: u32) -> Result<Self, String> {
if (0..=3).contains(&index) {
Err(format!(
"Index {} is reserved and cannot be used for custom currency units.",
index
))
} else {
Ok(Self::Custom(name, index))
}
}
}

#[cfg(feature = "mint")]
impl CurrencyUnit {
/// Derivation index mint will use for unit
pub fn derivation_index(&self) -> Option<u32> {
pub fn derivation_index(&self) -> u32 {
match self {
Self::Sat => Some(0),
Self::Msat => Some(1),
Self::Usd => Some(2),
Self::Eur => Some(3),
_ => None,
Self::Sat => 0,
Self::Msat => 1,
Self::Usd => 2,
Self::Eur => 3,
Self::Custom(_, index) => *index,
}
}
}

impl FromStr for CurrencyUnit {
type Err = Error;
fn from_str(value: &str) -> Result<Self, Self::Err> {
let value = &value.to_uppercase();
match value.as_str() {
// Split on ':' to check for derivation index
let parts: Vec<&str> = value.split(':').collect();
let currency = parts[0].to_uppercase();

match currency.as_str() {
Comment on lines +415 to +419
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can't assume that we get the unit in this form it is not in the spec.

"SAT" => Ok(Self::Sat),
"MSAT" => Ok(Self::Msat),
"USD" => Ok(Self::Usd),
"EUR" => Ok(Self::Eur),
c => Ok(Self::Custom(c.to_string())),
c => {
// Require explicit index for custom currencies
if parts.len() != 2 {
return Err(Error::UnsupportedUnit);
}
let index = parts[1].parse().map_err(|_| Error::UnsupportedUnit)?;
Ok(Self::Custom(c.to_string(), index))
}
}
}
}

impl fmt::Display for CurrencyUnit {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
CurrencyUnit::Sat => "SAT",
CurrencyUnit::Msat => "MSAT",
CurrencyUnit::Usd => "USD",
CurrencyUnit::Eur => "EUR",
CurrencyUnit::Custom(unit) => unit,
CurrencyUnit::Sat => "SAT".to_string(),
CurrencyUnit::Msat => "MSAT".to_string(),
CurrencyUnit::Usd => "USD".to_string(),
CurrencyUnit::Eur => "EUR".to_string(),
CurrencyUnit::Custom(unit, index) => format!("{}:{}", unit, index),
};
if let Some(width) = f.width() {
write!(f, "{:width$}", s.to_lowercase(), width = width)
Expand Down Expand Up @@ -763,4 +787,68 @@ mod tests {
.unwrap();
assert_eq!(b.len(), 1);
}

#[test]
fn test_currency_unit_from_str() {
// Standard currencies
assert_eq!(CurrencyUnit::from_str("SAT").unwrap(), CurrencyUnit::Sat);
assert_eq!(CurrencyUnit::from_str("sat").unwrap(), CurrencyUnit::Sat);
assert_eq!(CurrencyUnit::from_str("MSAT").unwrap(), CurrencyUnit::Msat);
assert_eq!(CurrencyUnit::from_str("msat").unwrap(), CurrencyUnit::Msat);
assert_eq!(CurrencyUnit::from_str("USD").unwrap(), CurrencyUnit::Usd);
assert_eq!(CurrencyUnit::from_str("usd").unwrap(), CurrencyUnit::Usd);
assert_eq!(CurrencyUnit::from_str("EUR").unwrap(), CurrencyUnit::Eur);
assert_eq!(CurrencyUnit::from_str("eur").unwrap(), CurrencyUnit::Eur);

// Custom currency
assert_eq!(
CurrencyUnit::from_str("GBP:1001").unwrap(),
CurrencyUnit::Custom("GBP".to_string(), 1001)
);

assert!(CurrencyUnit::from_str("GBP").is_err());
assert!(CurrencyUnit::from_str("GBP:").is_err());
assert!(CurrencyUnit::from_str("GBP:abc").is_err());
}

#[test]
fn test_currency_unit_display() {
// Standard currencies
assert_eq!(CurrencyUnit::Sat.to_string(), "sat");
assert_eq!(CurrencyUnit::Msat.to_string(), "msat");
assert_eq!(CurrencyUnit::Usd.to_string(), "usd");
assert_eq!(CurrencyUnit::Eur.to_string(), "eur");

// Custom currency
assert_eq!(
CurrencyUnit::Custom("GBP".to_string(), 1001).to_string(),
"gbp:1001"
);
}

#[test]
fn test_custom_currency_valid_index() {
let valid_index = 5;
let result = CurrencyUnit::new_custom("MyCurrency".to_string(), valid_index);
assert!(result.is_ok());
if let Ok(CurrencyUnit::Custom(name, index)) = result {
assert_eq!(name, "MyCurrency");
assert_eq!(index, valid_index);
}
}

#[test]
fn test_custom_currency_invalid_indexes() {
let invalid_indexes = [0, 1, 2, 3];
for &index in &invalid_indexes {
let result = CurrencyUnit::new_custom("InvalidCurrency".to_string(), index);
assert!(result.is_err(), "Index {} should not be allowed", index);
if let Err(err) = result {
assert!(
err.contains(&index.to_string()),
"Error message should mention the invalid index"
);
}
}
}
}
Loading