[CONTRACTS] update/rename mwixnet onion classes (#719)

* update/rename mwixnet onion classes

* fix serialize trait errors
This commit is contained in:
Yeastplume 2024-08-27 13:25:18 +01:00 committed by GitHub
parent 0b24640c89
commit 96b5d240bb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 52 additions and 56 deletions

View file

@ -31,7 +31,7 @@ use crate::libwallet::api_impl::{owner, owner_updater};
use crate::libwallet::contract::types::{ use crate::libwallet::contract::types::{
ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI, ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI,
}; };
use crate::libwallet::mwmixnet::types::{MixnetReqCreationParams, SwapReq}; use crate::libwallet::mwixnet::types::{MixnetReqCreationParams, SwapReq};
use crate::libwallet::{ use crate::libwallet::{
AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient,
NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress,
@ -831,7 +831,7 @@ where
} }
/// Create MXMixnet request /// Create MXMixnet request
pub fn create_mwmixnet_req( pub fn create_mwixnet_req(
&self, &self,
keychain_mask: Option<&SecretKey>, keychain_mask: Option<&SecretKey>,
params: &MixnetReqCreationParams, params: &MixnetReqCreationParams,
@ -840,7 +840,7 @@ where
) -> Result<SwapReq, Error> { ) -> Result<SwapReq, Error> {
let mut w_lock = self.wallet_inst.lock(); let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?; let w = w_lock.lc_provider()?.wallet_inst()?;
owner::create_mwmixnet_req(&mut **w, keychain_mask, params, slate) owner::create_mwixnet_req(&mut **w, keychain_mask, params, slate)
} }
/// Processes an invoice tranaction created by another party, essentially /// Processes an invoice tranaction created by another party, essentially

View file

@ -22,8 +22,8 @@ use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self}; use impls::test_framework::{self};
use libwallet::contract::my_fee_contribution; use libwallet::contract::my_fee_contribution;
use libwallet::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI}; use libwallet::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI};
use libwallet::mwmixnet::onion::crypto::secp; use libwallet::mwixnet::onion::crypto::secp;
use libwallet::mwmixnet::types::MixnetReqCreationParams; use libwallet::mwixnet::types::MixnetReqCreationParams;
use libwallet::{Slate, SlateState, TxLogEntryType}; use libwallet::{Slate, SlateState, TxLogEntryType};
use std::sync::atomic::Ordering; use std::sync::atomic::Ordering;
use std::thread; use std::thread;
@ -33,8 +33,8 @@ use std::time::Duration;
mod common; mod common;
use common::{clean_output_dir, create_wallets, setup}; use common::{clean_output_dir, create_wallets, setup};
/// contract SRS flow - just creating an mwmixnet tx at the moment /// contract SRS flow - just creating an mwixnet tx at the moment
fn contract_srs_mwmixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
// create two wallets and mine 4 blocks in each (we want both to have balance to get a payjoin) // create two wallets and mine 4 blocks in each (we want both to have balance to get a payjoin)
let (wallets, chain, stopper, mut bh) = let (wallets, chain, stopper, mut bh) =
create_wallets(vec![vec![("default", 4)], vec![("default", 4)]], test_dir).unwrap(); create_wallets(vec![vec![("default", 4)], vec![("default", 4)]], test_dir).unwrap();
@ -89,7 +89,7 @@ fn contract_srs_mwmixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet
server_keys: vec![server_key_1, server_key_2], server_keys: vec![server_key_1, server_key_2],
fee_per_hop: 50_000_000, fee_per_hop: 50_000_000,
}; };
//api.create_mwmixnet_req(send_mask, &params, &slate)?; //api.create_mwixnet_req(send_mask, &params, &slate)?;
Ok(()) Ok(())
})?; })?;
@ -147,10 +147,10 @@ fn contract_srs_mwmixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet
} }
#[test] #[test]
fn wallet_contract_srs_mwmixnet_tx() -> Result<(), libwallet::Error> { fn wallet_contract_srs_mwixnet_tx() -> Result<(), libwallet::Error> {
let test_dir = "test_output/contract_srs_mwmixnet_tx"; let test_dir = "test_output/contract_srs_mwixnet_tx";
setup(test_dir); setup(test_dir);
contract_srs_mwmixnet_tx_impl(test_dir)?; contract_srs_mwixnet_tx_impl(test_dir)?;
clean_output_dir(test_dir); clean_output_dir(test_dir);
Ok(()) Ok(())
} }

