Skip to content

Commit

Permalink
[CONTRACTS] update/rename mwixnet onion classes (#719)
Browse files Browse the repository at this point in the history
* update/rename mwixnet onion classes

* fix serialize trait errors
  • Loading branch information
yeastplume authored Aug 27, 2024
1 parent 0b24640 commit 96b5d24
Show file tree
Hide file tree
Showing 16 changed files with 52 additions and 56 deletions.
6 changes: 3 additions & 3 deletions api/src/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ use crate::libwallet::api_impl::{owner, owner_updater};
use crate::libwallet::contract::types::{
ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI,
};
use crate::libwallet::mwmixnet::types::{MixnetReqCreationParams, SwapReq};
use crate::libwallet::mwixnet::types::{MixnetReqCreationParams, SwapReq};
use crate::libwallet::{
AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient,
NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress,
Expand Down Expand Up @@ -831,7 +831,7 @@ where
}

/// Create MXMixnet request
pub fn create_mwmixnet_req(
pub fn create_mwixnet_req(
&self,
keychain_mask: Option<&SecretKey>,
params: &MixnetReqCreationParams,
Expand All @@ -840,7 +840,7 @@ where
) -> Result<SwapReq, Error> {
let mut w_lock = self.wallet_inst.lock();
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
Expand Down
16 changes: 8 additions & 8 deletions controller/tests/contract_srs_mwmixnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@ use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self};
use libwallet::contract::my_fee_contribution;
use libwallet::contract::types::{ContractNewArgsAPI, ContractSetupArgsAPI};
use libwallet::mwmixnet::onion::crypto::secp;
use libwallet::mwmixnet::types::MixnetReqCreationParams;
use libwallet::mwixnet::onion::crypto::secp;
use libwallet::mwixnet::types::MixnetReqCreationParams;
use libwallet::{Slate, SlateState, TxLogEntryType};
use std::sync::atomic::Ordering;
use std::thread;
Expand All @@ -33,8 +33,8 @@ use std::time::Duration;
mod common;
use common::{clean_output_dir, create_wallets, setup};

/// contract SRS flow - just creating an mwmixnet tx at the moment
fn contract_srs_mwmixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
/// contract SRS flow - just creating an mwixnet tx at the moment
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)
let (wallets, chain, stopper, mut bh) =
create_wallets(vec![vec![("default", 4)], vec![("default", 4)]], test_dir).unwrap();
Expand Down Expand Up @@ -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],
fee_per_hop: 50_000_000,
};
//api.create_mwmixnet_req(send_mask, &params, &slate)?;
//api.create_mwixnet_req(send_mask, &params, &slate)?;
Ok(())
})?;

Expand Down Expand Up @@ -147,10 +147,10 @@ fn contract_srs_mwmixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet
}

#[test]
fn wallet_contract_srs_mwmixnet_tx() -> Result<(), libwallet::Error> {
let test_dir = "test_output/contract_srs_mwmixnet_tx";
fn wallet_contract_srs_mwixnet_tx() -> Result<(), libwallet::Error> {
let test_dir = "test_output/contract_srs_mwixnet_tx";
setup(test_dir);
contract_srs_mwmixnet_tx_impl(test_dir)?;
contract_srs_mwixnet_tx_impl(test_dir)?;
clean_output_dir(test_dir);
Ok(())
}
2 changes: 1 addition & 1 deletion libwallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]}

#mwmixnet onion
#mwixnet onion
chacha20 = "0.8.1"
hmac = { version = "0.12.0", features = ["std"]}

Expand Down
6 changes: 3 additions & 3 deletions libwallet/src/api_impl/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ use crate::util::{OnionV3Address, OnionV3AddressError};
use crate::api_impl::owner_updater::StatusMessage;
use crate::contract::types::{ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI};
use crate::grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType};
use crate::mwmixnet::onion::create_onion;
use crate::mwmixnet::types::{
use crate::mwixnet::onion::create_onion;
use crate::mwixnet::types::{
add_excess, new_hop, random_secret, ComSignature, Hop, MixnetReqCreationParams, SwapReq,
};

Expand Down Expand Up @@ -1604,7 +1604,7 @@ where
}

