convert.rs 13 KB

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