convert.rs 16 KB

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