nut00.rs 14 KB

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