convert.rs 13 KB

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