View file

@ -42,7 +42,7 @@ grin_wallet_config = { path = "../config", version = "5.4.0-contracts.0" }
grin_secp256k1zkp = { version = "0.7.12", features = ["bullet-proof-sizing"]} grin_secp256k1zkp = { version = "0.7.12", features = ["bullet-proof-sizing"]}
#mwmixnet onion #mwixnet onion
chacha20 = "0.8.1" chacha20 = "0.8.1"
hmac = { version = "0.12.0", features = ["std"]} hmac = { version = "0.12.0", features = ["std"]}

View file

@ -30,8 +30,8 @@ use crate::util::{OnionV3Address, OnionV3AddressError};
use crate::api_impl::owner_updater::StatusMessage; use crate::api_impl::owner_updater::StatusMessage;
use crate::contract::types::{ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI}; use crate::contract::types::{ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI};
use crate::grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType}; use crate::grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType};
use crate::mwmixnet::onion::create_onion; use crate::mwixnet::onion::create_onion;
use crate::mwmixnet::types::{ use crate::mwixnet::types::{
add_excess, new_hop, random_secret, ComSignature, Hop, MixnetReqCreationParams, SwapReq, add_excess, new_hop, random_secret, ComSignature, Hop, MixnetReqCreationParams, SwapReq,
}; };
@ -1604,7 +1604,7 @@ where
} }
/// Create MXMixnet request /// Create MXMixnet request
pub fn create_mwmixnet_req<'a, T: ?Sized, C, K>( pub fn create_mwixnet_req<'a, T: ?Sized, C, K>(
w: &mut T, w: &mut T,
keychain_mask: Option<&SecretKey>, keychain_mask: Option<&SecretKey>,
params: &MixnetReqCreationParams, params: &MixnetReqCreationParams,

View file

@ -67,11 +67,11 @@ pub enum Error {
/// Comsig error /// Comsig error
#[error("Comsig error: {0}")] #[error("Comsig error: {0}")]
ComSig(#[from] crate::mwmixnet::onion::crypto::comsig::ComSigError), ComSig(#[from] crate::mwixnet::onion::crypto::comsig::ComSigError),
/// MwMixnet Onion error /// mwixnet Onion error
#[error("Onion error: {0}")] #[error("Onion error: {0}")]
Onion(#[from] crate::mwmixnet::onion::onion::OnionError), Onion(#[from] crate::mwixnet::onion::onion::OnionError),
/// Callback implementation error conversion /// Callback implementation error conversion
#[error("Trait Implementation error")] #[error("Trait Implementation error")]

View file

@ -52,7 +52,7 @@ mod slate;
pub mod slate_versions; pub mod slate_versions;
pub mod slatepack; pub mod slatepack;
pub mod mwmixnet; pub mod mwixnet;
mod types; mod types;
pub use crate::error::Error; pub use crate::error::Error;

View file

@ -33,10 +33,8 @@ pub struct ComSignature {
/// Error types for Commitment Signatures /// Error types for Commitment Signatures
#[derive(Error, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] #[derive(Error, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum ComSigError { pub enum ComSigError {
/// Invalid com sig
#[error("Commitment signature is invalid")] #[error("Commitment signature is invalid")]
InvalidSig, InvalidSig,
/// SECP Error Wrapper
#[error("Secp256k1zkp error: {0:?}")] #[error("Secp256k1zkp error: {0:?}")]
Secp256k1zkp(secp256k1zkp::Error), Secp256k1zkp(secp256k1zkp::Error),
} }
@ -48,7 +46,6 @@ impl From<secp256k1zkp::Error> for ComSigError {
} }
impl ComSignature { impl ComSignature {
/// Create new Com signature from commit and keys
pub fn new(pub_nonce: &Commitment, s: &SecretKey, t: &SecretKey) -> ComSignature { pub fn new(pub_nonce: &Commitment, s: &SecretKey, t: &SecretKey) -> ComSignature {
ComSignature { ComSignature {
pub_nonce: pub_nonce.to_owned(), pub_nonce: pub_nonce.to_owned(),
@ -58,7 +55,6 @@ impl ComSignature {
} }
#[allow(dead_code)] #[allow(dead_code)]
/// Sign com signature with kernel values
pub fn sign( pub fn sign(
amount: u64, amount: u64,
blind: &SecretKey, blind: &SecretKey,
@ -92,7 +88,6 @@ impl ComSignature {
} }
#[allow(non_snake_case)] #[allow(non_snake_case)]
/// Verify a com sig
pub fn verify(&self, commit: &Commitment, msg: &Vec<u8>) -> Result<(), ComSigError> { pub fn verify(&self, commit: &Commitment, msg: &Vec<u8>) -> Result<(), ComSigError> {
let secp = Secp256k1::with_caps(ContextFlag::Commit); let secp = Secp256k1::with_caps(ContextFlag::Commit);

View file

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! Dalek key wrapper for mwmixnet primitives //! Dalek key wrapper for mwixnet primitives
use super::secp::SecretKey; use super::secp::SecretKey;
@ -183,7 +183,7 @@ pub fn sign(sk: &SecretKey, message: &[u8]) -> Result<DalekSignature, DalekError
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use crate::mwmixnet::onion::test_util::rand_keypair; use crate::mwixnet::onion::test_util::rand_keypair;
use grin_core::ser::{self, ProtocolVersion}; use grin_core::ser::{self, ProtocolVersion};
use grin_util::ToHex; use grin_util::ToHex;
use rand::Rng; use rand::Rng;

View file

@ -12,11 +12,16 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! Onion defn for mwmixnet //! Onion defn for mwixnet
use super::crypto::secp::{self, Commitment, RangeProof, SecretKey}; use super::crypto::secp::{self, Commitment, RangeProof, SecretKey};
use super::util::{read_optional, vec_to_array, write_optional}; use super::util::{read_optional, vec_to_array, write_optional};
use std::convert::TryFrom;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::result::Result;
use chacha20::cipher::{NewCipher, StreamCipher}; use chacha20::cipher::{NewCipher, StreamCipher};
use chacha20::{ChaCha20, Key, Nonce}; use chacha20::{ChaCha20, Key, Nonce};
use grin_core::core::FeeFields; use grin_core::core::FeeFields;
@ -27,15 +32,11 @@ use hmac::{Hmac, Mac};
use serde::ser::SerializeStruct; use serde::ser::SerializeStruct;
use serde::Deserialize; use serde::Deserialize;
use sha2::Sha256; use sha2::Sha256;
use std::convert::TryFrom;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::result::Result;
use thiserror::Error; use thiserror::Error;
use x25519_dalek::{PublicKey as xPublicKey, SharedSecret, StaticSecret}; use x25519_dalek::{PublicKey as xPublicKey, SharedSecret, StaticSecret};
type HmacSha256 = Hmac<Sha256>; type HmacSha256 = Hmac<Sha256>;
/// Wrap u8 vec /// Raw bytes alias
pub type RawBytes = Vec<u8>; pub type RawBytes = Vec<u8>;
const CURRENT_ONION_VERSION: u8 = 0; const CURRENT_ONION_VERSION: u8 = 0;
@ -75,24 +76,24 @@ impl Hash for Onion {
/// A single, decrypted/peeled layer of an Onion. /// A single, decrypted/peeled layer of an Onion.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Payload { pub struct Payload {
/// next ephemeral pk /// PK of next server
pub next_ephemeral_pk: xPublicKey, pub next_ephemeral_pk: xPublicKey,
/// excess /// Excess calculation
pub excess: SecretKey, pub excess: SecretKey,
/// fee /// Fee
pub fee: FeeFields, pub fee: FeeFields,
/// proof /// Rangeproof
pub rangeproof: Option<RangeProof>, pub rangeproof: Option<RangeProof>,
} }
impl Payload { impl Payload {
/// Deser a payload /// Deserialize
pub fn deserialize(bytes: &Vec<u8>) -> Result<Payload, ser::Error> { pub fn deserialize(bytes: &Vec<u8>) -> Result<Payload, ser::Error> {
let payload: Payload = ser::deserialize_default(&mut &bytes[..])?; let payload: Payload = ser::deserialize_default(&mut &bytes[..])?;
Ok(payload) Ok(payload)
} }
/// Serialize a payload /// Serialize
pub fn serialize(&self) -> Result<Vec<u8>, ser::Error> { pub fn serialize(&self) -> Result<Vec<u8>, ser::Error> {
let mut vec = vec![]; let mut vec = vec![];
ser::serialize_default(&mut vec, &self)?; ser::serialize_default(&mut vec, &self)?;
@ -142,7 +143,7 @@ pub struct PeeledOnion {
} }
impl Onion { impl Onion {
/// Serialize onion /// Serialize to binary
pub fn serialize(&self) -> Result<Vec<u8>, ser::Error> { pub fn serialize(&self) -> Result<Vec<u8>, ser::Error> {
let mut vec = vec![]; let mut vec = vec![];
ser::serialize_default(&mut vec, &self)?; ser::serialize_default(&mut vec, &self)?;
@ -189,7 +190,7 @@ impl Onion {
} }
} }
/// Create new stream cypher from shared secret /// Create a new stream cipher
pub fn new_stream_cipher(shared_secret: &SharedSecret) -> Result<ChaCha20, OnionError> { pub fn new_stream_cipher(shared_secret: &SharedSecret) -> Result<ChaCha20, OnionError> {
let mut mu_hmac = HmacSha256::new_from_slice(b"MWIXNET")?; let mut mu_hmac = HmacSha256::new_from_slice(b"MWIXNET")?;
mu_hmac.update(shared_secret.as_bytes()); mu_hmac.update(shared_secret.as_bytes());
@ -329,19 +330,19 @@ pub enum OnionError {
/// Invalid Key Length /// Invalid Key Length
#[error("Invalid key length for MAC initialization")] #[error("Invalid key length for MAC initialization")]
InvalidKeyLength, InvalidKeyLength,
/// Serialization error /// Serialization Error
#[error("Serialization error occurred: {0:?}")] #[error("Serialization error occurred: {0:?}")]
SerializationError(ser::Error), SerializationError(ser::Error),
/// Deserialization error /// Deserialization Error
#[error("Deserialization error occurred: {0:?}")] #[error("Deserialization error occurred: {0:?}")]
DeserializationError(ser::Error), DeserializationError(ser::Error),
/// Error calculating blinding factor /// Error calculating blinding factor
#[error("Error calculating blinding factor: {0:?}")] #[error("Error calculating blinding factor: {0:?}")]
CalcBlindError(secp256k1zkp::Error), CalcBlindError(secp256k1zkp::Error),
/// Error calculating ephemeral key /// Error calculating ephemeral pubkey
#[error("Error calculating ephemeral pubkey: {0:?}")] #[error("Error calculating ephemeral pubkey: {0:?}")]
CalcPubKeyError(secp256k1zkp::Error), CalcPubKeyError(secp256k1zkp::Error),
/// Error calculating commitment /// Error calculating commit
#[error("Error calculating commitment: {0:?}")] #[error("Error calculating commitment: {0:?}")]
CalcCommitError(secp256k1zkp::Error), CalcCommitError(secp256k1zkp::Error),
} }
@ -361,8 +362,8 @@ impl From<ser::Error> for OnionError {
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use super::*; use super::*;
use crate::mwmixnet::onion::crypto::secp::random_secret; use crate::mwixnet::onion::crypto::secp::random_secret;
use crate::mwmixnet::onion::{new_hop, Hop}; use crate::mwixnet::onion::{new_hop, Hop};
use grin_core::core::FeeFields; use grin_core::core::FeeFields;
@ -408,12 +409,12 @@ pub mod tests {
hops.push(hop); hops.push(hop);
} }
let mut onion_packet = crate::mwmixnet::onion::create_onion(&commitment, &hops).unwrap(); let mut onion_packet = crate::mwixnet::onion::create_onion(&commitment, &hops).unwrap();
let mut payload = Payload { let mut payload = Payload {
next_ephemeral_pk: onion_packet.ephemeral_pubkey.clone(), next_ephemeral_pk: onion_packet.ephemeral_pubkey.clone(),
excess: random_secret(), excess: random_secret(),
fee: FeeFields::from(fee_per_hop as u32), fee: FeeFields::from(fee_per_hop),
rangeproof: None, rangeproof: None,
}; };
for i in 0..5 { for i in 0..5 {
@ -425,6 +426,6 @@ pub mod tests {
assert!(payload.rangeproof.is_some()); assert!(payload.rangeproof.is_some());
assert_eq!(payload.rangeproof.unwrap(), hops[4].rangeproof.unwrap()); assert_eq!(payload.rangeproof.unwrap(), hops[4].rangeproof.unwrap());
assert_eq!(secp::commit(out_value, &final_blind).unwrap(), final_commit); assert_eq!(secp::commit(out_value, &final_blind).unwrap(), final_commit);
assert_eq!(payload.fee, FeeFields::from(fee_per_hop as u32)); assert_eq!(payload.fee, FeeFields::from(fee_per_hop));
} }
} }

View file

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! Util fns for mwmixnet //! Util fns for mwixnet
//! TODO: possibly redundant, check or move elsewhere //! TODO: possibly redundant, check or move elsewhere
use grin_core::ser::{self, Readable, Reader, Writeable, Writer}; use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
@ -37,7 +37,7 @@ use std::convert::TryInto;
/// # Example /// # Example
/// ///
/// ``` /// ```
/// use grin_wallet_libwallet::mwmixnet::onion::util::write_optional; /// use grin_wallet_libwallet::mwixnet::onion::util::write_optional;
/// let mut writer:Vec<u8> = vec![]; /// let mut writer:Vec<u8> = vec![];
/// let optional_value: Option<u32> = Some(10); /// let optional_value: Option<u32> = Some(10);
/// //write_optional(&mut writer, &optional_value); /// //write_optional(&mut writer, &optional_value);
@ -75,7 +75,7 @@ pub fn write_optional<O: Writeable, W: Writer>(
/// # Example /// # Example
/// ///
/// ``` /// ```
/// use grin_wallet_libwallet::mwmixnet::onion::util::read_optional; /// use grin_wallet_libwallet::mwixnet::onion::util::read_optional;
/// use grin_core::ser::{BinReader, ProtocolVersion, DeserializationMode}; /// use grin_core::ser::{BinReader, ProtocolVersion, DeserializationMode};
/// let mut buf: &[u8] = &[1, 0, 0, 0, 10]; /// let mut buf: &[u8] = &[1, 0, 0, 0, 10];
/// let mut reader = BinReader::new(&mut buf, ProtocolVersion::local(), DeserializationMode::default()); /// let mut reader = BinReader::new(&mut buf, ProtocolVersion::local(), DeserializationMode::default());
@ -106,7 +106,7 @@ pub fn read_optional<O: Readable, R: Reader>(reader: &mut R) -> Result<Option<O>
/// # Example /// # Example
/// ///
/// ``` /// ```
/// use grin_wallet_libwallet::mwmixnet::onion::util::vec_to_array; /// use grin_wallet_libwallet::mwixnet::onion::util::vec_to_array;
/// let v = vec![0, 1, 2, 3, 4, 5]; /// let v = vec![0, 1, 2, 3, 4, 5];
/// let a = vec_to_array::<4>(&v).unwrap(); /// let a = vec_to_array::<4>(&v).unwrap();
/// assert_eq!(a, [0, 1, 2, 3]); /// assert_eq!(a, [0, 1, 2, 3]);

View file

@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and // See the License for the specific language governing permissions and
// limitations under the License. // limitations under the License.
//! Types related to mwmixnet requests required by rest of lib crate apis //! Types related to mwixnet requests required by rest of lib crate apis
//! Should rexport all needed types here //! Should rexport all needed types here
pub use super::onion::crypto::comsig::{self, ComSignature}; pub use super::onion::crypto::comsig::{self, ComSignature};
@ -32,7 +32,7 @@ pub struct SwapReq {
pub onion: Onion, pub onion: Onion,
} }
/// MWMixnetRequest Creation Params /// mwixnetRequest Creation Params
pub struct MixnetReqCreationParams { pub struct MixnetReqCreationParams {
/// List of all the server keys /// List of all the server keys

View file

@ -791,7 +791,7 @@ pub enum TxLogEntryType {
TxReceivedCancelled, TxReceivedCancelled,
/// Sent transaction that was rolled back by user /// Sent transaction that was rolled back by user
TxSentCancelled, TxSentCancelled,
/// Self spend, as per contracts and mwmixnet /// Self spend, as per contracts and mwixnet
TxSelfSpend, TxSelfSpend,
/// Self Spend Cancelled (has to happen before sent to chain, flag rather than delete) /// Self Spend Cancelled (has to happen before sent to chain, flag rather than delete)
TxSelfSpendCancelled, TxSelfSpendCancelled,