Move monero ser/deser to monero module

This commit is contained in:
rishflab 2021-01-08 10:44:31 +11:00
parent e7c00d742e
commit f64eede5d8
5 changed files with 101 additions and 105 deletions

View File

@ -4,8 +4,8 @@ use serde::{Deserialize, Serialize};
use crate::{ use crate::{
bitcoin::{EncryptedSignature, TxCancel, TxRefund}, bitcoin::{EncryptedSignature, TxCancel, TxRefund},
monero, monero,
monero::monero_private_key,
protocol::{alice, alice::swap::AliceState}, protocol::{alice, alice::swap::AliceState},
serde::monero_private_key,
SwapAmounts, SwapAmounts,
}; };

View File

@ -16,7 +16,7 @@
missing_copy_implementations missing_copy_implementations
)] )]
use ::serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::fmt::{self, Display}; use std::fmt::{self, Display};
pub mod bitcoin; pub mod bitcoin;
@ -26,7 +26,6 @@ pub mod database;
pub mod monero; pub mod monero;
pub mod network; pub mod network;
pub mod protocol; pub mod protocol;
pub mod serde;
pub mod trace; pub mod trace;
pub type Never = std::convert::Infallible; pub type Never = std::convert::Infallible;
@ -52,7 +51,7 @@ pub struct SwapAmounts {
#[serde(with = "::bitcoin::util::amount::serde::as_sat")] #[serde(with = "::bitcoin::util::amount::serde::as_sat")]
pub btc: bitcoin::Amount, pub btc: bitcoin::Amount,
/// Amount of XMR to swap. /// Amount of XMR to swap.
#[serde(with = "serde::monero_amount")] #[serde(with = "monero::monero_amount")]
pub xmr: monero::Amount, pub xmr: monero::Amount,
} }

View File

@ -15,7 +15,7 @@ use std::{
str::FromStr, str::FromStr,
}; };
use crate::{bitcoin, serde::monero_private_key}; use crate::bitcoin;
pub use ::monero::{Network, PrivateKey, PublicKey}; pub use ::monero::{Network, PrivateKey, PublicKey};
pub use curve25519_dalek::scalar::Scalar; pub use curve25519_dalek::scalar::Scalar;
@ -217,6 +217,75 @@ pub trait CreateWalletForOutput {
#[error("Overflow, cannot convert {0} to u64")] #[error("Overflow, cannot convert {0} to u64")]
pub struct OverflowError(pub String); pub struct OverflowError(pub String);
pub mod monero_private_key {
use monero::{
consensus::{Decodable, Encodable},
PrivateKey,
};
use serde::{de, de::Visitor, ser::Error, Deserializer, Serializer};
use std::{fmt, io::Cursor};
struct BytesVisitor;
impl<'de> Visitor<'de> for BytesVisitor {
type Value = PrivateKey;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a byte array representing a Monero private key")
}
fn visit_bytes<E>(self, s: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
let mut s = s;
PrivateKey::consensus_decode(&mut s).map_err(|err| E::custom(format!("{:?}", err)))
}
}
pub fn serialize<S>(x: &PrivateKey, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut bytes = Cursor::new(vec![]);
x.consensus_encode(&mut bytes)
.map_err(|err| S::Error::custom(format!("{:?}", err)))?;
s.serialize_bytes(bytes.into_inner().as_ref())
}
pub fn deserialize<'de, D>(
deserializer: D,
) -> Result<PrivateKey, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de>,
{
let key = deserializer.deserialize_bytes(BytesVisitor)?;
Ok(key)
}
}
pub mod monero_amount {
use crate::monero::Amount;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S>(x: &Amount, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_u64(x.as_piconero())
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Amount, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de>,
{
let picos = u64::deserialize(deserializer)?;
let amount = Amount::from_piconero(picos);
Ok(amount)
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@ -278,4 +347,31 @@ mod tests {
&OverflowError(overflow_pics.to_owned()) &OverflowError(overflow_pics.to_owned())
); );
} }
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct MoneroPrivateKey(#[serde(with = "monero_private_key")] crate::monero::PrivateKey);
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct MoneroAmount(#[serde(with = "monero_amount")] crate::monero::Amount);
#[test]
fn serde_monero_private_key() {
let key = MoneroPrivateKey(monero::PrivateKey::from_scalar(
crate::monero::Scalar::random(&mut OsRng),
));
let encoded = serde_cbor::to_vec(&key).unwrap();
let decoded: MoneroPrivateKey = serde_cbor::from_slice(&encoded).unwrap();
assert_eq!(key, decoded);
}
#[test]
fn serde_monero_amount() {
let amount = MoneroAmount(crate::monero::Amount::from_piconero(1000));
let encoded = serde_cbor::to_vec(&amount).unwrap();
let decoded: MoneroAmount = serde_cbor::from_slice(&encoded).unwrap();
assert_eq!(amount, decoded);
}
} }

