nut00.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. //! Notation and Models
  2. // https://github.com/cashubtc/nuts/blob/main/00.md
  3. use std::fmt;
  4. use std::hash::{Hash, Hasher};
  5. use std::str::FromStr;
  6. use serde::{Deserialize, Serialize};
  7. use super::{Id, Proofs, PublicKey};
  8. use crate::error::Error;
  9. use crate::secret::Secret;
  10. use crate::url::UncheckedUrl;
  11. use crate::Amount;
  12. /// Blinded Message [NUT-00]
  13. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  14. pub struct BlindedMessage {
  15. /// Amount
  16. pub amount: Amount,
  17. /// Keyset Id
  18. #[serde(rename = "id")]
  19. pub keyset_id: Id,
  20. /// encrypted secret message (B_)
  21. #[serde(rename = "B_")]
  22. pub b: PublicKey,
  23. }
  24. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, Hash)]
  25. #[serde(rename_all = "lowercase")]
  26. pub enum CurrencyUnit {
  27. #[default]
  28. Sat,
  29. Usd,
  30. Custom(String),
  31. }
  32. impl FromStr for CurrencyUnit {
  33. type Err = Error;
  34. fn from_str(s: &str) -> Result<Self, Self::Err> {
  35. match s {
  36. "sat" => Ok(Self::Sat),
  37. "usd" => Ok(Self::Usd),
  38. _ => Ok(Self::Custom(s.to_string())),
  39. }
  40. }
  41. }
  42. impl fmt::Display for CurrencyUnit {
  43. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  44. match self {
  45. CurrencyUnit::Sat => write!(f, "sat"),
  46. CurrencyUnit::Usd => write!(f, "usd"),
  47. CurrencyUnit::Custom(unit) => write!(f, "{}", unit),
  48. }
  49. }
  50. }
  51. #[derive(Default, Deserialize, Serialize, Debug, PartialEq, Eq, Clone, Hash)]
  52. #[serde(rename_all = "lowercase")]
  53. pub enum PaymentMethod {
  54. #[default]
  55. Bolt11,
  56. Custom(String),
  57. }
  58. impl FromStr for PaymentMethod {
  59. type Err = Error;
  60. fn from_str(s: &str) -> Result<Self, Self::Err> {
  61. match s {
  62. "bolt11" => Ok(Self::Bolt11),
  63. _ => Ok(Self::Custom(s.to_string())),
  64. }
  65. }
  66. }
  67. impl fmt::Display for PaymentMethod {
  68. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  69. match self {
  70. PaymentMethod::Bolt11 => write!(f, "bolt11"),
  71. PaymentMethod::Custom(unit) => write!(f, "{}", unit),
  72. }
  73. }
  74. }
  75. #[cfg(feature = "wallet")]
  76. pub mod wallet {
  77. use std::cmp::Ordering;
  78. use std::fmt;
  79. use std::str::FromStr;
  80. use base64::engine::{general_purpose, GeneralPurpose};
  81. use base64::{alphabet, Engine as _};
  82. use bip39::Mnemonic;
  83. use serde::{Deserialize, Serialize};
  84. use url::Url;
  85. use super::{CurrencyUnit, MintProofs};
  86. use crate::dhke::blind_message;
  87. use crate::error::wallet;
  88. use crate::nuts::{BlindedMessage, Id, Proofs, SecretKey};
  89. use crate::secret::Secret;
  90. use crate::url::UncheckedUrl;
  91. use crate::{error, Amount};
  92. #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
  93. pub struct PreMint {
  94. /// Blinded message
  95. pub blinded_message: BlindedMessage,
  96. /// Secret
  97. pub secret: Secret,
  98. /// R
  99. pub r: SecretKey,
  100. /// Amount
  101. pub amount: Amount,
  102. }
  103. impl Ord for PreMint {
  104. fn cmp(&self, other: &Self) -> std::cmp::Ordering {
  105. self.amount.cmp(&other.amount)
  106. }
  107. }
  108. impl PartialOrd for PreMint {
  109. fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
  110. Some(self.cmp(other))
  111. }
  112. }
  113. #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)]
  114. pub struct PreMintSecrets {
  115. secrets: Vec<PreMint>,
  116. }
  117. // Implement Iterator for PreMintSecrets
  118. impl Iterator for PreMintSecrets {
  119. type Item = PreMint;
  120. fn next(&mut self) -> Option<Self::Item> {
  121. // Use the iterator of the vector
  122. self.secrets.pop()
  123. }
  124. }
  125. impl Ord for PreMintSecrets {
  126. fn cmp(&self, other: &Self) -> Ordering {
  127. self.secrets.cmp(&other.secrets)
  128. }
  129. }
  130. impl PartialOrd for PreMintSecrets {
  131. fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
  132. Some(self.cmp(other))
  133. }
  134. }
  135. impl PreMintSecrets {
  136. /// Outputs for speceifed amount with random secret
  137. pub fn random(keyset_id: Id, amount: Amount) -> Result<Self, wallet::Error> {
  138. let amount_split = amount.split();
  139. let mut output = Vec::with_capacity(amount_split.len());
  140. for amount in amount_split {
  141. let secret = Secret::new();
  142. let (blinded, r) = blind_message(secret.as_bytes(), None)?;
  143. let blinded_message = BlindedMessage {
  144. amount,
  145. b: blinded,
  146. keyset_id,
  147. };
  148. output.push(PreMint {
  149. secret,
  150. blinded_message,
  151. r: r.into(),
  152. amount,
  153. });
  154. }
  155. Ok(PreMintSecrets { secrets: output })
  156. }
  157. pub fn from_secrets(
  158. keyset_id: Id,
  159. amounts: Vec<Amount>,
  160. secrets: Vec<Secret>,
  161. ) -> Result<Self, wallet::Error> {
  162. let mut output = Vec::with_capacity(secrets.len());
  163. for (secret, amount) in secrets.into_iter().zip(amounts) {
  164. let (blinded, r) = blind_message(secret.as_bytes(), None)?;
  165. let blinded_message = BlindedMessage {
  166. amount,
  167. b: blinded,
  168. keyset_id,
  169. };
  170. output.push(PreMint {
  171. secret,
  172. blinded_message,
  173. r: r.into(),
  174. amount,
  175. });
  176. }
  177. Ok(PreMintSecrets { secrets: output })
  178. }
  179. /// Blank Outputs used for NUT-08 change
  180. pub fn blank(keyset_id: Id, fee_reserve: Amount) -> Result<Self, wallet::Error> {
  181. let count = ((u64::from(fee_reserve) as f64).log2().ceil() as u64).max(1);
  182. let mut output = Vec::with_capacity(count as usize);
  183. for _i in 0..count {
  184. let secret = Secret::new();
  185. let (blinded, r) = blind_message(secret.as_bytes(), None)?;
  186. let blinded_message = BlindedMessage {
  187. amount: Amount::ZERO,
  188. b: blinded,
  189. keyset_id,
  190. };
  191. output.push(PreMint {
  192. secret,
  193. blinded_message,
  194. r: r.into(),
  195. amount: Amount::ZERO,
  196. })
  197. }
  198. Ok(PreMintSecrets { secrets: output })
  199. }
  200. /// Generate blinded messages from predetermined secrets and blindings
  201. /// factor
  202. /// TODO: Put behind feature
  203. pub fn from_seed(
  204. keyset_id: Id,
  205. counter: u64,
  206. mnemonic: &Mnemonic,
  207. amount: Amount,
  208. ) -> Result<Self, wallet::Error> {
  209. let mut pre_mint_secrets = PreMintSecrets::default();
  210. let mut counter = counter;
  211. for amount in amount.split() {
  212. let secret = Secret::from_seed(mnemonic, keyset_id, counter);
  213. let blinding_factor = SecretKey::from_seed(mnemonic, keyset_id, counter);
  214. let (blinded, r) = blind_message(secret.as_bytes(), Some(blinding_factor.into()))?;
  215. let blinded_message = BlindedMessage {
  216. keyset_id,
  217. amount,
  218. b: blinded,
  219. };
  220. let pre_mint = PreMint {
  221. blinded_message,
  222. secret: secret.clone(),
  223. r: r.into(),
  224. amount: Amount::ZERO,
  225. };
  226. pre_mint_secrets.secrets.push(pre_mint);
  227. counter += 1;
  228. }
  229. Ok(pre_mint_secrets)
  230. }
  231. pub fn iter(&self) -> impl Iterator<Item = &PreMint> {
  232. self.secrets.iter()
  233. }
  234. pub fn len(&self) -> usize {
  235. self.secrets.len()
  236. }
  237. pub fn is_empty(&self) -> bool {
  238. self.secrets.is_empty()
  239. }
  240. pub fn total_amount(&self) -> Amount {
  241. self.secrets
  242. .iter()
  243. .map(|PreMint { amount, .. }| *amount)
  244. .sum()
  245. }
  246. pub fn blinded_messages(&self) -> Vec<BlindedMessage> {
  247. self.iter().map(|pm| pm.blinded_message.clone()).collect()
  248. }
  249. pub fn secrets(&self) -> Vec<Secret> {
  250. self.iter().map(|pm| pm.secret.clone()).collect()
  251. }
  252. pub fn rs(&self) -> Vec<SecretKey> {
  253. self.iter().map(|pm| pm.r.clone()).collect()
  254. }
  255. pub fn amounts(&self) -> Vec<Amount> {
  256. self.iter().map(|pm| pm.amount).collect()
  257. }
  258. pub fn combine(&mut self, mut other: Self) {
  259. self.secrets.append(&mut other.secrets)
  260. }
  261. pub fn sort_secrets(&mut self) {
  262. self.secrets.sort();
  263. }
  264. }
  265. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  266. pub struct Token {
  267. pub token: Vec<MintProofs>,
  268. /// Memo for token
  269. #[serde(skip_serializing_if = "Option::is_none")]
  270. pub memo: Option<String>,
  271. /// Token Unit
  272. #[serde(skip_serializing_if = "Option::is_none")]
  273. pub unit: Option<CurrencyUnit>,
  274. }
  275. impl Token {
  276. pub fn new(
  277. mint_url: UncheckedUrl,
  278. proofs: Proofs,
  279. memo: Option<String>,
  280. unit: Option<CurrencyUnit>,
  281. ) -> Result<Self, wallet::Error> {
  282. if proofs.is_empty() {
  283. return Err(wallet::Error::ProofsRequired);
  284. }
  285. // Check Url is valid
  286. let _: Url = (&mint_url).try_into()?;
  287. Ok(Self {
  288. token: vec![MintProofs::new(mint_url, proofs)],
  289. memo,
  290. unit,
  291. })
  292. }
  293. pub fn token_info(&self) -> (u64, String) {
  294. let mut amount = Amount::ZERO;
  295. for proofs in &self.token {
  296. for proof in &proofs.proofs {
  297. amount += proof.amount;
  298. }
  299. }
  300. (amount.into(), self.token[0].mint.to_string())
  301. }
  302. }
  303. impl FromStr for Token {
  304. type Err = error::wallet::Error;
  305. fn from_str(s: &str) -> Result<Self, Self::Err> {
  306. let s = if s.starts_with("cashuA") {
  307. s.replace("cashuA", "")
  308. } else {
  309. return Err(wallet::Error::UnsupportedToken);
  310. };
  311. let decode_config = general_purpose::GeneralPurposeConfig::new()
  312. .with_decode_padding_mode(base64::engine::DecodePaddingMode::Indifferent);
  313. let decoded = GeneralPurpose::new(&alphabet::STANDARD, decode_config).decode(s)?;
  314. let decoded_str = String::from_utf8(decoded)?;
  315. let token: Token = serde_json::from_str(&decoded_str)?;
  316. Ok(token)
  317. }
  318. }
  319. impl fmt::Display for Token {
  320. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  321. let json_string = serde_json::to_string(self).map_err(|_| fmt::Error)?;
  322. let encoded = general_purpose::STANDARD.encode(json_string);
  323. write!(f, "cashuA{}", encoded)
  324. }
  325. }
  326. }
  327. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  328. pub struct MintProofs {
  329. pub mint: UncheckedUrl,
  330. pub proofs: Proofs,
  331. }
  332. #[cfg(feature = "wallet")]
  333. impl MintProofs {
  334. fn new(mint_url: UncheckedUrl, proofs: Proofs) -> Self {
  335. Self {
  336. mint: mint_url,
  337. proofs,
  338. }
  339. }
  340. }
  341. /// Promise (BlindedSignature) [NUT-00]
  342. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  343. pub struct BlindedSignature {
  344. pub amount: Amount,
  345. /// Keyset Id
  346. #[serde(rename = "id")]
  347. pub keyset_id: Id,
  348. /// blinded signature (C_) on the secret message `B_` of [BlindedMessage]
  349. #[serde(rename = "C_")]
  350. pub c: PublicKey,
  351. }
  352. /// Proofs [NUT-00]
  353. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  354. pub struct Proof {
  355. /// Amount in satoshi
  356. pub amount: Amount,
  357. /// `Keyset id`
  358. #[serde(rename = "id")]
  359. pub keyset_id: Id,
  360. /// Secret message
  361. pub secret: Secret,
  362. /// Unblinded signature
  363. #[serde(rename = "C")]
  364. pub c: PublicKey,
  365. }
  366. impl Hash for Proof {
  367. fn hash<H: Hasher>(&self, state: &mut H) {
  368. self.secret.hash(state);
  369. }
  370. }
  371. impl Ord for Proof {
  372. fn cmp(&self, other: &Self) -> std::cmp::Ordering {
  373. self.amount.cmp(&other.amount)
  374. }
  375. }
  376. impl PartialOrd for Proof {
  377. fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
  378. Some(self.cmp(other))
  379. }
  380. }
  381. #[cfg(test)]
  382. mod tests {
  383. use std::str::FromStr;
  384. use super::wallet::*;
  385. use super::*;
  386. #[test]
  387. fn test_proof_serialize() {
  388. let proof = "[{\"id\":\"009a1f293253e41e\",\"amount\":2,\"secret\":\"407915bc212be61a77e3e6d2aeb4c727980bda51cd06a6afc29e2861768a7837\",\"C\":\"02bc9097997d81afb2cc7346b5e4345a9346bd2a506eb7958598a72f0cf85163ea\"},{\"id\":\"009a1f293253e41e\",\"amount\":8,\"secret\":\"fe15109314e61d7756b0f8ee0f23a624acaa3f4e042f61433c728c7057b931be\",\"C\":\"029e8e5050b890a7d6c0968db16bc1d5d5fa040ea1de284f6ec69d61299f671059\"}]";
  389. let proof: Proofs = serde_json::from_str(proof).unwrap();
  390. assert_eq!(
  391. proof[0].clone().keyset_id,
  392. Id::from_str("009a1f293253e41e").unwrap()
  393. );
  394. assert_eq!(proof.len(), 2);
  395. }
  396. #[test]
  397. fn test_token_str_round_trip() {
  398. let token_str = "cashuAeyJ0b2tlbiI6W3sibWludCI6Imh0dHBzOi8vODMzMy5zcGFjZTozMzM4IiwicHJvb2ZzIjpbeyJhbW91bnQiOjIsImlkIjoiMDA5YTFmMjkzMjUzZTQxZSIsInNlY3JldCI6IjQwNzkxNWJjMjEyYmU2MWE3N2UzZTZkMmFlYjRjNzI3OTgwYmRhNTFjZDA2YTZhZmMyOWUyODYxNzY4YTc4MzciLCJDIjoiMDJiYzkwOTc5OTdkODFhZmIyY2M3MzQ2YjVlNDM0NWE5MzQ2YmQyYTUwNmViNzk1ODU5OGE3MmYwY2Y4NTE2M2VhIn0seyJhbW91bnQiOjgsImlkIjoiMDA5YTFmMjkzMjUzZTQxZSIsInNlY3JldCI6ImZlMTUxMDkzMTRlNjFkNzc1NmIwZjhlZTBmMjNhNjI0YWNhYTNmNGUwNDJmNjE0MzNjNzI4YzcwNTdiOTMxYmUiLCJDIjoiMDI5ZThlNTA1MGI4OTBhN2Q2YzA5NjhkYjE2YmMxZDVkNWZhMDQwZWExZGUyODRmNmVjNjlkNjEyOTlmNjcxMDU5In1dfV0sInVuaXQiOiJzYXQiLCJtZW1vIjoiVGhhbmsgeW91LiJ9";
  399. let token = Token::from_str(token_str).unwrap();
  400. assert_eq!(
  401. token.token[0].mint,
  402. UncheckedUrl::from_str("https://8333.space:3338").unwrap()
  403. );
  404. assert_eq!(
  405. token.token[0].proofs[0].clone().keyset_id,
  406. Id::from_str("009a1f293253e41e").unwrap()
  407. );
  408. assert_eq!(token.unit.clone().unwrap(), CurrencyUnit::Sat);
  409. let encoded = &token.to_string();
  410. let token_data = Token::from_str(encoded).unwrap();
  411. assert_eq!(token_data, token);
  412. }
  413. #[test]
  414. fn test_blank_blinded_messages() {
  415. // TODO: Need to update id to new type in proof
  416. let b = PreMintSecrets::blank(
  417. Id::from_str("009a1f293253e41e").unwrap(),
  418. Amount::from(1000),
  419. )
  420. .unwrap();
  421. assert_eq!(b.len(), 10);
  422. // TODO: Need to update id to new type in proof
  423. let b = PreMintSecrets::blank(Id::from_str("009a1f293253e41e").unwrap(), Amount::from(1))
  424. .unwrap();
  425. assert_eq!(b.len(), 1);
  426. }
  427. #[test]
  428. fn incorrect_tokens() {
  429. let incorrect_prefix = "casshuAeyJ0b2tlbiI6W3sibWludCI6Imh0dHBzOi8vODMzMy5zcGFjZTozMzM4IiwicHJvb2ZzIjpbeyJhbW91bnQiOjIsImlkIjoiMDA5YTFmMjkzMjUzZTQxZSIsInNlY3JldCI6IjQwNzkxNWJjMjEyYmU2MWE3N2UzZTZkMmFlYjRjNzI3OTgwYmRhNTFjZDA2YTZhZmMyOWUyODYxNzY4YTc4MzciLCJDIjoiMDJiYzkwOTc5OTdkODFhZmIyY2M3MzQ2YjVlNDM0NWE5MzQ2YmQyYTUwNmViNzk1ODU5OGE3MmYwY2Y4NTE2M2VhIn0seyJhbW91bnQiOjgsImlkIjoiMDA5YTFmMjkzMjUzZTQxZSIsInNlY3JldCI6ImZlMTUxMDkzMTRlNjFkNzc1NmIwZjhlZTBmMjNhNjI0YWNhYTNmNGUwNDJmNjE0MzNjNzI4YzcwNTdiOTMxYmUiLCJDIjoiMDI5ZThlNTA1MGI4OTBhN2Q2YzA5NjhkYjE2YmMxZDVkNWZhMDQwZWExZGUyODRmNmVjNjlkNjEyOTlmNjcxMDU5In1dfV0sInVuaXQiOiJzYXQiLCJtZW1vIjoiVGhhbmsgeW91LiJ9";
  430. let incorrect_prefix_token = Token::from_str(incorrect_prefix);
  431. assert!(incorrect_prefix_token.is_err());
  432. let no_prefix = "eyJ0b2tlbiI6W3sibWludCI6Imh0dHBzOi8vODMzMy5zcGFjZTozMzM4IiwicHJvb2ZzIjpbeyJhbW91bnQiOjIsImlkIjoiMDA5YTFmMjkzMjUzZTQxZSIsInNlY3JldCI6IjQwNzkxNWJjMjEyYmU2MWE3N2UzZTZkMmFlYjRjNzI3OTgwYmRhNTFjZDA2YTZhZmMyOWUyODYxNzY4YTc4MzciLCJDIjoiMDJiYzkwOTc5OTdkODFhZmIyY2M3MzQ2YjVlNDM0NWE5MzQ2YmQyYTUwNmViNzk1ODU5OGE3MmYwY2Y4NTE2M2VhIn0seyJhbW91bnQiOjgsImlkIjoiMDA5YTFmMjkzMjUzZTQxZSIsInNlY3JldCI6ImZlMTUxMDkzMTRlNjFkNzc1NmIwZjhlZTBmMjNhNjI0YWNhYTNmNGUwNDJmNjE0MzNjNzI4YzcwNTdiOTMxYmUiLCJDIjoiMDI5ZThlNTA1MGI4OTBhN2Q2YzA5NjhkYjE2YmMxZDVkNWZhMDQwZWExZGUyODRmNmVjNjlkNjEyOTlmNjcxMDU5In1dfV0sInVuaXQiOiJzYXQiLCJtZW1vIjoiVGhhbmsgeW91LiJ9";
  433. let no_prefix_token = Token::from_str(no_prefix);
  434. assert!(no_prefix_token.is_err());
  435. let correct_token = "cashuAeyJ0b2tlbiI6W3sibWludCI6Imh0dHBzOi8vODMzMy5zcGFjZTozMzM4IiwicHJvb2ZzIjpbeyJhbW91bnQiOjIsImlkIjoiMDA5YTFmMjkzMjUzZTQxZSIsInNlY3JldCI6IjQwNzkxNWJjMjEyYmU2MWE3N2UzZTZkMmFlYjRjNzI3OTgwYmRhNTFjZDA2YTZhZmMyOWUyODYxNzY4YTc4MzciLCJDIjoiMDJiYzkwOTc5OTdkODFhZmIyY2M3MzQ2YjVlNDM0NWE5MzQ2YmQyYTUwNmViNzk1ODU5OGE3MmYwY2Y4NTE2M2VhIn0seyJhbW91bnQiOjgsImlkIjoiMDA5YTFmMjkzMjUzZTQxZSIsInNlY3JldCI6ImZlMTUxMDkzMTRlNjFkNzc1NmIwZjhlZTBmMjNhNjI0YWNhYTNmNGUwNDJmNjE0MzNjNzI4YzcwNTdiOTMxYmUiLCJDIjoiMDI5ZThlNTA1MGI4OTBhN2Q2YzA5NjhkYjE2YmMxZDVkNWZhMDQwZWExZGUyODRmNmVjNjlkNjEyOTlmNjcxMDU5In1dfV0sInVuaXQiOiJzYXQiLCJtZW1vIjoiVGhhbmsgeW91LiJ9";
  436. let correct_token = Token::from_str(correct_token);
  437. assert!(correct_token.is_ok());
  438. }
  439. }