convert.rs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. //! Type conversions between Rust types and the generated protobuf types.
  2. use std::collections::BTreeMap;
  3. use cdk_common::secret::Secret;
  4. use cdk_common::util::hex;
  5. use cdk_common::{Amount, PublicKey};
  6. use tonic::Status;
  7. use super::*;
  8. const INTERNAL_ERROR: &str = "Missing property";
  9. impl From<crate::signatory::SignatoryKeysets> for SignatoryKeysets {
  10. fn from(keyset: crate::signatory::SignatoryKeysets) -> Self {
  11. Self {
  12. pubkey: keyset.pubkey.to_bytes().to_vec(),
  13. keysets: keyset
  14. .keysets
  15. .into_iter()
  16. .map(|keyset| keyset.into())
  17. .collect(),
  18. }
  19. }
  20. }
  21. impl TryInto<crate::signatory::SignatoryKeysets> for SignatoryKeysets {
  22. /// TODO: Make sure that all type Error here are cdk_common::Error
  23. type Error = cdk_common::Error;
  24. fn try_into(self) -> Result<crate::signatory::SignatoryKeysets, Self::Error> {
  25. Ok(crate::signatory::SignatoryKeysets {
  26. pubkey: PublicKey::from_slice(&self.pubkey)?,
  27. keysets: self
  28. .keysets
  29. .into_iter()
  30. .map(|keyset| keyset.try_into())
  31. .collect::<Result<Vec<_>, _>>()?,
  32. })
  33. }
  34. }
  35. impl TryInto<crate::signatory::SignatoryKeySet> for KeySet {
  36. type Error = cdk_common::Error;
  37. fn try_into(self) -> Result<crate::signatory::SignatoryKeySet, Self::Error> {
  38. Ok(crate::signatory::SignatoryKeySet {
  39. id: self.id.parse()?,
  40. unit: self
  41. .unit
  42. .ok_or(cdk_common::Error::Custom(INTERNAL_ERROR.to_owned()))?
  43. .try_into()
  44. .map_err(|_| cdk_common::Error::Custom("Invalid currency unit".to_owned()))?,
  45. active: self.active,
  46. input_fee_ppk: self.input_fee_ppk,
  47. keys: cdk_common::Keys::new(
  48. self.keys
  49. .ok_or(cdk_common::Error::Custom(INTERNAL_ERROR.to_owned()))?
  50. .keys
  51. .into_iter()
  52. .map(|(amount, pk)| PublicKey::from_slice(&pk).map(|pk| (amount.into(), pk)))
  53. .collect::<Result<BTreeMap<Amount, _>, _>>()?,
  54. ),
  55. final_expiry: self.final_expiry,
  56. })
  57. }
  58. }
  59. impl From<crate::signatory::SignatoryKeySet> for KeySet {
  60. fn from(keyset: crate::signatory::SignatoryKeySet) -> Self {
  61. Self {
  62. id: keyset.id.to_string(),
  63. unit: Some(keyset.unit.into()),
  64. active: keyset.active,
  65. input_fee_ppk: keyset.input_fee_ppk,
  66. keys: Some(Keys {
  67. keys: keyset
  68. .keys
  69. .iter()
  70. .map(|(key, value)| ((*key).into(), value.to_bytes().to_vec()))
  71. .collect(),
  72. }),
  73. final_expiry: keyset.final_expiry,
  74. }
  75. }
  76. }
  77. impl From<cdk_common::Error> for Error {
  78. fn from(err: cdk_common::Error) -> Self {
  79. let code = match err {
  80. cdk_common::Error::AmountError(_) => ErrorCode::AmountOutsideLimit,
  81. cdk_common::Error::DuplicateInputs => ErrorCode::DuplicateInputsProvided,
  82. cdk_common::Error::DuplicateOutputs => ErrorCode::DuplicateInputsProvided,
  83. cdk_common::Error::UnknownKeySet => ErrorCode::KeysetNotKnown,
  84. cdk_common::Error::InactiveKeyset => ErrorCode::KeysetInactive,
  85. _ => ErrorCode::Unspecified,
  86. };
  87. Error {
  88. code: code.into(),
  89. detail: err.to_string(),
  90. }
  91. }
  92. }
  93. impl From<Error> for cdk_common::Error {
  94. fn from(val: Error) -> Self {
  95. match val.code.try_into().expect("valid code") {
  96. ErrorCode::AmountOutsideLimit => {
  97. cdk_common::Error::AmountError(cdk_common::amount::Error::AmountOverflow)
  98. }
  99. ErrorCode::DuplicateInputsProvided => cdk_common::Error::DuplicateInputs,
  100. ErrorCode::KeysetNotKnown => cdk_common::Error::UnknownKeySet,
  101. ErrorCode::KeysetInactive => cdk_common::Error::InactiveKeyset,
  102. ErrorCode::Unspecified => cdk_common::Error::Custom(val.detail),
  103. _ => todo!(),
  104. }
  105. }
  106. }
  107. impl From<cdk_common::BlindSignatureDleq> for BlindSignatureDleq {
  108. fn from(value: cdk_common::BlindSignatureDleq) -> Self {
  109. BlindSignatureDleq {
  110. e: value.e.as_secret_bytes().to_vec(),
  111. s: value.s.as_secret_bytes().to_vec(),
  112. }
  113. }
  114. }
  115. impl TryInto<cdk_common::BlindSignatureDleq> for BlindSignatureDleq {
  116. type Error = cdk_common::error::Error;
  117. fn try_into(self) -> Result<cdk_common::BlindSignatureDleq, Self::Error> {
  118. Ok(cdk_common::BlindSignatureDleq {
  119. e: cdk_common::SecretKey::from_slice(&self.e)?,
  120. s: cdk_common::SecretKey::from_slice(&self.s)?,
  121. })
  122. }
  123. }
  124. impl From<cdk_common::BlindSignature> for BlindSignature {
  125. fn from(value: cdk_common::BlindSignature) -> Self {
  126. BlindSignature {
  127. amount: value.amount.into(),
  128. blinded_secret: value.c.to_bytes().to_vec(),
  129. keyset_id: value.keyset_id.to_string(),
  130. dleq: value.dleq.map(|x| x.into()),
  131. }
  132. }
  133. }
  134. impl From<Vec<cdk_common::Proof>> for Proofs {
  135. fn from(value: Vec<cdk_common::Proof>) -> Self {
  136. Proofs {
  137. proof: value.into_iter().map(|x| x.into()).collect(),
  138. operation: Operation::Unspecified.into(),
  139. correlation_id: "".to_owned(),
  140. }
  141. }
  142. }
  143. impl From<cdk_common::Proof> for Proof {
  144. fn from(value: cdk_common::Proof) -> Self {
  145. Proof {
  146. amount: value.amount.into(),
  147. keyset_id: value.keyset_id.to_string(),
  148. secret: value.secret.to_bytes(),
  149. c: value.c.to_bytes().to_vec(),
  150. }
  151. }
  152. }
  153. impl TryInto<cdk_common::Proof> for Proof {
  154. type Error = Status;
  155. fn try_into(self) -> Result<cdk_common::Proof, Self::Error> {
  156. let secret = if let Ok(str) = String::from_utf8(self.secret.clone()) {
  157. str
  158. } else {
  159. hex::encode(&self.secret)
  160. };
  161. Ok(cdk_common::Proof {
  162. amount: self.amount.into(),
  163. keyset_id: self
  164. .keyset_id
  165. .parse()
  166. .map_err(|e| Status::from_error(Box::new(e)))?,
  167. secret: Secret::new(secret),
  168. c: cdk_common::PublicKey::from_slice(&self.c)
  169. .map_err(|e| Status::from_error(Box::new(e)))?,
  170. witness: None,
  171. dleq: None,
  172. })
  173. }
  174. }
  175. impl TryInto<cdk_common::BlindSignature> for BlindSignature {
  176. type Error = cdk_common::error::Error;
  177. fn try_into(self) -> Result<cdk_common::BlindSignature, Self::Error> {
  178. Ok(cdk_common::BlindSignature {
  179. amount: self.amount.into(),
  180. c: cdk_common::PublicKey::from_slice(&self.blinded_secret)?,
  181. keyset_id: self.keyset_id.parse().expect("Invalid keyset id"),
  182. dleq: self.dleq.map(|dleq| dleq.try_into()).transpose()?,
  183. })
  184. }
  185. }
  186. impl From<cdk_common::BlindedMessage> for BlindedMessage {
  187. fn from(value: cdk_common::BlindedMessage) -> Self {
  188. BlindedMessage {
  189. amount: value.amount.into(),
  190. keyset_id: value.keyset_id.to_string(),
  191. blinded_secret: value.blinded_secret.to_bytes().to_vec(),
  192. }
  193. }
  194. }
  195. impl TryInto<cdk_common::BlindedMessage> for BlindedMessage {
  196. type Error = Status;
  197. fn try_into(self) -> Result<cdk_common::BlindedMessage, Self::Error> {
  198. Ok(cdk_common::BlindedMessage {
  199. amount: self.amount.into(),
  200. keyset_id: self
  201. .keyset_id
  202. .parse()
  203. .map_err(|e| Status::from_error(Box::new(e)))?,
  204. blinded_secret: cdk_common::PublicKey::from_slice(&self.blinded_secret)
  205. .map_err(|e| Status::from_error(Box::new(e)))?,
  206. witness: None,
  207. })
  208. }
  209. }
  210. impl From<()> for EmptyRequest {
  211. fn from(_: ()) -> Self {
  212. EmptyRequest {}
  213. }
  214. }
  215. impl TryInto<()> for EmptyRequest {
  216. type Error = cdk_common::error::Error;
  217. fn try_into(self) -> Result<(), Self::Error> {
  218. Ok(())
  219. }
  220. }
  221. impl From<cdk_common::CurrencyUnit> for CurrencyUnit {
  222. fn from(value: cdk_common::CurrencyUnit) -> Self {
  223. match value {
  224. cdk_common::CurrencyUnit::Sat => CurrencyUnit {
  225. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  226. CurrencyUnitType::Sat.into(),
  227. )),
  228. },
  229. cdk_common::CurrencyUnit::Msat => CurrencyUnit {
  230. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  231. CurrencyUnitType::Msat.into(),
  232. )),
  233. },
  234. cdk_common::CurrencyUnit::Usd => CurrencyUnit {
  235. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  236. CurrencyUnitType::Usd.into(),
  237. )),
  238. },
  239. cdk_common::CurrencyUnit::Eur => CurrencyUnit {
  240. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  241. CurrencyUnitType::Eur.into(),
  242. )),
  243. },
  244. cdk_common::CurrencyUnit::Auth => CurrencyUnit {
  245. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  246. CurrencyUnitType::Auth.into(),
  247. )),
  248. },
  249. cdk_common::CurrencyUnit::Custom(name) => CurrencyUnit {
  250. currency_unit: Some(currency_unit::CurrencyUnit::CustomUnit(name)),
  251. },
  252. _ => unreachable!(),
  253. }
  254. }
  255. }
  256. impl TryInto<cdk_common::CurrencyUnit> for CurrencyUnit {
  257. type Error = Status;
  258. fn try_into(self) -> Result<cdk_common::CurrencyUnit, Self::Error> {
  259. match self.currency_unit {
  260. Some(currency_unit::CurrencyUnit::Unit(u)) => match u
  261. .try_into()
  262. .map_err(|_| Status::invalid_argument("Invalid currency unit"))?
  263. {
  264. CurrencyUnitType::Sat => Ok(cdk_common::CurrencyUnit::Sat),
  265. CurrencyUnitType::Msat => Ok(cdk_common::CurrencyUnit::Msat),
  266. CurrencyUnitType::Usd => Ok(cdk_common::CurrencyUnit::Usd),
  267. CurrencyUnitType::Eur => Ok(cdk_common::CurrencyUnit::Eur),
  268. CurrencyUnitType::Auth => Ok(cdk_common::CurrencyUnit::Auth),
  269. CurrencyUnitType::Unspecified => {
  270. Err(Status::invalid_argument("Current unit is not specified"))
  271. }
  272. },
  273. Some(currency_unit::CurrencyUnit::CustomUnit(name)) => {
  274. Ok(cdk_common::CurrencyUnit::Custom(name))
  275. }
  276. None => Err(Status::invalid_argument("Currency unit not set")),
  277. }
  278. }
  279. }
  280. impl TryInto<cdk_common::KeySet> for KeySet {
  281. type Error = cdk_common::error::Error;
  282. fn try_into(self) -> Result<cdk_common::KeySet, Self::Error> {
  283. Ok(cdk_common::KeySet {
  284. id: self
  285. .id
  286. .parse()
  287. .map_err(|_| cdk_common::error::Error::Custom("Invalid ID".to_owned()))?,
  288. unit: self
  289. .unit
  290. .ok_or(cdk_common::error::Error::Custom(INTERNAL_ERROR.to_owned()))?
  291. .try_into()
  292. .map_err(|_| cdk_common::Error::Custom("Invalid unit encoding".to_owned()))?,
  293. keys: cdk_common::Keys::new(
  294. self.keys
  295. .ok_or(cdk_common::error::Error::Custom(INTERNAL_ERROR.to_owned()))?
  296. .keys
  297. .into_iter()
  298. .map(|(k, v)| cdk_common::PublicKey::from_slice(&v).map(|pk| (k.into(), pk)))
  299. .collect::<Result<BTreeMap<cdk_common::Amount, cdk_common::PublicKey>, _>>()?,
  300. ),
  301. final_expiry: self.final_expiry,
  302. })
  303. }
  304. }
  305. impl From<crate::signatory::RotateKeyArguments> for RotationRequest {
  306. fn from(value: crate::signatory::RotateKeyArguments) -> Self {
  307. Self {
  308. unit: Some(value.unit.into()),
  309. max_order: value.max_order.into(),
  310. input_fee_ppk: value.input_fee_ppk,
  311. }
  312. }
  313. }
  314. impl TryInto<crate::signatory::RotateKeyArguments> for RotationRequest {
  315. type Error = Status;
  316. fn try_into(self) -> Result<crate::signatory::RotateKeyArguments, Self::Error> {
  317. Ok(crate::signatory::RotateKeyArguments {
  318. unit: self
  319. .unit
  320. .ok_or(Status::invalid_argument("unit not set"))?
  321. .try_into()?,
  322. max_order: self
  323. .max_order
  324. .try_into()
  325. .map_err(|_| Status::invalid_argument("Invalid max_order"))?,
  326. input_fee_ppk: self.input_fee_ppk,
  327. })
  328. }
  329. }
  330. impl From<cdk_common::KeySetInfo> for KeySet {
  331. fn from(value: cdk_common::KeySetInfo) -> Self {
  332. Self {
  333. id: value.id.into(),
  334. unit: Some(value.unit.into()),
  335. active: value.active,
  336. input_fee_ppk: value.input_fee_ppk,
  337. keys: Default::default(),
  338. final_expiry: value.final_expiry,
  339. }
  340. }
  341. }
  342. impl TryInto<cdk_common::KeySetInfo> for KeySet {
  343. type Error = cdk_common::Error;
  344. fn try_into(self) -> Result<cdk_common::KeySetInfo, Self::Error> {
  345. Ok(cdk_common::KeySetInfo {
  346. id: self.id.try_into()?,
  347. unit: self
  348. .unit
  349. .ok_or(cdk_common::Error::Custom(INTERNAL_ERROR.to_owned()))?
  350. .try_into()
  351. .map_err(|_| cdk_common::Error::Custom("Invalid unit encoding".to_owned()))?,
  352. active: self.active,
  353. input_fee_ppk: self.input_fee_ppk,
  354. final_expiry: self.final_expiry,
  355. })
  356. }
  357. }