View File

@ -15,8 +15,8 @@ use crate::{
Transaction, TransactionBlockHeight, TxCancel, Txid, WatchForRawTransaction, Transaction, TransactionBlockHeight, TxCancel, Txid, WatchForRawTransaction,
}, },
monero, monero,
monero::monero_private_key,
protocol::{alice, bob}, protocol::{alice, bob},
serde::monero_private_key,
ExpiredTimelocks, ExpiredTimelocks,
}; };

View File

@ -1,99 +0,0 @@
pub mod monero_private_key {
use monero::{
consensus::{Decodable, Encodable},
PrivateKey,
};
use serde::{de, de::Visitor, ser::Error, Deserializer, Serializer};
use std::{fmt, io::Cursor};
struct BytesVisitor;
impl<'de> Visitor<'de> for BytesVisitor {
type Value = PrivateKey;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "a byte array representing a Monero private key")
}
fn visit_bytes<E>(self, s: &[u8]) -> Result<Self::Value, E>
where
E: de::Error,
{
let mut s = s;
PrivateKey::consensus_decode(&mut s).map_err(|err| E::custom(format!("{:?}", err)))
}
}
pub fn serialize<S>(x: &PrivateKey, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut bytes = Cursor::new(vec![]);
x.consensus_encode(&mut bytes)
.map_err(|err| S::Error::custom(format!("{:?}", err)))?;
s.serialize_bytes(bytes.into_inner().as_ref())
}
pub fn deserialize<'de, D>(
deserializer: D,
) -> Result<PrivateKey, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de>,
{
let key = deserializer.deserialize_bytes(BytesVisitor)?;
Ok(key)
}
}
pub mod monero_amount {
use crate::monero::Amount;
use serde::{Deserialize, Deserializer, Serializer};
pub fn serialize<S>(x: &Amount, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.serialize_u64(x.as_piconero())
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Amount, <D as Deserializer<'de>>::Error>
where
D: Deserializer<'de>,
{
let picos = u64::deserialize(deserializer)?;
let amount = Amount::from_piconero(picos);
Ok(amount)
}
}
#[cfg(test)]
mod tests {
use super::*;
use rand::rngs::OsRng;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct MoneroPrivateKey(#[serde(with = "monero_private_key")] crate::monero::PrivateKey);
#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct MoneroAmount(#[serde(with = "monero_amount")] crate::monero::Amount);
#[test]
fn serde_monero_private_key() {
let key = MoneroPrivateKey(monero::PrivateKey::from_scalar(
crate::monero::Scalar::random(&mut OsRng),
));
let encoded = serde_cbor::to_vec(&key).unwrap();
let decoded: MoneroPrivateKey = serde_cbor::from_slice(&encoded).unwrap();
assert_eq!(key, decoded);
}
#[test]
fn serde_monero_amount() {
let amount = MoneroAmount(crate::monero::Amount::from_piconero(1000));
let encoded = serde_cbor::to_vec(&amount).unwrap();
let decoded: MoneroAmount = serde_cbor::from_slice(&encoded).unwrap();
assert_eq!(amount, decoded);
}
}