convert.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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, Id, 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: Id::from_bytes(&self.id)?,
  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_bytes(),
  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. version: Default::default(),
  75. }
  76. }
  77. }
  78. impl From<cdk_common::Error> for Error {
  79. fn from(err: cdk_common::Error) -> Self {
  80. let code = match err {
  81. cdk_common::Error::AmountError(_) => ErrorCode::AmountOutsideLimit,
  82. cdk_common::Error::DuplicateInputs => ErrorCode::DuplicateInputsProvided,
  83. cdk_common::Error::DuplicateOutputs => ErrorCode::DuplicateInputsProvided,
  84. cdk_common::Error::UnknownKeySet => ErrorCode::KeysetNotKnown,
  85. cdk_common::Error::InactiveKeyset => ErrorCode::KeysetInactive,
  86. _ => ErrorCode::Unspecified,
  87. };
  88. Error {
  89. code: code.into(),
  90. detail: err.to_string(),
  91. }
  92. }
  93. }
  94. impl From<Error> for cdk_common::Error {
  95. fn from(val: Error) -> Self {
  96. match val.code.try_into().expect("valid code") {
  97. ErrorCode::AmountOutsideLimit => {
  98. cdk_common::Error::AmountError(cdk_common::amount::Error::AmountOverflow)
  99. }
  100. ErrorCode::DuplicateInputsProvided => cdk_common::Error::DuplicateInputs,
  101. ErrorCode::KeysetNotKnown => cdk_common::Error::UnknownKeySet,
  102. ErrorCode::KeysetInactive => cdk_common::Error::InactiveKeyset,
  103. ErrorCode::Unspecified => cdk_common::Error::Custom(val.detail),
  104. _ => todo!(),
  105. }
  106. }
  107. }
  108. impl From<cdk_common::BlindSignatureDleq> for BlindSignatureDleq {
  109. fn from(value: cdk_common::BlindSignatureDleq) -> Self {
  110. BlindSignatureDleq {
  111. e: value.e.as_secret_bytes().to_vec(),
  112. s: value.s.as_secret_bytes().to_vec(),
  113. }
  114. }
  115. }
  116. impl TryInto<cdk_common::BlindSignatureDleq> for BlindSignatureDleq {
  117. type Error = cdk_common::error::Error;
  118. fn try_into(self) -> Result<cdk_common::BlindSignatureDleq, Self::Error> {
  119. Ok(cdk_common::BlindSignatureDleq {
  120. e: cdk_common::SecretKey::from_slice(&self.e)?,
  121. s: cdk_common::SecretKey::from_slice(&self.s)?,
  122. })
  123. }
  124. }
  125. impl From<cdk_common::BlindSignature> for BlindSignature {
  126. fn from(value: cdk_common::BlindSignature) -> Self {
  127. BlindSignature {
  128. amount: value.amount.into(),
  129. blinded_secret: value.c.to_bytes().to_vec(),
  130. keyset_id: value.keyset_id.to_bytes(),
  131. dleq: value.dleq.map(|x| x.into()),
  132. }
  133. }
  134. }
  135. impl From<Vec<cdk_common::Proof>> for Proofs {
  136. fn from(value: Vec<cdk_common::Proof>) -> Self {
  137. Proofs {
  138. proof: value.into_iter().map(|x| x.into()).collect(),
  139. operation: Operation::Unspecified.into(),
  140. correlation_id: "".to_owned(),
  141. }
  142. }
  143. }
  144. impl From<cdk_common::Proof> for Proof {
  145. fn from(value: cdk_common::Proof) -> Self {
  146. Proof {
  147. amount: value.amount.into(),
  148. keyset_id: value.keyset_id.to_bytes(),
  149. secret: value.secret.to_bytes(),
  150. c: value.c.to_bytes().to_vec(),
  151. }
  152. }
  153. }
  154. impl TryInto<cdk_common::Proof> for Proof {
  155. type Error = Status;
  156. fn try_into(self) -> Result<cdk_common::Proof, Self::Error> {
  157. let secret = if let Ok(str) = String::from_utf8(self.secret.clone()) {
  158. str
  159. } else {
  160. hex::encode(&self.secret)
  161. };
  162. Ok(cdk_common::Proof {
  163. amount: self.amount.into(),
  164. keyset_id: Id::from_bytes(&self.keyset_id)
  165. .map_err(|e| Status::from_error(Box::new(e)))?,
  166. secret: Secret::new(secret),
  167. c: cdk_common::PublicKey::from_slice(&self.c)
  168. .map_err(|e| Status::from_error(Box::new(e)))?,
  169. witness: None,
  170. dleq: None,
  171. })
  172. }
  173. }
  174. impl TryInto<cdk_common::BlindSignature> for BlindSignature {
  175. type Error = cdk_common::error::Error;
  176. fn try_into(self) -> Result<cdk_common::BlindSignature, Self::Error> {
  177. Ok(cdk_common::BlindSignature {
  178. amount: self.amount.into(),
  179. c: cdk_common::PublicKey::from_slice(&self.blinded_secret)?,
  180. keyset_id: Id::from_bytes(&self.keyset_id)?,
  181. dleq: self.dleq.map(|dleq| dleq.try_into()).transpose()?,
  182. })
  183. }
  184. }
  185. impl From<cdk_common::BlindedMessage> for BlindedMessage {
  186. fn from(value: cdk_common::BlindedMessage) -> Self {
  187. BlindedMessage {
  188. amount: value.amount.into(),
  189. keyset_id: value.keyset_id.to_bytes(),
  190. blinded_secret: value.blinded_secret.to_bytes().to_vec(),
  191. }
  192. }
  193. }
  194. impl TryInto<cdk_common::BlindedMessage> for BlindedMessage {
  195. type Error = Status;
  196. fn try_into(self) -> Result<cdk_common::BlindedMessage, Self::Error> {
  197. Ok(cdk_common::BlindedMessage {
  198. amount: self.amount.into(),
  199. keyset_id: Id::from_bytes(&self.keyset_id)
  200. .map_err(|e| Status::from_error(Box::new(e)))?,
  201. blinded_secret: cdk_common::PublicKey::from_slice(&self.blinded_secret)
  202. .map_err(|e| Status::from_error(Box::new(e)))?,
  203. witness: None,
  204. })
  205. }
  206. }
  207. impl From<()> for EmptyRequest {
  208. fn from(_: ()) -> Self {
  209. EmptyRequest {}
  210. }
  211. }
  212. impl TryInto<()> for EmptyRequest {
  213. type Error = cdk_common::error::Error;
  214. fn try_into(self) -> Result<(), Self::Error> {
  215. Ok(())
  216. }
  217. }
  218. impl From<cdk_common::CurrencyUnit> for CurrencyUnit {
  219. fn from(value: cdk_common::CurrencyUnit) -> Self {
  220. match value {
  221. cdk_common::CurrencyUnit::Sat => CurrencyUnit {
  222. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  223. CurrencyUnitType::Sat.into(),
  224. )),
  225. },
  226. cdk_common::CurrencyUnit::Msat => CurrencyUnit {
  227. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  228. CurrencyUnitType::Msat.into(),
  229. )),
  230. },
  231. cdk_common::CurrencyUnit::Usd => CurrencyUnit {
  232. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  233. CurrencyUnitType::Usd.into(),
  234. )),
  235. },
  236. cdk_common::CurrencyUnit::Eur => CurrencyUnit {
  237. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  238. CurrencyUnitType::Eur.into(),
  239. )),
  240. },
  241. cdk_common::CurrencyUnit::Auth => CurrencyUnit {
  242. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  243. CurrencyUnitType::Auth.into(),
  244. )),
  245. },
  246. cdk_common::CurrencyUnit::Custom(name) => CurrencyUnit {
  247. currency_unit: Some(currency_unit::CurrencyUnit::CustomUnit(name)),
  248. },
  249. _ => unreachable!(),
  250. }
  251. }
  252. }
  253. impl TryInto<cdk_common::CurrencyUnit> for CurrencyUnit {
  254. type Error = Status;
  255. fn try_into(self) -> Result<cdk_common::CurrencyUnit, Self::Error> {
  256. match self.currency_unit {
  257. Some(currency_unit::CurrencyUnit::Unit(u)) => match u
  258. .try_into()
  259. .map_err(|_| Status::invalid_argument("Invalid currency unit"))?
  260. {
  261. CurrencyUnitType::Sat => Ok(cdk_common::CurrencyUnit::Sat),
  262. CurrencyUnitType::Msat => Ok(cdk_common::CurrencyUnit::Msat),
  263. CurrencyUnitType::Usd => Ok(cdk_common::CurrencyUnit::Usd),
  264. CurrencyUnitType::Eur => Ok(cdk_common::CurrencyUnit::Eur),
  265. CurrencyUnitType::Auth => Ok(cdk_common::CurrencyUnit::Auth),
  266. CurrencyUnitType::Unspecified => {
  267. Err(Status::invalid_argument("Current unit is not specified"))
  268. }
  269. },
  270. Some(currency_unit::CurrencyUnit::CustomUnit(name)) => {
  271. Ok(cdk_common::CurrencyUnit::Custom(name))
  272. }
  273. None => Err(Status::invalid_argument("Currency unit not set")),
  274. }
  275. }
  276. }
  277. impl TryInto<cdk_common::KeySet> for KeySet {
  278. type Error = cdk_common::error::Error;
  279. fn try_into(self) -> Result<cdk_common::KeySet, Self::Error> {
  280. Ok(cdk_common::KeySet {
  281. id: Id::from_bytes(&self.id)?,
  282. unit: self
  283. .unit
  284. .ok_or(cdk_common::error::Error::Custom(INTERNAL_ERROR.to_owned()))?
  285. .try_into()
  286. .map_err(|_| cdk_common::Error::Custom("Invalid unit encoding".to_owned()))?,
  287. keys: cdk_common::Keys::new(
  288. self.keys
  289. .ok_or(cdk_common::error::Error::Custom(INTERNAL_ERROR.to_owned()))?
  290. .keys
  291. .into_iter()
  292. .map(|(k, v)| cdk_common::PublicKey::from_slice(&v).map(|pk| (k.into(), pk)))
  293. .collect::<Result<BTreeMap<cdk_common::Amount, cdk_common::PublicKey>, _>>()?,
  294. ),
  295. final_expiry: self.final_expiry,
  296. })
  297. }
  298. }
  299. impl From<crate::signatory::RotateKeyArguments> for RotationRequest {
  300. fn from(value: crate::signatory::RotateKeyArguments) -> Self {
  301. Self {
  302. unit: Some(value.unit.into()),
  303. amounts: value.amounts,
  304. input_fee_ppk: value.input_fee_ppk,
  305. }
  306. }
  307. }
  308. impl TryInto<crate::signatory::RotateKeyArguments> for RotationRequest {
  309. type Error = Status;
  310. fn try_into(self) -> Result<crate::signatory::RotateKeyArguments, Self::Error> {
  311. Ok(crate::signatory::RotateKeyArguments {
  312. unit: self
  313. .unit
  314. .ok_or(Status::invalid_argument("unit not set"))?
  315. .try_into()?,
  316. amounts: self.amounts,
  317. input_fee_ppk: self.input_fee_ppk,
  318. })
  319. }
  320. }
  321. impl From<cdk_common::KeySetInfo> for KeySet {
  322. fn from(value: cdk_common::KeySetInfo) -> Self {
  323. Self {
  324. id: value.id.to_bytes(),
  325. unit: Some(value.unit.into()),
  326. active: value.active,
  327. input_fee_ppk: value.input_fee_ppk,
  328. keys: Default::default(),
  329. final_expiry: value.final_expiry,
  330. version: Default::default(),
  331. }
  332. }
  333. }
  334. impl TryInto<cdk_common::KeySetInfo> for KeySet {
  335. type Error = cdk_common::Error;
  336. fn try_into(self) -> Result<cdk_common::KeySetInfo, Self::Error> {
  337. Ok(cdk_common::KeySetInfo {
  338. id: Id::from_bytes(&self.id)?,
  339. unit: self
  340. .unit
  341. .ok_or(cdk_common::Error::Custom(INTERNAL_ERROR.to_owned()))?
  342. .try_into()
  343. .map_err(|_| cdk_common::Error::Custom("Invalid unit encoding".to_owned()))?,
  344. active: self.active,
  345. input_fee_ppk: self.input_fee_ppk,
  346. final_expiry: self.final_expiry,
  347. })
  348. }
  349. }