nut00.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. //! Notation and Models
  2. // https://github.com/cashubtc/nuts/blob/main/00.md
  3. use url::Url;
  4. use crate::serde_utils::serde_url;
  5. use crate::Amount;
  6. use serde::{Deserialize, Serialize};
  7. use super::nut01::PublicKey;
  8. /// Blinded Message [NUT-00]
  9. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  10. pub struct BlindedMessage {
  11. /// Amount in satoshi
  12. pub amount: Amount,
  13. /// encrypted secret message (B_)
  14. #[serde(rename = "B_")]
  15. pub b: PublicKey,
  16. }
  17. #[cfg(feature = "wallet")]
  18. pub mod wallet {
  19. use std::str::FromStr;
  20. use base64::{engine::general_purpose, Engine as _};
  21. use serde::{Deserialize, Serialize};
  22. use url::Url;
  23. use crate::error;
  24. use crate::error::wallet;
  25. use crate::nuts::nut00::BlindedMessage;
  26. use crate::nuts::nut00::Proofs;
  27. use crate::nuts::nut01;
  28. use crate::utils::generate_secret;
  29. use crate::Amount;
  30. use crate::{dhke::blind_message, utils::split_amount};
  31. use super::MintProofs;
  32. /// Blinded Messages [NUT-00]
  33. #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
  34. pub struct BlindedMessages {
  35. /// Blinded messages
  36. pub blinded_messages: Vec<BlindedMessage>,
  37. /// Secrets
  38. pub secrets: Vec<String>,
  39. /// Rs
  40. pub rs: Vec<nut01::SecretKey>,
  41. /// Amounts
  42. pub amounts: Vec<Amount>,
  43. }
  44. impl BlindedMessages {
  45. /// Outputs for speceifed amount with random secret
  46. pub fn random(amount: Amount) -> Result<Self, wallet::Error> {
  47. let mut blinded_messages = BlindedMessages::default();
  48. for amount in split_amount(amount) {
  49. let secret = generate_secret();
  50. let (blinded, r) = blind_message(secret.as_bytes(), None)?;
  51. let blinded_message = BlindedMessage { amount, b: blinded };
  52. blinded_messages.secrets.push(secret);
  53. blinded_messages.blinded_messages.push(blinded_message);
  54. blinded_messages.rs.push(r.into());
  55. blinded_messages.amounts.push(amount);
  56. }
  57. Ok(blinded_messages)
  58. }
  59. /// Blank Outputs used for NUT-08 change
  60. pub fn blank(fee_reserve: Amount) -> Result<Self, wallet::Error> {
  61. let mut blinded_messages = BlindedMessages::default();
  62. let fee_reserve = bitcoin::Amount::from_sat(fee_reserve.to_sat());
  63. let count = (fee_reserve
  64. .to_float_in(bitcoin::Denomination::Satoshi)
  65. .log2()
  66. .ceil() as u64)
  67. .max(1);
  68. for _i in 0..count {
  69. let secret = generate_secret();
  70. let (blinded, r) = blind_message(secret.as_bytes(), None)?;
  71. let blinded_message = BlindedMessage {
  72. amount: Amount::ZERO,
  73. b: blinded,
  74. };
  75. blinded_messages.secrets.push(secret);
  76. blinded_messages.blinded_messages.push(blinded_message);
  77. blinded_messages.rs.push(r.into());
  78. blinded_messages.amounts.push(Amount::ZERO);
  79. }
  80. Ok(blinded_messages)
  81. }
  82. }
  83. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  84. pub struct Token {
  85. pub token: Vec<MintProofs>,
  86. pub memo: Option<String>,
  87. }
  88. impl Token {
  89. pub fn new(mint_url: Url, proofs: Proofs, memo: Option<String>) -> Self {
  90. Self {
  91. token: vec![MintProofs::new(mint_url, proofs)],
  92. memo,
  93. }
  94. }
  95. pub fn token_info(&self) -> (u64, String) {
  96. let mut amount = Amount::ZERO;
  97. for proofs in &self.token {
  98. for proof in &proofs.proofs {
  99. amount += proof.amount;
  100. }
  101. }
  102. (amount.to_sat(), self.token[0].mint.to_string())
  103. }
  104. }
  105. impl FromStr for Token {
  106. type Err = error::wallet::Error;
  107. fn from_str(s: &str) -> Result<Self, Self::Err> {
  108. if !s.starts_with("cashuA") {
  109. return Err(wallet::Error::UnsupportedToken);
  110. }
  111. let s = s.replace("cashuA", "");
  112. let decoded = general_purpose::STANDARD.decode(s)?;
  113. let decoded_str = String::from_utf8(decoded)?;
  114. let token: Token = serde_json::from_str(&decoded_str)?;
  115. Ok(token)
  116. }
  117. }
  118. impl Token {
  119. pub fn convert_to_string(&self) -> Result<String, wallet::Error> {
  120. let json_string = serde_json::to_string(self)?;
  121. let encoded = general_purpose::STANDARD.encode(json_string);
  122. Ok(format!("cashuA{}", encoded))
  123. }
  124. }
  125. }
  126. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  127. pub struct MintProofs {
  128. #[serde(with = "serde_url")]
  129. pub mint: Url,
  130. pub proofs: Proofs,
  131. }
  132. #[cfg(feature = "wallet")]
  133. impl MintProofs {
  134. fn new(mint_url: Url, proofs: Proofs) -> Self {
  135. Self {
  136. mint: mint_url,
  137. proofs,
  138. }
  139. }
  140. }
  141. /// Promise (BlindedSignature) [NUT-00]
  142. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  143. pub struct BlindedSignature {
  144. pub id: String,
  145. pub amount: Amount,
  146. /// blinded signature (C_) on the secret message `B_` of [BlindedMessage]
  147. #[serde(rename = "C_")]
  148. pub c: PublicKey,
  149. }
  150. /// Proofs [NUT-00]
  151. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  152. pub struct Proof {
  153. /// Amount in satoshi
  154. pub amount: Amount,
  155. /// Secret message
  156. // #[serde(with = "crate::serde_utils::bytes_base64")]
  157. pub secret: String,
  158. /// Unblinded signature
  159. #[serde(rename = "C")]
  160. pub c: PublicKey,
  161. /// `Keyset id`
  162. pub id: Option<String>,
  163. }
  164. /// List of proofs
  165. pub type Proofs = Vec<Proof>;
  166. impl From<Proof> for mint::Proof {
  167. fn from(proof: Proof) -> Self {
  168. Self {
  169. amount: Some(proof.amount),
  170. secret: proof.secret,
  171. c: Some(proof.c),
  172. id: proof.id,
  173. }
  174. }
  175. }
  176. pub mod mint {
  177. use serde::{Deserialize, Serialize};
  178. use crate::Amount;
  179. use super::PublicKey;
  180. /// Proofs [NUT-00]
  181. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  182. pub struct Proof {
  183. /// Amount in satoshi
  184. pub amount: Option<Amount>,
  185. /// Secret message
  186. // #[serde(with = "crate::serde_utils::bytes_base64")]
  187. pub secret: String,
  188. /// Unblinded signature
  189. #[serde(rename = "C")]
  190. pub c: Option<PublicKey>,
  191. /// `Keyset id`
  192. pub id: Option<String>,
  193. }
  194. /// List of proofs
  195. pub type Proofs = Vec<Proof>;
  196. pub fn mint_proofs_from_proofs(proofs: super::Proofs) -> Proofs {
  197. proofs.iter().map(|p| p.to_owned().into()).collect()
  198. }
  199. }
  200. #[cfg(test)]
  201. mod tests {
  202. use std::str::FromStr;
  203. use url::Url;
  204. use super::wallet::*;
  205. use super::*;
  206. #[test]
  207. fn test_proof_seralize() {
  208. let proof = "[{\"id\":\"DSAl9nvvyfva\",\"amount\":2,\"secret\":\"EhpennC9qB3iFlW8FZ_pZw\",\"C\":\"02c020067db727d586bc3183aecf97fcb800c3f4cc4759f69c626c9db5d8f5b5d4\"},{\"id\":\"DSAl9nvvyfva\",\"amount\":8,\"secret\":\"TmS6Cv0YT5PU_5ATVKnukw\",\"C\":\"02ac910bef28cbe5d7325415d5c263026f15f9b967a079ca9779ab6e5c2db133a7\"}]";
  209. let proof: Proofs = serde_json::from_str(proof).unwrap();
  210. assert_eq!(proof[0].clone().id.unwrap(), "DSAl9nvvyfva");
  211. }
  212. #[test]
  213. fn test_token_str_round_trip() {
  214. let token_str = "cashuAeyJ0b2tlbiI6W3sibWludCI6Imh0dHBzOi8vODMzMy5zcGFjZTozMzM4IiwicHJvb2ZzIjpbeyJpZCI6IkRTQWw5bnZ2eWZ2YSIsImFtb3VudCI6Miwic2VjcmV0IjoiRWhwZW5uQzlxQjNpRmxXOEZaX3BadyIsIkMiOiIwMmMwMjAwNjdkYjcyN2Q1ODZiYzMxODNhZWNmOTdmY2I4MDBjM2Y0Y2M0NzU5ZjY5YzYyNmM5ZGI1ZDhmNWI1ZDQifSx7ImlkIjoiRFNBbDludnZ5ZnZhIiwiYW1vdW50Ijo4LCJzZWNyZXQiOiJUbVM2Q3YwWVQ1UFVfNUFUVktudWt3IiwiQyI6IjAyYWM5MTBiZWYyOGNiZTVkNzMyNTQxNWQ1YzI2MzAyNmYxNWY5Yjk2N2EwNzljYTk3NzlhYjZlNWMyZGIxMzNhNyJ9XX1dLCJtZW1vIjoiVGhhbmt5b3UuIn0=";
  215. let token = Token::from_str(token_str).unwrap();
  216. assert_eq!(
  217. token.token[0].mint,
  218. Url::from_str("https://8333.space:3338").unwrap()
  219. );
  220. assert_eq!(token.token[0].proofs[0].clone().id.unwrap(), "DSAl9nvvyfva");
  221. let encoded = &token.convert_to_string().unwrap();
  222. let token_data = Token::from_str(encoded).unwrap();
  223. assert_eq!(token_data, token);
  224. }
  225. #[test]
  226. fn test_blank_blinded_messages() {
  227. let b = BlindedMessages::blank(Amount::from_sat(1000)).unwrap();
  228. assert_eq!(b.blinded_messages.len(), 10);
  229. let b = BlindedMessages::blank(Amount::from_sat(1)).unwrap();
  230. assert_eq!(b.blinded_messages.len(), 1);
  231. }
  232. }