nut00.rs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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. #[serde(skip_serializing_if = "Option::is_none")]
  164. /// P2SHScript that specifies the spending condition for this Proof
  165. pub script: Option<String>,
  166. }
  167. /// List of proofs
  168. pub type Proofs = Vec<Proof>;
  169. impl From<Proof> for mint::Proof {
  170. fn from(proof: Proof) -> Self {
  171. Self {
  172. amount: Some(proof.amount),
  173. secret: proof.secret,
  174. c: Some(proof.c),
  175. id: proof.id,
  176. script: proof.script,
  177. }
  178. }
  179. }
  180. pub mod mint {
  181. use serde::{Deserialize, Serialize};
  182. use crate::Amount;
  183. use super::PublicKey;
  184. /// Proofs [NUT-00]
  185. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  186. pub struct Proof {
  187. /// Amount in satoshi
  188. pub amount: Option<Amount>,
  189. /// Secret message
  190. // #[serde(with = "crate::serde_utils::bytes_base64")]
  191. pub secret: String,
  192. /// Unblinded signature
  193. #[serde(rename = "C")]
  194. pub c: Option<PublicKey>,
  195. /// `Keyset id`
  196. pub id: Option<String>,
  197. #[serde(skip_serializing_if = "Option::is_none")]
  198. /// P2SHScript that specifies the spending condition for this Proof
  199. pub script: Option<String>,
  200. }
  201. /// List of proofs
  202. pub type Proofs = Vec<Proof>;
  203. pub fn mint_proofs_from_proofs(proofs: super::Proofs) -> Proofs {
  204. proofs.iter().map(|p| p.to_owned().into()).collect()
  205. }
  206. }
  207. #[cfg(test)]
  208. mod tests {
  209. use std::str::FromStr;
  210. use url::Url;
  211. use super::wallet::*;
  212. use super::*;
  213. #[test]
  214. fn test_proof_seralize() {
  215. let proof = "[{\"id\":\"DSAl9nvvyfva\",\"amount\":2,\"secret\":\"EhpennC9qB3iFlW8FZ_pZw\",\"C\":\"02c020067db727d586bc3183aecf97fcb800c3f4cc4759f69c626c9db5d8f5b5d4\"},{\"id\":\"DSAl9nvvyfva\",\"amount\":8,\"secret\":\"TmS6Cv0YT5PU_5ATVKnukw\",\"C\":\"02ac910bef28cbe5d7325415d5c263026f15f9b967a079ca9779ab6e5c2db133a7\"}]";
  216. let proof: Proofs = serde_json::from_str(proof).unwrap();
  217. assert_eq!(proof[0].clone().id.unwrap(), "DSAl9nvvyfva");
  218. }
  219. #[test]
  220. fn test_token_str_round_trip() {
  221. let token_str = "cashuAeyJ0b2tlbiI6W3sibWludCI6Imh0dHBzOi8vODMzMy5zcGFjZTozMzM4IiwicHJvb2ZzIjpbeyJpZCI6IkRTQWw5bnZ2eWZ2YSIsImFtb3VudCI6Miwic2VjcmV0IjoiRWhwZW5uQzlxQjNpRmxXOEZaX3BadyIsIkMiOiIwMmMwMjAwNjdkYjcyN2Q1ODZiYzMxODNhZWNmOTdmY2I4MDBjM2Y0Y2M0NzU5ZjY5YzYyNmM5ZGI1ZDhmNWI1ZDQifSx7ImlkIjoiRFNBbDludnZ5ZnZhIiwiYW1vdW50Ijo4LCJzZWNyZXQiOiJUbVM2Q3YwWVQ1UFVfNUFUVktudWt3IiwiQyI6IjAyYWM5MTBiZWYyOGNiZTVkNzMyNTQxNWQ1YzI2MzAyNmYxNWY5Yjk2N2EwNzljYTk3NzlhYjZlNWMyZGIxMzNhNyJ9XX1dLCJtZW1vIjoiVGhhbmt5b3UuIn0=";
  222. let token = Token::from_str(token_str).unwrap();
  223. assert_eq!(
  224. token.token[0].mint,
  225. Url::from_str("https://8333.space:3338").unwrap()
  226. );
  227. assert_eq!(token.token[0].proofs[0].clone().id.unwrap(), "DSAl9nvvyfva");
  228. let encoded = &token.convert_to_string().unwrap();
  229. let token_data = Token::from_str(encoded).unwrap();
  230. assert_eq!(token_data, token);
  231. }
  232. #[test]
  233. fn test_blank_blinded_messages() {
  234. let b = BlindedMessages::blank(Amount::from_sat(1000)).unwrap();
  235. assert_eq!(b.blinded_messages.len(), 10);
  236. let b = BlindedMessages::blank(Amount::from_sat(1)).unwrap();
  237. assert_eq!(b.blinded_messages.len(), 1);
  238. }
  239. }