convert.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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, HTLCWitness, P2PKWitness, 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 From<cdk_common::ProofDleq> for ProofDleq {
  176. fn from(value: cdk_common::ProofDleq) -> Self {
  177. ProofDleq {
  178. e: value.e.as_secret_bytes().to_vec(),
  179. s: value.s.as_secret_bytes().to_vec(),
  180. r: value.r.as_secret_bytes().to_vec(),
  181. }
  182. }
  183. }
  184. impl TryInto<cdk_common::ProofDleq> for ProofDleq {
  185. type Error = Status;
  186. fn try_into(self) -> Result<cdk_common::ProofDleq, Self::Error> {
  187. Ok(cdk_common::ProofDleq {
  188. e: cdk_common::SecretKey::from_slice(&self.e)
  189. .map_err(|e| Status::from_error(Box::new(e)))?,
  190. s: cdk_common::SecretKey::from_slice(&self.s)
  191. .map_err(|e| Status::from_error(Box::new(e)))?,
  192. r: cdk_common::SecretKey::from_slice(&self.r)
  193. .map_err(|e| Status::from_error(Box::new(e)))?,
  194. })
  195. }
  196. }
  197. impl TryInto<cdk_common::BlindSignature> for BlindSignature {
  198. type Error = cdk_common::error::Error;
  199. fn try_into(self) -> Result<cdk_common::BlindSignature, Self::Error> {
  200. Ok(cdk_common::BlindSignature {
  201. amount: self.amount.into(),
  202. c: cdk_common::PublicKey::from_slice(&self.blinded_secret)?,
  203. keyset_id: self.keyset_id.parse().expect("Invalid keyset id"),
  204. dleq: self.dleq.map(|dleq| dleq.try_into()).transpose()?,
  205. })
  206. }
  207. }
  208. impl From<cdk_common::BlindedMessage> for BlindedMessage {
  209. fn from(value: cdk_common::BlindedMessage) -> Self {
  210. BlindedMessage {
  211. amount: value.amount.into(),
  212. keyset_id: value.keyset_id.to_string(),
  213. blinded_secret: value.blinded_secret.to_bytes().to_vec(),
  214. }
  215. }
  216. }
  217. impl TryInto<cdk_common::BlindedMessage> for BlindedMessage {
  218. type Error = Status;
  219. fn try_into(self) -> Result<cdk_common::BlindedMessage, Self::Error> {
  220. Ok(cdk_common::BlindedMessage {
  221. amount: self.amount.into(),
  222. keyset_id: self
  223. .keyset_id
  224. .parse()
  225. .map_err(|e| Status::from_error(Box::new(e)))?,
  226. blinded_secret: cdk_common::PublicKey::from_slice(&self.blinded_secret)
  227. .map_err(|e| Status::from_error(Box::new(e)))?,
  228. witness: None,
  229. })
  230. }
  231. }
  232. impl From<cdk_common::Witness> for Witness {
  233. fn from(value: cdk_common::Witness) -> Self {
  234. match value {
  235. cdk_common::Witness::P2PKWitness(P2PKWitness { signatures }) => Witness {
  236. witness_type: Some(witness::WitnessType::P2pkWitness(P2pkWitness {
  237. signatures,
  238. })),
  239. },
  240. cdk_common::Witness::HTLCWitness(HTLCWitness {
  241. preimage,
  242. signatures,
  243. }) => Witness {
  244. witness_type: Some(witness::WitnessType::HtlcWitness(HtlcWitness {
  245. preimage,
  246. signatures: signatures.unwrap_or_default(),
  247. })),
  248. },
  249. }
  250. }
  251. }
  252. impl TryInto<cdk_common::Witness> for Witness {
  253. type Error = Status;
  254. fn try_into(self) -> Result<cdk_common::Witness, Self::Error> {
  255. match self.witness_type {
  256. Some(witness::WitnessType::P2pkWitness(P2pkWitness { signatures })) => {
  257. Ok(P2PKWitness { signatures }.into())
  258. }
  259. Some(witness::WitnessType::HtlcWitness(hltc_witness)) => Ok(HTLCWitness {
  260. preimage: hltc_witness.preimage,
  261. signatures: if hltc_witness.signatures.is_empty() {
  262. None
  263. } else {
  264. Some(hltc_witness.signatures)
  265. },
  266. }
  267. .into()),
  268. None => Err(Status::invalid_argument("Witness type not set")),
  269. }
  270. }
  271. }
  272. impl From<()> for EmptyRequest {
  273. fn from(_: ()) -> Self {
  274. EmptyRequest {}
  275. }
  276. }
  277. impl TryInto<()> for EmptyRequest {
  278. type Error = cdk_common::error::Error;
  279. fn try_into(self) -> Result<(), Self::Error> {
  280. Ok(())
  281. }
  282. }
  283. impl From<cdk_common::CurrencyUnit> for CurrencyUnit {
  284. fn from(value: cdk_common::CurrencyUnit) -> Self {
  285. match value {
  286. cdk_common::CurrencyUnit::Sat => CurrencyUnit {
  287. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  288. CurrencyUnitType::Sat.into(),
  289. )),
  290. },
  291. cdk_common::CurrencyUnit::Msat => CurrencyUnit {
  292. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  293. CurrencyUnitType::Msat.into(),
  294. )),
  295. },
  296. cdk_common::CurrencyUnit::Usd => CurrencyUnit {
  297. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  298. CurrencyUnitType::Usd.into(),
  299. )),
  300. },
  301. cdk_common::CurrencyUnit::Eur => CurrencyUnit {
  302. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  303. CurrencyUnitType::Eur.into(),
  304. )),
  305. },
  306. cdk_common::CurrencyUnit::Auth => CurrencyUnit {
  307. currency_unit: Some(currency_unit::CurrencyUnit::Unit(
  308. CurrencyUnitType::Auth.into(),
  309. )),
  310. },
  311. cdk_common::CurrencyUnit::Custom(name) => CurrencyUnit {
  312. currency_unit: Some(currency_unit::CurrencyUnit::CustomUnit(name)),
  313. },
  314. _ => unreachable!(),
  315. }
  316. }
  317. }
  318. impl TryInto<cdk_common::CurrencyUnit> for CurrencyUnit {
  319. type Error = Status;
  320. fn try_into(self) -> Result<cdk_common::CurrencyUnit, Self::Error> {
  321. match self.currency_unit {
  322. Some(currency_unit::CurrencyUnit::Unit(u)) => match u
  323. .try_into()
  324. .map_err(|_| Status::invalid_argument("Invalid currency unit"))?
  325. {
  326. CurrencyUnitType::Sat => Ok(cdk_common::CurrencyUnit::Sat),
  327. CurrencyUnitType::Msat => Ok(cdk_common::CurrencyUnit::Msat),
  328. CurrencyUnitType::Usd => Ok(cdk_common::CurrencyUnit::Usd),
  329. CurrencyUnitType::Eur => Ok(cdk_common::CurrencyUnit::Eur),
  330. CurrencyUnitType::Auth => Ok(cdk_common::CurrencyUnit::Auth),
  331. CurrencyUnitType::Unspecified => {
  332. Err(Status::invalid_argument("Current unit is not specified"))
  333. }
  334. },
  335. Some(currency_unit::CurrencyUnit::CustomUnit(name)) => {
  336. Ok(cdk_common::CurrencyUnit::Custom(name))
  337. }
  338. None => Err(Status::invalid_argument("Currency unit not set")),
  339. }
  340. }
  341. }
  342. impl TryInto<cdk_common::KeySet> for KeySet {
  343. type Error = cdk_common::error::Error;
  344. fn try_into(self) -> Result<cdk_common::KeySet, Self::Error> {
  345. Ok(cdk_common::KeySet {
  346. id: self
  347. .id
  348. .parse()
  349. .map_err(|_| cdk_common::error::Error::Custom("Invalid ID".to_owned()))?,
  350. unit: self
  351. .unit
  352. .ok_or(cdk_common::error::Error::Custom(INTERNAL_ERROR.to_owned()))?
  353. .try_into()
  354. .map_err(|_| cdk_common::Error::Custom("Invalid unit encoding".to_owned()))?,
  355. keys: cdk_common::Keys::new(
  356. self.keys
  357. .ok_or(cdk_common::error::Error::Custom(INTERNAL_ERROR.to_owned()))?
  358. .keys
  359. .into_iter()
  360. .map(|(k, v)| cdk_common::PublicKey::from_slice(&v).map(|pk| (k.into(), pk)))
  361. .collect::<Result<BTreeMap<cdk_common::Amount, cdk_common::PublicKey>, _>>()?,
  362. ),
  363. final_expiry: self.final_expiry,
  364. })
  365. }
  366. }
  367. impl From<crate::signatory::RotateKeyArguments> for RotationRequest {
  368. fn from(value: crate::signatory::RotateKeyArguments) -> Self {
  369. Self {
  370. unit: Some(value.unit.into()),
  371. max_order: value.max_order.into(),
  372. input_fee_ppk: value.input_fee_ppk,
  373. }
  374. }
  375. }
  376. impl TryInto<crate::signatory::RotateKeyArguments> for RotationRequest {
  377. type Error = Status;
  378. fn try_into(self) -> Result<crate::signatory::RotateKeyArguments, Self::Error> {
  379. Ok(crate::signatory::RotateKeyArguments {
  380. unit: self
  381. .unit
  382. .ok_or(Status::invalid_argument("unit not set"))?
  383. .try_into()?,
  384. max_order: self
  385. .max_order
  386. .try_into()
  387. .map_err(|_| Status::invalid_argument("Invalid max_order"))?,
  388. input_fee_ppk: self.input_fee_ppk,
  389. })
  390. }
  391. }
  392. impl From<cdk_common::KeySetInfo> for KeySet {
  393. fn from(value: cdk_common::KeySetInfo) -> Self {
  394. Self {
  395. id: value.id.into(),
  396. unit: Some(value.unit.into()),
  397. active: value.active,
  398. input_fee_ppk: value.input_fee_ppk,
  399. keys: Default::default(),
  400. final_expiry: value.final_expiry,
  401. }
  402. }
  403. }
  404. impl TryInto<cdk_common::KeySetInfo> for KeySet {
  405. type Error = cdk_common::Error;
  406. fn try_into(self) -> Result<cdk_common::KeySetInfo, Self::Error> {
  407. Ok(cdk_common::KeySetInfo {
  408. id: self.id.try_into()?,
  409. unit: self
  410. .unit
  411. .ok_or(cdk_common::Error::Custom(INTERNAL_ERROR.to_owned()))?
  412. .try_into()
  413. .map_err(|_| cdk_common::Error::Custom("Invalid unit encoding".to_owned()))?,
  414. active: self.active,
  415. input_fee_ppk: self.input_fee_ppk,
  416. final_expiry: self.final_expiry,
  417. })
  418. }
  419. }