/// 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,
keychain_mask: Option<&SecretKey>,
params: &MixnetReqCreationParams,
Expand Down
6 changes: 3 additions & 3 deletions libwallet/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ pub enum Error {

/// Comsig error
#[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}")]
Onion(#[from] crate::mwmixnet::onion::onion::OnionError),
Onion(#[from] crate::mwixnet::onion::onion::OnionError),

/// Callback implementation error conversion
#[error("Trait Implementation error")]
Expand Down
2 changes: 1 addition & 1 deletion libwallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ mod slate;
pub mod slate_versions;
pub mod slatepack;

pub mod mwmixnet;
pub mod mwixnet;
mod types;

pub use crate::error::Error;
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,8 @@ pub struct ComSignature {
/// Error types for Commitment Signatures
#[derive(Error, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum ComSigError {
/// Invalid com sig
#[error("Commitment signature is invalid")]
InvalidSig,
/// SECP Error Wrapper
#[error("Secp256k1zkp error: {0:?}")]
Secp256k1zkp(secp256k1zkp::Error),
}
Expand All @@ -48,7 +46,6 @@ impl From<secp256k1zkp::Error> for ComSigError {
}

impl ComSignature {
/// Create new Com signature from commit and keys
pub fn new(pub_nonce: &Commitment, s: &SecretKey, t: &SecretKey) -> ComSignature {
ComSignature {
pub_nonce: pub_nonce.to_owned(),
Expand All @@ -58,7 +55,6 @@ impl ComSignature {
}

#[allow(dead_code)]
/// Sign com signature with kernel values
pub fn sign(
amount: u64,
blind: &SecretKey,
Expand Down Expand Up @@ -92,7 +88,6 @@ impl ComSignature {
}

#[allow(non_snake_case)]
/// Verify a com sig
pub fn verify(&self, commit: &Commitment, msg: &Vec<u8>) -> Result<(), ComSigError> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//! Dalek key wrapper for mwmixnet primitives
//! Dalek key wrapper for mwixnet primitives
use super::secp::SecretKey;

Expand Down Expand Up @@ -183,7 +183,7 @@ pub fn sign(sk: &SecretKey, message: &[u8]) -> Result<DalekSignature, DalekError
#[cfg(test)]
mod tests {
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_util::ToHex;
use rand::Rng;
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//! Onion defn for mwmixnet
//! Onion defn for mwixnet
use super::crypto::secp::{self, Commitment, RangeProof, SecretKey};
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::{ChaCha20, Key, Nonce};
use grin_core::core::FeeFields;
Expand All @@ -27,15 +32,11 @@ use hmac::{Hmac, Mac};
use serde::ser::SerializeStruct;
use serde::Deserialize;
use sha2::Sha256;
use std::convert::TryFrom;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::result::Result;
use thiserror::Error;
use x25519_dalek::{PublicKey as xPublicKey, SharedSecret, StaticSecret};

type HmacSha256 = Hmac<Sha256>;
/// Wrap u8 vec
/// Raw bytes alias
pub type RawBytes = Vec<u8>;

const CURRENT_ONION_VERSION: u8 = 0;
Expand Down Expand Up @@ -75,24 +76,24 @@ impl Hash for Onion {
/// A single, decrypted/peeled layer of an Onion.
#[derive(Debug, Clone)]
pub struct Payload {
/// next ephemeral pk
/// PK of next server
pub next_ephemeral_pk: xPublicKey,
/// excess
/// Excess calculation
pub excess: SecretKey,
/// fee
/// Fee
pub fee: FeeFields,
/// proof
/// Rangeproof
pub rangeproof: Option<RangeProof>,
}

impl Payload {
/// Deser a payload
/// Deserialize
pub fn deserialize(bytes: &Vec<u8>) -> Result<Payload, ser::Error> {
let payload: Payload = ser::deserialize_default(&mut &bytes[..])?;
Ok(payload)
}

/// Serialize a payload
/// Serialize
pub fn serialize(&self) -> Result<Vec<u8>, ser::Error> {
let mut vec = vec![];
ser::serialize_default(&mut vec, &self)?;
Expand Down Expand Up @@ -142,7 +143,7 @@ pub struct PeeledOnion {
}

impl Onion {
/// Serialize onion
/// Serialize to binary
pub fn serialize(&self) -> Result<Vec<u8>, ser::Error> {
let mut vec = vec![];
ser::serialize_default(&mut vec, &self)?;
Expand Down Expand Up @@ -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> {
let mut mu_hmac = HmacSha256::new_from_slice(b"MWIXNET")?;
mu_hmac.update(shared_secret.as_bytes());
Expand Down Expand Up @@ -329,19 +330,19 @@ pub enum OnionError {
/// Invalid Key Length
#[error("Invalid key length for MAC initialization")]
InvalidKeyLength,
/// Serialization error
/// Serialization Error
#[error("Serialization error occurred: {0:?}")]
SerializationError(ser::Error),
/// Deserialization error
/// Deserialization Error
#[error("Deserialization error occurred: {0:?}")]
DeserializationError(ser::Error),
/// Error calculating blinding factor
#[error("Error calculating blinding factor: {0:?}")]
CalcBlindError(secp256k1zkp::Error),
/// Error calculating ephemeral key
/// Error calculating ephemeral pubkey
#[error("Error calculating ephemeral pubkey: {0:?}")]
CalcPubKeyError(secp256k1zkp::Error),
/// Error calculating commitment
/// Error calculating commit
#[error("Error calculating commitment: {0:?}")]
CalcCommitError(secp256k1zkp::Error),
}
Expand All @@ -361,8 +362,8 @@ impl From<ser::Error> for OnionError {
#[cfg(test)]
pub mod tests {
use super::*;
use crate::mwmixnet::onion::crypto::secp::random_secret;
use crate::mwmixnet::onion::{new_hop, Hop};
use crate::mwixnet::onion::crypto::secp::random_secret;
use crate::mwixnet::onion::{new_hop, Hop};

use grin_core::core::FeeFields;

Expand Down Expand Up @@ -408,12 +409,12 @@ pub mod tests {
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 {
next_ephemeral_pk: onion_packet.ephemeral_pubkey.clone(),
excess: random_secret(),
fee: FeeFields::from(fee_per_hop as u32),
fee: FeeFields::from(fee_per_hop),
rangeproof: None,
};
for i in 0..5 {
Expand All @@ -425,6 +426,6 @@ pub mod tests {
assert!(payload.rangeproof.is_some());
assert_eq!(payload.rangeproof.unwrap(), hops[4].rangeproof.unwrap());
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));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.

//! Util fns for mwmixnet
//! Util fns for mwixnet
//! TODO: possibly redundant, check or move elsewhere
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
Expand All @@ -37,7 +37,7 @@ use std::convert::TryInto;
/// # 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 optional_value: Option<u32> = Some(10);
/// //write_optional(&mut writer, &optional_value);
Expand Down Expand Up @@ -75,7 +75,7 @@ pub fn write_optional<O: Writeable, W: Writer>(
/// # 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};
/// let mut buf: &[u8] = &[1, 0, 0, 0, 10];
/// let mut reader = BinReader::new(&mut buf, ProtocolVersion::local(), DeserializationMode::default());
Expand Down Expand Up @@ -106,7 +106,7 @@ pub fn read_optional<O: Readable, R: Reader>(reader: &mut R) -> Result<Option<O>
/// # 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 a = vec_to_array::<4>(&v).unwrap();
/// assert_eq!(a, [0, 1, 2, 3]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// 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
pub use super::onion::crypto::comsig::{self, ComSignature};
Expand All @@ -32,7 +32,7 @@ pub struct SwapReq {
pub onion: Onion,
}

/// MWMixnetRequest Creation Params
/// mwixnetRequest Creation Params
pub struct MixnetReqCreationParams {
/// List of all the server keys
Expand Down
2 changes: 1 addition & 1 deletion libwallet/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -791,7 +791,7 @@ pub enum TxLogEntryType {
TxReceivedCancelled,
/// Sent transaction that was rolled back by user
TxSentCancelled,
/// Self spend, as per contracts and mwmixnet
/// Self spend, as per contracts and mwixnet
TxSelfSpend,
/// Self Spend Cancelled (has to happen before sent to chain, flag rather than delete)
TxSelfSpendCancelled,
Expand Down

0 comments on commit 96b5d24

Please sign in to comment.