nut01.rs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. //! Mint public key exchange
  2. // https://github.com/cashubtc/nuts/blob/main/01.md
  3. use std::collections::{BTreeMap, HashMap};
  4. use serde::{Deserialize, Serialize};
  5. use crate::error::Error;
  6. use crate::Amount;
  7. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
  8. #[serde(transparent)]
  9. pub struct PublicKey(#[serde(with = "crate::serde_utils::serde_public_key")] k256::PublicKey);
  10. impl From<PublicKey> for k256::PublicKey {
  11. fn from(value: PublicKey) -> k256::PublicKey {
  12. value.0
  13. }
  14. }
  15. impl From<&PublicKey> for k256::PublicKey {
  16. fn from(value: &PublicKey) -> k256::PublicKey {
  17. value.0
  18. }
  19. }
  20. impl From<k256::PublicKey> for PublicKey {
  21. fn from(value: k256::PublicKey) -> Self {
  22. Self(value)
  23. }
  24. }
  25. impl PublicKey {
  26. pub fn from_hex(hex: String) -> Result<Self, Error> {
  27. let hex = hex::decode(hex)?;
  28. Ok(PublicKey(k256::PublicKey::from_sec1_bytes(&hex)?))
  29. }
  30. pub fn to_hex(&self) -> String {
  31. let bytes = self.0.to_sec1_bytes();
  32. hex::encode(bytes)
  33. }
  34. pub fn to_bytes(&self) -> Box<[u8]> {
  35. self.0.to_sec1_bytes()
  36. }
  37. }
  38. impl std::fmt::Display for PublicKey {
  39. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  40. f.write_str(&self.to_hex())
  41. }
  42. }
  43. #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
  44. #[serde(transparent)]
  45. pub struct SecretKey(#[serde(with = "crate::serde_utils::serde_secret_key")] k256::SecretKey);
  46. impl From<SecretKey> for k256::SecretKey {
  47. fn from(value: SecretKey) -> k256::SecretKey {
  48. value.0
  49. }
  50. }
  51. impl From<k256::SecretKey> for SecretKey {
  52. fn from(value: k256::SecretKey) -> Self {
  53. Self(value)
  54. }
  55. }
  56. impl SecretKey {
  57. pub fn to_hex(&self) -> String {
  58. let bytes = self.0.to_bytes();
  59. hex::encode(bytes)
  60. }
  61. pub fn public_key(&self) -> PublicKey {
  62. self.0.public_key().into()
  63. }
  64. }
  65. /// Mint Keys [NUT-01]
  66. #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
  67. pub struct Keys(BTreeMap<Amount, PublicKey>);
  68. impl From<mint::Keys> for Keys {
  69. fn from(keys: mint::Keys) -> Self {
  70. Self(
  71. keys.0
  72. .iter()
  73. .map(|(amount, keypair)| (*amount, keypair.public_key.clone()))
  74. .collect(),
  75. )
  76. }
  77. }
  78. impl Keys {
  79. pub fn new(keys: BTreeMap<Amount, PublicKey>) -> Self {
  80. Self(keys)
  81. }
  82. pub fn keys(&self) -> BTreeMap<Amount, PublicKey> {
  83. self.0.clone()
  84. }
  85. pub fn amount_key(&self, amount: Amount) -> Option<PublicKey> {
  86. self.0.get(&amount).cloned()
  87. }
  88. /// As serialized hashmap
  89. pub fn as_hashmap(&self) -> HashMap<Amount, String> {
  90. self.0
  91. .iter()
  92. .map(|(k, v)| (k.to_owned(), hex::encode(v.0.to_sec1_bytes())))
  93. .collect()
  94. }
  95. /// Iterate through the (`Amount`, `PublicKey`) entries in the Map
  96. pub fn iter(&self) -> impl Iterator<Item = (&Amount, &PublicKey)> {
  97. self.0.iter()
  98. }
  99. }
  100. /// Mint Public Keys [NUT-01]
  101. #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
  102. pub struct KeysResponse {
  103. /// set of public keys that the mint generates
  104. #[serde(flatten)]
  105. pub keys: Keys,
  106. }
  107. impl<'de> serde::de::Deserialize<'de> for KeysResponse {
  108. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  109. where
  110. D: serde::Deserializer<'de>,
  111. {
  112. struct KeysVisitor;
  113. impl<'de> serde::de::Visitor<'de> for KeysVisitor {
  114. type Value = KeysResponse;
  115. fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
  116. formatter.write_str("")
  117. }
  118. fn visit_map<M>(self, mut m: M) -> Result<Self::Value, M::Error>
  119. where
  120. M: serde::de::MapAccess<'de>,
  121. {
  122. let mut keys: BTreeMap<Amount, PublicKey> = BTreeMap::new();
  123. while let Some((a, k)) = m.next_entry::<String, String>()? {
  124. let amount = a.parse();
  125. let pub_key = PublicKey::from_hex(k);
  126. if let (Ok(amount), Ok(pubkey)) = (amount, pub_key) {
  127. let amount = Amount::from_sat(amount);
  128. keys.insert(amount, pubkey);
  129. }
  130. // TODO: Should return an error if an amount or key is
  131. // invalid and not continue
  132. }
  133. Ok(KeysResponse { keys: Keys(keys) })
  134. }
  135. }
  136. deserializer.deserialize_map(KeysVisitor)
  137. }
  138. }
  139. pub mod mint {
  140. use std::collections::BTreeMap;
  141. use serde::Serialize;
  142. use super::{PublicKey, SecretKey};
  143. use crate::Amount;
  144. #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
  145. pub struct Keys(pub BTreeMap<Amount, KeyPair>);
  146. #[derive(Debug, Clone, PartialEq, Eq, Serialize)]
  147. pub struct KeyPair {
  148. pub public_key: PublicKey,
  149. pub secret_key: SecretKey,
  150. }
  151. impl KeyPair {
  152. pub fn from_secret_key(secret_key: SecretKey) -> Self {
  153. Self {
  154. public_key: secret_key.public_key(),
  155. secret_key,
  156. }
  157. }
  158. }
  159. }
  160. #[cfg(test)]
  161. mod tests {
  162. use super::*;
  163. #[test]
  164. fn pubkey() {
  165. let pubkey_str = "02c020067db727d586bc3183aecf97fcb800c3f4cc4759f69c626c9db5d8f5b5d4";
  166. let pubkey = PublicKey::from_hex(pubkey_str.to_string()).unwrap();
  167. assert_eq!(pubkey_str, pubkey.to_hex())
  168. }
  169. #[test]
  170. fn key_response() {
  171. let res: String = r#"{"1":"02f71e2d93aa95fc52b938735a24774ad926406c81e9dc9d2aa699fb89281548fd","2":"03b28dd9c19aaf1ec847be31b60c6a5e1a6cb6f87434afcdb0d9348ba0e2bdb150","4":"03ede0e704e223e764a82f73984b0fec0fdbde15ef57b4de95b527f7182af7487e","8":"020fd24fbd552445df70c244be2af77da2b2f634ccfda9e9620b347b5cd50dbdd8","16":"03ef9ef2515df5c0d0851ed9419a24a571ef5e03206d9d2fc6572ac050c5afe1aa","32":"02dbd455474176b30234c178573e874cc79d0c2fc1920cf0e9f133204cf43299c1","64":"0237c1eb11b8a214cca3e0104684227952188039a05cd55c1ad3896a572c70a7c3","128":"02655041771766b94a269f9f1ec1860f2eade55bb472c4db74ac1257ef54aac52b","256":"02b9e0be7b423bded7d60ff7114549de8d2d5b9c099edf8887aff474037e4bc0cf","512":"0320454cc41e646f49e1ac0a62b9667c80dee45545b045575f2a26f01770dc2521","1024":"0267fc1dabac016f46b3d1a650d97b56f3e56540106720f3d24ff7a6e9cd7183e9","2048":"035a9a25251a4da56f49667ca50677470fc6d8e186a875ab7b32aa064eb9e9e948","4096":"02f607a9eed310825c2d2e66d6e64fb237fe21b640b9a66cc7646b2a6480d91457","8192":"033346f7dce2ef71a80c5d657a8930bdd19c7c1708d03829daf43f20eaeda76768","16384":"024fad3b0b60c6b71d848deac173183fae8ddde31bbde531f18ab23473ddff541d","32768":"020d195466819d96d8c7eee9150565b7bd37196c7d12d0e96e389f56be8aebb44b","65536":"038c9bf295a745726c38d14988851d68d201296a802c296faa838000c2f44d25e0","131072":"032ff6491cdeff0bf9b34acd5deceef3cca7682b5f94dbe3068af8bb3b5aa34b81","262144":"02570090f5b6900955fd794d8f22c23fb35fc87fa03069b9b16bea63ea7cda419a","524288":"029d3c751c7d1c3e1d3e4b7791e1e809f6dedf2c28e172a82967d49a14b7c26ce2","1048576":"03b4a41d39cc6f2a8925f694c514e107b87d7ddb8f5ac55c9e4b7895139d0decd8","2097152":"02d4abbce491f87656eb0d2e66ef18eb009f6320169ef12e66703298d5395f2b91","4194304":"0359023fb85f6e6ede0141ab8f4a1277c19ed62b49b8ef5c5e2c8ca7fefe9b2f91","8388608":"0353d3ae1dad05e1b46ab85a366bfcdb7a645e3457f7714003e0fb06f4d75f4d87","16777216":"032d0847606465b97f15aca30c69f5baeeb43bf6188b4679f723119ce6fb9708c5","33554432":"028a673a53e78aa8c992128e21efb3b33fbd54de20afcf81a67e69eaf2bab7e0e9","67108864":"0278b66e140559352bb5aeca854a6466bc439ee206a9f349ed7926aae4335269b7","134217728":"023834651da0737f484a77204c2d06543fb65ad2dd8d095a2be48ca12ebf2664ec","268435456":"032cba9068638965ccc3870c140c72a1b028a820851f36fe59639e7ab3093a8ffd","536870912":"03eae5e4b22dfa5ad77476c925717dc4e005da78142e75b47fb28569d745483af3","1073741824":"02d17d61027602432a8484b65e6d6063ed9157c51ce92099d61ac2820411c59f9f","2147483648":"0236870e39b3a739d5caa04988dce432e3d7988420f04d9b415125af22672e2726"}"#.to_string();
  172. let response: Keys = serde_json::from_str(&res).unwrap();
  173. assert_eq!(&serde_json::to_string(&response).unwrap(), &res)
  174. }
  175. }