diff --git a/Cargo.lock b/Cargo.lock index d6452a1..2354a45 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2233,7 +2233,7 @@ checksum = "9985c9503b412198aa4197559e9a318524ebc4519c229bfa05a535828c950b9d" [[package]] name = "grin_api" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bytes 1.12.0", "easy-jsonrpc-mw", @@ -2265,7 +2265,7 @@ dependencies = [ [[package]] name = "grin_chain" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bit-vec", "bitflags 1.3.2", @@ -2289,7 +2289,7 @@ dependencies = [ [[package]] name = "grin_core" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "byteorder", @@ -2315,7 +2315,7 @@ dependencies = [ [[package]] name = "grin_keychain" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "byteorder", @@ -2336,7 +2336,7 @@ dependencies = [ [[package]] name = "grin_p2p" -version = "5.5.1" +version = "5.5.2" dependencies = [ "bitflags 1.3.2", "built", @@ -2359,7 +2359,7 @@ dependencies = [ [[package]] name = "grin_pool" -version = "5.5.1" +version = "5.5.2" dependencies = [ "blake2-rfc", "chrono", @@ -2376,9 +2376,9 @@ dependencies = [ [[package]] name = "grin_secp256k1zkp" -version = "0.7.15" +version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf7bb95f155b1eede2648a1b9afbba82bc3d9f2af0518b478767559a572bd973" +checksum = "57e0a5f761e8c56db5be865f79832677d3badb3be91d7172d468e448f3d69f82" dependencies = [ "arrayvec 0.7.8", "cc", @@ -2391,7 +2391,7 @@ dependencies = [ [[package]] name = "grin_store" -version = "5.5.1" +version = "5.5.2" dependencies = [ "byteorder", "chrono", @@ -2413,7 +2413,7 @@ dependencies = [ [[package]] name = "grin_util" -version = "5.5.1" +version = "5.5.2" dependencies = [ "anyhow", "backtrace", diff --git a/api/src/owner.rs b/api/src/owner.rs index 368b999..d124b64 100644 --- a/api/src/owner.rs +++ b/api/src/owner.rs @@ -14,6 +14,7 @@ //! Owner API External Definition +use crate::config::config::{reload_global_config, update_global_config, WALLET_CONFIG_FILE_NAME}; use crate::config::{TorConfig, WalletConfig}; use crate::core::core::OutputFeatures; use crate::core::global; @@ -23,7 +24,11 @@ use crate::keychain::{Identifier, Keychain}; use crate::libwallet::api_impl::owner_updater::{start_updater_log_thread, StatusMessage}; use crate::libwallet::api_impl::types::update_tx_slate_state; use crate::libwallet::api_impl::{owner, owner_updater}; +use crate::libwallet::mwixnet::{parse_mwixnet_response, MwixnetResponse, SwapReq}; +use crate::libwallet::mwixnet::{MixnetReqCreationParams, MwixnetReqCreationResult}; +use crate::libwallet::slatepack::SlatepackAddressIndex; use crate::libwallet::wallet_lock; +use crate::libwallet::RetrieveTxQueryArgs; use crate::libwallet::{ AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress, @@ -32,13 +37,9 @@ use crate::libwallet::{ use crate::util::logger::LoggingConfig; use crate::util::secp::{key::SecretKey, pedersen::Commitment}; use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString}; -use grin_wallet_config::config::{ - reload_global_config, update_global_config, WALLET_CONFIG_FILE_NAME, -}; -use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, SwapReq}; -use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; -use grin_wallet_libwallet::RetrieveTxQueryArgs; use grin_wallet_util::OnionV3Address; +use impls::json_rpc; +use impls::tor::arti::tor_post; use chrono::prelude::*; use ed25519_dalek::SigningKey as DalekSecretKey; @@ -1318,6 +1319,7 @@ where &tx, tx_id, tx_slate_id, + true, ) } @@ -2606,21 +2608,22 @@ where // MWIXNET - /// Creates a mwixnet request [SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html) + /// Creates a mwixnet request [SwapReq](grin_wallet_libwallet::mwixnet::SwapReq) /// from a given output commitment under this wallet's control. /// /// # Arguments /// * `keychain_mask` - Wallet secret mask to XOR against the stored wallet seed before using, if /// being used. - /// * `params` - A [MixnetReqCreationParams](../grin_wallet_libwallet/api_impl/types/struct.MixnetReqCreationParams.html) + /// * `params` - A [MixnetReqCreationParams] /// struct containing the parameters for the request, which include: - /// `server_keys` - The public keys of the servers participating in the mixnet (each encoded internally as a `SecretKey`) - /// `fee_per_hop` - The fee to be paid to each server for each hop in the mixnet + /// `server_keys` - Published X25519 onion keys in route order, not Ed25519 identity keys + /// or private keys + /// `fee_per_hop` - Optional fee per hop with the swap minimum as default /// * `commitment` - The commitment of the output to be mixed /// * `lock_output` - Whether to lock the referenced output after creating the request /// /// # Returns - /// * Ok([SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html)) if successful + /// * Ok([MwixnetReqCreationResult](../grin_wallet_libwallet/mwixnet/struct.MwixnetReqCreationResult.html)) if successful /// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered /// /// # Example @@ -2631,8 +2634,10 @@ where /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); /// let keychain_mask = None; /// let params = MixnetReqCreationParams { - /// server_keys: vec![], // Public keys here in secret key representation - /// fee_per_hop: 100, + /// server_keys: vec![libwallet::mwixnet::MwixnetServerPublicKey::from_hex( + /// "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + /// ).unwrap()], + /// fee_per_hop: None, /// }; /// /// let commitment = Commitment::from_vec(vec![0; 32]); @@ -2645,7 +2650,7 @@ where /// lock_output, /// ); /// - /// if let Ok(req) = result { + /// if let Ok(result) = result { /// //... /// } /// ``` @@ -2655,9 +2660,8 @@ where params: &MixnetReqCreationParams, commitment: &Commitment, lock_output: bool, // use_test_rng: bool, - ) -> Result { - let mut w_lock = self.wallet_inst.lock(); - let w = w_lock.lc_provider()?.wallet_inst()?; + ) -> Result { + wallet_lock!(self.wallet_inst, w); owner::create_mwixnet_req( w, keychain_mask, @@ -2667,6 +2671,81 @@ where self.doctest_mode, ) } + + /// Sends a mwixnet request [SwapReq](grin_wallet_libwallet::mwixnet::SwapReq) + /// to provided onion server. + /// + /// # Arguments + /// * `req` - A [SwapReq] + /// struct containing the parameters for the request, which include: + /// `comsig` - [ComSignature](grin_wallet_libwallet::mwixnet::ComSignature) signature with a pedersen commitment value & blinding factors as the keys + /// `onion` - [Onion](grin_wallet_libwallet::mwixnet::Onion) encrypted route payload + /// * `server` - Onion server address + /// + /// # Returns + /// * `Ok(None)` if the server accepted the request + /// * `Ok(Some(message))` if the server rejected the request + /// * `Err` for configuration, transport, or invalid-response failures + /// + /// Leaves output locks unchanged + /// + /// # Example + /// Set up as in [`new`](struct.Owner.html#method.new) method above. + /// ``` + /// # grin_wallet_api::doctest_helper_setup_doc_env!(wallet, wallet_config); + /// + /// let api_owner = Owner::new(wallet.clone(), None, std::path::PathBuf::from("grin-wallet.toml")); + /// let keychain_mask = None; + /// let params = MixnetReqCreationParams { + /// server_keys: vec![libwallet::mwixnet::MwixnetServerPublicKey::from_hex( + /// "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + /// ).unwrap()], + /// fee_per_hop: None, + /// }; + /// + /// let commitment = Commitment::from_vec(vec![0; 32]); + /// let lock_output = true; + /// + /// let result = api_owner.create_mwixnet_req( + /// keychain_mask, + /// ¶ms, + /// &commitment, + /// lock_output, + /// ); + /// + /// if let Ok(result) = result { + /// let server = "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion".try_into().unwrap(); + /// let result = api_owner.send_mwixnet_req(&result.request, server); + /// if let Ok(result) = result { + /// //.. + /// } + /// } + /// ``` + pub fn send_mwixnet_req( + &self, + req: &SwapReq, + server: OnionV3Address, + ) -> Result, Error> { + let url = format!("{}/v1", server.to_http_str()); + let rpc_params = serde_json::json!([req]); + let rpc_request = json_rpc::build_request("swap", &rpc_params); + let tor_config = crate::tor_config::load(&self.config_path())?; + let response = match tor_post(&tor_config, &rpc_request, &url) { + Ok(response) => response, + Err(e) => { + return Err(Error::GenericError(format!( + "Could not determine whether mwixnet accepted the request: {}", + e, + ))); + } + }; + match parse_mwixnet_response(&response).map_err(|e| { + Error::GenericError(format!("Could not confirm the mwixnet response: {}", e)) + })? { + MwixnetResponse::Accepted => Ok(None), + MwixnetResponse::Rejected(message) => Ok(Some(message)), + } + } } /// attempt to send slate synchronously with TOR diff --git a/api/src/owner_rpc.rs b/api/src/owner_rpc.rs index 6532e24..7c5eba4 100644 --- a/api/src/owner_rpc.rs +++ b/api/src/owner_rpc.rs @@ -14,7 +14,7 @@ //! JSON-RPC Stub generation for the Owner API use grin_wallet_libwallet::RetrieveTxQueryArgs; -use libwallet::mwixnet::SwapReq; +use libwallet::mwixnet::MwixnetReqCreationResult; use uuid::Uuid; use crate::config::{TorConfig, WalletConfig}; @@ -22,10 +22,11 @@ use crate::core::core::OutputFeatures; use crate::core::global; use crate::keychain::{Identifier, Keychain}; use crate::libwallet::{ - mwixnet::MixnetReqCreationParams, AcctPathMapping, Amount, BuiltOutput, Error, InitTxArgs, - IssueInvoiceTxArgs, NodeClient, NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, - SlateVersion, Slatepack, SlatepackAddress, StatusMessage, TxLogEntry, VersionedSlate, - ViewWallet, WalletInfo, WalletLCProvider, + mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey}, + AcctPathMapping, Amount, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient, + NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, SlateVersion, Slatepack, + SlatepackAddress, StatusMessage, TxLogEntry, VersionedSlate, ViewWallet, WalletInfo, + WalletLCProvider, }; use crate::util::logger::LoggingConfig; use crate::util::secp::key::{PublicKey, SecretKey}; @@ -2062,7 +2063,11 @@ pub trait OwnerRpc { ) -> Result; /** - Networked version of [Owner::build_output](struct.Owner.html#method.create_mwixnet_req). + Networked version of [Owner::create_mwixnet_req](struct.Owner.html#method.create_mwixnet_req). + + server_keys accepts public X25519 onion keys as hex, in route order, replacing secret keys + fee_per_hop accepts a nanogrin string or null for the swap minimum + ``` # grin_wallet_api::doctest_helper_json_rpc_owner_assert_response!( # r#" @@ -2072,12 +2077,12 @@ pub trait OwnerRpc { "params": { "token": "d202964900000000d302964900000000d402964900000000d502964900000000", "commitment": "08e1da9e6dc4d6e808a718b2f110a991dd775d65ce5ae408a4e1f002a4961aa9e7", - "fee_per_hop": "5000000", + "fee_per_hop": null, "lock_output": true, "server_keys": [ - "97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332", - "0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e", - "b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5" + "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + "3ab3b7d1fb643393897a0b942934d34be9cb823621cd49c09b12fdfa69598d71", + "80f2ceadcc5a767961772f4ae04826c70b0ae497f4f50d782241ff056b71df45" ] }, "id": 1 @@ -2099,12 +2104,13 @@ pub trait OwnerRpc { "62ea6b8369686a0415e1e752b9b4d6e66cf5b6066a2d3c60d8818890a55f3adff4601466f4c6e6b646568b99ae93549a3595b7a7b4be815ced87d9297cabbd69518d7b2ed6edd14007528fd346aaea765a1165fe886666627ebcab9588b8ee1c9e98395ae67913c48eb6e924581b40182fce807f97312fb07fd5e216d99941f2b488babce4078a50cd66b28b30a66c4f54fcc127437408a99b30ffd6c3d0d8c7d39e864fc04e321b8c10138c8852d4cad0a4f2780412b9dadcc6e0f2657b7803a81bccb809ca392464be2e01755be7377d0e815698ad6ea51d4617cc92c3ccf852f038e33cc9c90992438ba5c49cca7cc188b682da684e2f4c9733a84a7b64ac5c2216ebf5926f0ee67b664fb5bab799109cbee755ce1aebc8cd352fea51cd84c333cb958093c53544c3f3ab05dba64d8f041c3b179796b476ec04b11044e39db6994ab767315e52cc0ef023432ec88ade2911612db7e74e0923889f765b58b00e3869c5072a4e882c1b721913f63bda986b8c97b7ae575f0d4be596a1ac3cd0db96ce6074ee000b32018b3bda16d7dba34a13ba9c3ce983946414c16e278351a3411cb8ef2cb8ef5b6e1667c4c58bc797c0324ae4fec8960d684e561c0e833ee4c3331c6c439b59042a62993535e23cc8a8a4cf705c0f9b1d62db4e3d76c22c01138800414b143ddff471e4df4413e842a1b41f43cc9647e47145fd6c86d4d1a34fb2f62f5a55b31c9353ee34743c548eff955f2d2143c1a86cbcb452104f96d0142db31153021bbeed995c71a92de8fb1f97269533a508085c543fcb3ee57000bb265e74187b858403aa97b6c7b085e5d5b6025cbfe5f6926d33c835f90e60fc62013e80bbe0a855da5938b4b8f83ac29c5e8251827795356222079a6d1612e2fdf93bd7836d1613c7a353ada48ce256f880bbbb3108e037e3b5647101bd4d549101b0ee73d2248a932a802a3b1beb0b69d777c4285d57e91d83e96fe2f8a1a2f182fe2c6ca37b18460cf8d7f56c201147b9be19f1d01f8ad305c1e9c4dd79b5d8719d6550432352cf737082b1e9de7a083ffbe1" ], "pubkey": "e7ee7d51b11d09f268ade98bc9d7ae9be3c4ac124ce1c3a40e50d34460fa5f08" - } + }, + "tx_id": 5 } } } # "# - # , 5, true, true, false, false); + # , 5, true, false, false, false); ``` * */ @@ -2112,10 +2118,10 @@ pub trait OwnerRpc { &self, token: Token, commitment: String, - fee_per_hop: String, + fee_per_hop: Option, lock_output: bool, server_keys: Vec, - ) -> Result; + ) -> Result; } impl OwnerRpc for Owner @@ -2530,28 +2536,22 @@ where &self, token: Token, commitment: String, - fee_per_hop: String, + fee_per_hop: Option, lock_output: bool, server_keys: Vec, - ) -> Result { + ) -> Result { let commit = Commitment::from_vec(from_hex(&commitment).map_err(Error::CommitDeser)?); - let secp_inst = static_secp_instance(); - let secp = secp_inst.lock(); - let mut keys = vec![]; for key in server_keys { - keys.push(SecretKey::from_slice( - &secp, - &grin_util::from_hex(&key).map_err(Error::ServerKeyDeser)?, - )?) + keys.push(MwixnetServerPublicKey::from_hex(&key).map_err(Error::ServerKeyDeser)?) } let req_params = MixnetReqCreationParams { server_keys: keys, fee_per_hop: fee_per_hop - .parse::() - .map_err(|_| Error::U64Deser(fee_per_hop))?, + .map(|fee| fee.parse::().map_err(|_| Error::U64Deser(fee))) + .transpose()?, }; Owner::create_mwixnet_req( diff --git a/controller/src/command.rs b/controller/src/command.rs index 3962cdb..ae2720a 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -22,16 +22,20 @@ use crate::error::Error; use crate::keychain; use crate::libwallet::api_impl::owner::{self, decrypt_slatepack, deserialize_slatepack}; use crate::libwallet::api_impl::types::update_tx_slate_state; +use crate::libwallet::mwixnet::MixnetReqCreationParams; use crate::libwallet::slatepack::get_slatepack_file_contents; use crate::libwallet::slatepack::SlatepackAddressIndex; +use crate::libwallet::OutputCommitMapping; use crate::libwallet::{ self, InitTxArgs, IssueInvoiceTxArgs, NodeClient, PaymentProof, Slate, SlateState, Slatepack, SlatepackAddress, WalletLCProvider, }; use crate::libwallet::{wallet_lock, WalletHandle}; use crate::util::secp::key::SecretKey; -use crate::util::{Mutex, ZeroingString}; +use crate::util::secp::pedersen::Commitment; +use crate::util::{Mutex, ToHex, ZeroingString}; use crate::{controller, display}; +use grin_wallet_util::OnionV3Address; use qr_code::QrCode; use serde_json as json; @@ -1598,6 +1602,123 @@ where } } +pub struct MwixnetArgs { + pub server: OnionV3Address, + pub output: MwixnetOutput, + pub minimum_confirmations: u64, + pub params: MixnetReqCreationParams, +} + +pub enum MwixnetOutput { + Commitment(Commitment), + MinimumAmount(u64), + Max, +} + +fn confirm_mwixnet_response( + response: Result, libwallet::Error>, + tx_id: u32, +) -> Result<(), Error> { + let message = match response { + Ok(None) => { + println!("MWixnet request accepted (transaction {})", tx_id); + return Ok(()); + } + Ok(Some(message)) => format!("MWixnet rejected the request: {}", message), + Err(error) => error.to_string(), + }; + // The server may already have accepted the request + Err(Error::GenericError(format!( + "{}. Output remains locked as transaction {}. The server may already have accepted \ + the request. To cancel manually, use `cancel -i {}`.", + message, tx_id, tx_id + ))) +} + +pub fn mwixnet( + owner_api: &mut Owner, + keychain_mask: Option<&SecretKey>, + args: MwixnetArgs, +) -> Result<(), Error> +where + L: WalletLCProvider<'static, C, K> + 'static, + C: NodeClient + 'static, + K: keychain::Keychain + 'static, +{ + let height = owner_api.node_height(keychain_mask)?.height; + let (refreshed, outputs) = owner_api.retrieve_outputs(keychain_mask, false, true, None)?; + if !refreshed { + return Err(Error::GenericError( + "Could not refresh wallet outputs. MWixnet request was not created".to_string(), + )); + } + let eligible = |output: &&OutputCommitMapping| { + output + .output + .eligible_to_spend(height, args.minimum_confirmations.max(1)) + }; + let output = match &args.output { + MwixnetOutput::Commitment(commitment) => outputs + .iter() + .find(|output| output.commit == *commitment && eligible(output)), + MwixnetOutput::MinimumAmount(amount) => outputs + .iter() + .filter(eligible) + .filter(|output| output.output.value >= *amount) + .min_by_key(|output| output.output.value), + MwixnetOutput::Max => outputs + .iter() + .filter(eligible) + .max_by_key(|output| output.output.value), + } + .ok_or_else(|| Error::GenericError("No eligible MWixnet output was found".to_string()))?; + let commitment = output.commit; + println!( + "Selected MWixnet output {} with value {}", + commitment.to_hex(), + core::amount_to_hr_string(output.output.value, false) + ); + + let creation = owner_api.create_mwixnet_req(keychain_mask, &args.params, &commitment, true)?; + match creation.tx_id { + None => Err(Error::GenericError( + "MWixnet request was created without locking its output".to_string(), + )), + Some(tx_id) => { + let res = owner_api.send_mwixnet_req(&creation.request, args.server); + confirm_mwixnet_response(res, tx_id) + } + } +} + +#[cfg(test)] +mod tests { + use super::confirm_mwixnet_response; + + #[test] + fn mwixnet_response_reports_uncertain_transactions_as_locked() { + assert!(confirm_mwixnet_response(Ok(None), 3).is_ok()); + let error = + confirm_mwixnet_response(Ok(Some("invalid response".to_string())), 3).unwrap_err(); + assert!(error + .to_string() + .contains("remains locked as transaction 3")); + assert!(error.to_string().contains("cancel -i 3")); + let error = confirm_mwixnet_response( + Err(super::libwallet::Error::GenericError( + "transport failed".into(), + )), + 4, + ) + .unwrap_err() + .to_string(); + assert!(error.contains("transport failed")); + assert!(error.contains("remains locked as transaction 4")); + assert!(error.contains("cancel -i 4")); + assert!(error.contains("may already have accepted")); + } +} + #[cfg(test)] mod send_tests { use super::*; diff --git a/controller/tests/mwixnet.rs b/controller/tests/mwixnet.rs index 5e81a35..16b348d 100644 --- a/controller/tests/mwixnet.rs +++ b/controller/tests/mwixnet.rs @@ -18,13 +18,17 @@ extern crate grin_wallet_controller as wallet; extern crate grin_wallet_impls as impls; use grin_core as core; +use grin_core::core::FeeFields; use grin_util as util; use grin_util::secp::key::SecretKey; use std::path::PathBuf; use grin_wallet_libwallet as libwallet; use impls::test_framework::{self, LocalWalletClient}; -use libwallet::{mwixnet::MixnetReqCreationParams, InitTxArgs}; +use libwallet::{ + mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey, MAX_MWIXNET_HOPS}, + InitTxArgs, OutputStatus, TxLogEntryType, +}; use std::sync::atomic::Ordering; use std::thread; use std::time::Duration; @@ -141,22 +145,167 @@ fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> { let server_key_3 = SecretKey::from_slice(&secp, &grin_util::from_hex(server_pubkey_str_3).unwrap())?; let params = MixnetReqCreationParams { - server_keys: vec![server_key_1, server_key_2, server_key_3], - fee_per_hop: 50_000_000, + server_keys: vec![ + MwixnetServerPublicKey::from_secret(&server_key_1), + MwixnetServerPublicKey::from_secret(&server_key_2), + MwixnetServerPublicKey::from_secret(&server_key_3), + ], + fee_per_hop: None, }; let outputs = api1.retrieve_outputs(mask1, false, false, None)?; // get last output let last_output = outputs.1[outputs.1.len() - 1].clone(); - let mwixnet_req = api1.create_mwixnet_req(mask1, ¶ms, &last_output.commit, true)?; + // Store the output with an MMR index, like a restored output + let mmr_index = Some(chain.get_output_pos(&last_output.commit).unwrap()); + { + wallet_inst!(wallet1, w); + let mut batch = w.batch(mask1)?; + let mut output = last_output.output.clone(); + batch.delete(&output.key_id, &output.mmr_index)?; + output.mmr_index = mmr_index; + batch.save(output)?; + batch.commit()?; + } - println!("MWIXNET REQ: {:?}", mwixnet_req); + let empty_params = MixnetReqCreationParams { + server_keys: vec![], + fee_per_hop: params.fee_per_hop, + }; + assert!(api1 + .create_mwixnet_req(mask1, &empty_params, &last_output.commit, true) + .is_err()); - // check output we created comsig for is indeed locked + let too_many_params = MixnetReqCreationParams { + server_keys: vec![params.server_keys[0]; MAX_MWIXNET_HOPS + 1], + fee_per_hop: params.fee_per_hop, + }; + assert!(api1 + .create_mwixnet_req(mask1, &too_many_params, &last_output.commit, true) + .is_err()); + + let oversized_fee_params = MixnetReqCreationParams { + server_keys: params.server_keys[..2].to_vec(), + fee_per_hop: Some(1 << 39), + }; + assert_eq!( + api1.create_mwixnet_req(mask1, &oversized_fee_params, &last_output.commit, true) + .unwrap_err(), + libwallet::Error::Fee("mwixnet total fee exceeds FeeFields limit".to_string()) + ); + + for fee in [0, 12_499_999] { + let invalid_params = MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: Some(fee), + }; + assert_eq!( + api1.create_mwixnet_req(mask1, &invalid_params, &last_output.commit, true) + .unwrap_err(), + libwallet::Error::Fee("mwixnet fee is below the swap minimum 0.0125".to_string()) + ); + } + let custom_params = MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: Some(25_000_000), + }; + let custom = api1.create_mwixnet_req(mask1, &custom_params, &last_output.commit, false)?; + let mut onion = custom.request.onion; + for server_key in [&server_key_1, &server_key_2, &server_key_3] { + let peeled = onion.peel_layer(server_key).unwrap(); + assert_eq!(peeled.payload.fee, FeeFields::try_from(25_000_000u64)?); + onion = peeled.onion; + } + + drop(secp); + + // Failed refresh must not create or lock a swap + let tx_count = api1.retrieve_txs(mask1, false, None, None, None)?.1.len(); + let (disconnected, receiver) = std::sync::mpsc::channel(); + drop(receiver); + let original_proxy = std::mem::replace(&mut *client1.proxy_tx.lock(), disconnected); + let mut api1 = api1; + let result = wallet::command::mwixnet( + &mut api1, + mask1, + wallet::command::MwixnetArgs { + server: "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion".try_into()?, + output: wallet::command::MwixnetOutput::Commitment(last_output.commit), + minimum_confirmations: 1, + params: MixnetReqCreationParams { + server_keys: params.server_keys.clone(), + fee_per_hop: None, + }, + }, + ); + *client1.proxy_tx.lock() = original_proxy; + assert!(result + .unwrap_err() + .to_string() + .contains("Could not refresh wallet outputs")); + assert_eq!( + api1.retrieve_txs(mask1, false, None, None, None)?.1.len(), + tx_count + ); + let outputs = api1.retrieve_outputs(mask1, false, false, None)?.1; + assert_eq!( + outputs + .iter() + .find(|o| o.commit == last_output.commit) + .unwrap() + .output + .status, + OutputStatus::Unspent + ); + + let creation = api1.create_mwixnet_req(mask1, ¶ms, &last_output.commit, true)?; + let creation_tx_id = creation.tx_id.unwrap(); + let fee_per_hop = 12_500_000; + let mut onion = creation.request.onion.clone(); + for server_key in [&server_key_1, &server_key_2, &server_key_3] { + let peeled = onion + .peel_layer(server_key) + .map_err(|e| libwallet::Error::GenericError(e.to_string()))?; + assert_eq!(peeled.payload.fee, FeeFields::try_from(fee_per_hop)?); + onion = peeled.onion; + } + + println!("MWIXNET REQ: {:?}", creation.request); + + // Check the input lock and expected output are tracked together. let outputs = api1.retrieve_outputs(mask1, false, false, None)?; - // get last output - let last_output = outputs.1[outputs.1.len() - 1].clone(); - assert_eq!(last_output.output.status, libwallet::OutputStatus::Locked); + let input = outputs + .1 + .iter() + .find(|o| o.commit == last_output.commit) + .unwrap(); + assert_eq!(input.output.status, OutputStatus::Locked); + assert_eq!(input.output.mmr_index, mmr_index); + let total_fee = fee_per_hop * params.server_keys.len() as u64; + let expected_amount = last_output.output.value - total_fee; + let expected_output = outputs + .1 + .iter() + .find(|o| o.output.status == OutputStatus::Unconfirmed && o.output.value == expected_amount) + .unwrap(); + assert_eq!( + input.output.tx_log_entry, + expected_output.output.tx_log_entry + ); + + let txs = api1.retrieve_txs(mask1, false, None, None, None)?.1; + let tx = txs.last().unwrap(); + assert_eq!(creation_tx_id, tx.id); + assert_eq!(tx.tx_type, TxLogEntryType::TxSent); + assert_eq!(tx.amount_debited, last_output.output.value); + assert_eq!(tx.amount_credited, expected_amount); + assert_eq!(tx.num_inputs, 1); + assert_eq!(tx.num_outputs, 1); + assert_eq!(tx.fee, Some(FeeFields::try_from(total_fee)?)); + + assert!(api1 + .create_mwixnet_req(mask1, ¶ms, &last_output.commit, false) + .is_err()); // let logging finish stopper.store(false, Ordering::Relaxed); diff --git a/grin b/grin index 4182d34..da95576 160000 --- a/grin +++ b/grin @@ -1 +1 @@ -Subproject commit 4182d3422175184d723232d23f85ac4ec6990285 +Subproject commit da955767a35a59cf1d8790a4a4dd70a49372710b diff --git a/impls/src/adapters/tor.rs b/impls/src/adapters/tor.rs index b5233fc..1684e12 100644 --- a/impls/src/adapters/tor.rs +++ b/impls/src/adapters/tor.rs @@ -187,7 +187,7 @@ impl TorSlateSender { client.send_request(req)? } else { tor_post(&self.config, &input, url) - .map_err(|e| ClientError::RequestError(format!("{:?}", e)))? + .map_err(|e| ClientError::RequestError(e.to_string()))? }; Ok(res) } diff --git a/impls/src/lib.rs b/impls/src/lib.rs index 4ff0c1b..f5c9b5b 100644 --- a/impls/src/lib.rs +++ b/impls/src/lib.rs @@ -44,6 +44,7 @@ pub mod tor; pub use crate::adapters::{ PathToSlate, SlateGetter, SlatePutter, SlateReceiver, SlateSender, TorSlateSender, }; +pub use crate::client_utils::json_rpc; pub use crate::error::Error; pub use crate::lifecycle::DefaultLCProvider; pub use crate::node_clients::HTTPNodeClient; diff --git a/impls/src/tor/arti.rs b/impls/src/tor/arti.rs index 3abeedd..d0a0c89 100644 --- a/impls/src/tor/arti.rs +++ b/impls/src/tor/arti.rs @@ -34,6 +34,7 @@ use sha2::Sha512; use std::collections::HashMap; use std::net::SocketAddr; use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, LazyLock, Mutex}; use std::thread::{self, JoinHandle}; use std::time::Duration; @@ -59,6 +60,18 @@ struct TorService { state_lock: PathBuf, } +/// Failure from an HTTP request over Tor, classified by whether delivery may +/// have started. +#[derive(Debug, thiserror::Error)] +pub enum TorPostError { + /// The failure happened before handing the request to Hyper. + #[error("{0}")] + NotSent(Error), + /// Hyper started sending the request, so delivery cannot be ruled out. + #[error("{0}")] + PossiblySent(Error), +} + type ArtiClientConfig = (Arc>, TorClientConfig); lazy_static! { @@ -218,39 +231,73 @@ pub fn start_tor_client(config: TorConfig) -> Result<(), Error> { Ok(()) } +/// Build an origin-form JSON POST request +fn build_post_request(json: String, url: &Uri) -> Result>, Error> { + let authority = url + .authority() + .ok_or_else(|| Error::GenericError(format!("URL {} has bad authority", url)))?; + let request_target = url + .path_and_query() + .map(|path| path.as_str()) + .unwrap_or("/"); + + Request::builder() + .uri(request_target) + .method("POST") + .header("host", authority.as_str()) + .header("accept", "application/json") + .header("content-type", "application/json") + .body(Full::from(json)) + .map_err(|e| Error::TorProcess(format!("{:?}", e))) +} + /// Make POST request. -pub fn tor_post(tor_config: &TorConfig, input: &IN, url: &str) -> Result +pub fn tor_post(tor_config: &TorConfig, input: &IN, url: &str) -> Result where IN: Serialize, { - let json = serde_json::to_string(input) - .map_err(|_| Error::GenericError("Could not serialize data to JSON".to_owned()))?; + let json = serde_json::to_string(input).map_err(|_| { + TorPostError::NotSent(Error::GenericError( + "Could not serialize data to JSON".to_owned(), + )) + })?; let url = url.to_string(); let url: Uri = url .parse() - .map_err(|_| Error::GenericError(format!("Bad URL: {}", url)))?; + .map_err(|_| TorPostError::NotSent(Error::GenericError(format!("Bad URL: {}", url))))?; let host = match url.host() { - None => return Err(Error::GenericError(format!("URL {} has bad host", url))), + None => { + return Err(TorPostError::NotSent(Error::GenericError(format!( + "URL {} has bad host", + url + )))) + } Some(h) => h, } .to_string(); + let port = url.port_u16().unwrap_or(80); + let request = build_post_request(json, &url).map_err(TorPostError::NotSent)?; let timeout = tor_config.request_timeout(); let (state_path, cache_path) = state_cache_paths(tor_config); - let (client, _) = init_client(&state_path, &cache_path, tor_config)?; - let res: Result = thread::spawn(move || { + let (client, _) = + init_client(&state_path, &cache_path, tor_config).map_err(TorPostError::NotSent)?; + let res: Result = thread::spawn(move || { let c = client.clone(); client.runtime().block_on(async move { - let res = c - .runtime() - .timeout(timeout, async { - let stream = c - .connect((host, url.port_u16().unwrap_or(80))) - .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let send_started = Arc::new(AtomicBool::new(false)); + let send_started_in_request = send_started.clone(); + let runtime = c.runtime().clone(); + let res = runtime + .timeout(timeout, async move { + let stream = c.connect((host, port)).await.map_err(|e| { + TorPostError::NotSent(Error::TorProcess(format!("{:?}", e))) + })?; let (mut request_sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + .map_err(|e| { + TorPostError::NotSent(Error::TorProcess(format!("{:?}", e))) + })?; // Spawn a task to poll the connection and drive the HTTP state. tokio::spawn(async move { @@ -259,36 +306,44 @@ where } }); - let resp = request_sender - .send_request( - Request::builder() - .uri(url) - .method("POST") - .body::>(Full::from(json)) - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?, - ) - .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + send_started_in_request.store(true, Ordering::Release); + let resp = request_sender.send_request(request).await.map_err(|e| { + TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e))) + })?; - let body_resp = resp - .into_body() - .collect() - .await - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let status = resp.status(); + let body_resp = resp.into_body().collect().await.map_err(|e| { + TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e))) + })?; let body = body_resp.to_bytes().into(); - let body_text = String::from_utf8(body) - .map_err(|e| Error::TorProcess(format!("{:?}", e)))?; + let body_text = String::from_utf8(body).map_err(|e| { + TorPostError::PossiblySent(Error::TorProcess(format!("{:?}", e))) + })?; + if !status.is_success() { + return Err(TorPostError::PossiblySent(Error::TorProcess(format!( + "HTTP request failed with status {}: {}", + status, body_text + )))); + } Ok(body_text) }) .await; match res { - Err(e) => Err(Error::TorProcess(format!("{:?}", e))), + Err(e) if send_started.load(Ordering::Acquire) => Err(TorPostError::PossiblySent( + Error::TorProcess(format!("{:?}", e)), + )), + Err(e) => Err(TorPostError::NotSent(Error::TorProcess(format!("{:?}", e)))), Ok(body) => Ok(body), } }) }) .join() - .unwrap_or_else(|e| Err(Error::TorProcess(format!("{:?}", e))))?; + .unwrap_or_else(|e| { + Err(TorPostError::PossiblySent(Error::TorProcess(format!( + "{:?}", + e + )))) + })?; res } @@ -300,6 +355,10 @@ fn init_client( ) -> Result<(Arc>, TorClientConfig), Error> { let mut builder = TorClientConfigBuilder::from_directories(state_path, cache_path); builder.address_filter().allow_onion_addrs(true); + // Circuit timeout minimum applies to listeners and sends too + builder + .override_net_params() + .insert("cbtmintimeout".into(), 60_000); // Configure bridge. if let Some(bridge_line) = tor_config.bridge.bridge_line.as_ref() { @@ -478,3 +537,21 @@ fn add_service_key( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::build_post_request; + use hyper::{Method, Uri}; + + #[test] + fn builds_origin_form_json_request() { + let url: Uri = "http://example.onion:8080/v1?test=1".parse().unwrap(); + let request = build_post_request("{}".to_string(), &url).unwrap(); + + assert_eq!(request.method(), Method::POST); + assert_eq!(request.uri(), "/v1?test=1"); + assert_eq!(request.headers()["host"], "example.onion:8080"); + assert_eq!(request.headers()["accept"], "application/json"); + assert_eq!(request.headers()["content-type"], "application/json"); + } +} diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index 7017ef7..e19587f 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -14,42 +14,42 @@ //! Generic implementation of owner API functions -use std::cmp; -use uuid::Uuid; - use crate::api_impl::foreign::finalize_tx as foreign_finalize; -use crate::util::OnionV3Address; -use grin_core::core::amount_to_hr_string; -use grin_core::core::hash::Hashed; -use grin_core::core::{FeeFields, Output, OutputFeatures, Transaction}; -use grin_core::libtx::proof; -use grin_keychain::ViewKey; -use grin_util::secp::{key::SecretKey, pedersen::Commitment}; -use grin_util::ToHex; - use crate::api_impl::owner_updater::StatusMessage; use crate::internal::{keys, scan, selection, tx, updater}; use crate::slate::{PaymentInfo, Slate, SlateState}; -use crate::types::{AcctPathMapping, NodeClient, TxLogEntry, WalletInfo}; +use crate::slatepack::SlatepackAddressIndex; +use crate::types::{AcctPathMapping, NodeClient, OutputData, OutputStatus, TxLogEntry, WalletInfo}; +use crate::util::OnionV3Address; use crate::{ address, - mwixnet::{create_onion, ComSignature, Hop, MixnetReqCreationParams, SwapReq}, + mwixnet::{ + create_onion, ComSignature, Hop, MixnetReqCreationParams, MwixnetReqCreationResult, + SwapReq, MAX_MWIXNET_HOPS, + }, slatepack, wallet_lock, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult, OutputCommitMapping, PaymentProof, RetrieveTxQueryArgs, ScannedBlockInfo, Slatepack, SlatepackAddress, SlatepackArmor, SlatepackBin, TxLogEntryType, ViewWallet, WalletBackend, WalletInitStatus, WalletLCProvider, }; +use grin_core::core::amount_to_hr_string; +use grin_core::core::hash::Hashed; +use grin_core::core::{FeeFields, Output, OutputFeatures, Transaction, TransactionBody}; +use grin_core::global::DEFAULT_ACCEPT_FEE_BASE; +use grin_core::libtx::proof; +use grin_keychain::ViewKey; use grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType}; +use grin_util::secp::{key::SecretKey, pedersen::Commitment}; +use grin_util::ToHex; +use grin_wallet_util::byte_ser; use ed25519_dalek::SigningKey as DalekSecretKey; use ed25519_dalek::Verifier; use ed25519_dalek::VerifyingKey as DalekPublicKey; -use x25519_dalek::{PublicKey as xPublicKey, StaticSecret}; - -use crate::slatepack::SlatepackAddressIndex; -use grin_wallet_util::byte_ser; +use std::cmp; use std::convert::{TryFrom, TryInto}; use std::sync::mpsc::Sender; +use uuid::Uuid; /// List of accounts pub fn accounts( @@ -1043,18 +1043,20 @@ pub fn cancel_tx<'a, L, C, K>( status_send_channel: &Option>, tx_id: Option, tx_slate_id: Option, + refresh_from_node: bool, ) -> Result<(), Error> where L: WalletLCProvider<'a, C, K>, C: NodeClient + 'a, K: Keychain + 'a, { - if !update_wallet_state( - wallet_inst.clone(), - keychain_mask, - status_send_channel, - false, - )? { + if refresh_from_node + && !update_wallet_state( + wallet_inst.clone(), + keychain_mask, + status_send_channel, + false, + )? { return Err(Error::TransactionCancellationError( "Can't contact running Grin node. Not Cancelling.", )); @@ -1610,7 +1612,7 @@ where }) } -/// Create MXMixnet request +/// Create mwixnet request pub fn create_mwixnet_req( w: &mut WalletBackend, keychain_mask: Option<&SecretKey>, @@ -1618,43 +1620,57 @@ pub fn create_mwixnet_req( commitment: &Commitment, lock_output: bool, use_test_rng: bool, -) -> Result +) -> Result where C: NodeClient, K: Keychain, { - let parent_key_id = w.parent_key_id(); - let keychain = w.keychain(keychain_mask)?; - let outputs = updater::retrieve_outputs(w, keychain_mask, false, None, Some(&parent_key_id))?; - - let mut output = None; - for o in &outputs { - if o.commit == *commitment { - output = Some(o.output.clone()); - break; - } + if params.server_keys.is_empty() { + return Err(Error::GenericError( + "mwixnet requires at least one server key".to_string(), + )); } - - if output.is_none() { - return Err(Error::GenericError(String::from("output not found"))); - } - - let amount = output.clone().unwrap().value; - let input_blind = keychain.derive_key( - amount, - &output.clone().unwrap().key_id, - SwitchCommitmentType::Regular, - )?; - - let mut server_pubkeys = vec![]; - for i in 0..params.server_keys.len() { - server_pubkeys.push(xPublicKey::from(&StaticSecret::from( - params.server_keys[i].0, + if params.server_keys.len() > MAX_MWIXNET_HOPS { + return Err(Error::GenericError(format!( + "mwixnet supports at most {} server keys", + MAX_MWIXNET_HOPS ))); } - let fee = grin_core::libtx::tx_fee(1, 1, 1); - let new_amount = amount - (fee * server_pubkeys.len() as u64); + let parent_key_id = w.parent_key_id(); + let keychain = w.keychain(keychain_mask)?; + let outputs = updater::retrieve_outputs(w, keychain_mask, true, None, Some(&parent_key_id))?; + let output = outputs + .into_iter() + .find(|o| o.commit == *commitment) + .map(|o| o.output) + .ok_or_else(|| Error::GenericError("output not found".to_string()))?; + let current_height = w.w2n_client().get_chain_tip()?.0; + if !output.eligible_to_spend(current_height, 1) { + return Err(Error::GenericError("output is not spendable".to_string())); + } + + let amount = output.value; + let input_blind = keychain.derive_key(amount, &output.key_id, SwitchCommitmentType::Regular)?; + + let server_pubkeys = ¶ms.server_keys; + let minimum_fee = TransactionBody::weight_by_iok(1, 1, 1) * DEFAULT_ACCEPT_FEE_BASE; + let fee_per_hop = params.fee_per_hop.unwrap_or(minimum_fee); + if fee_per_hop < minimum_fee { + return Err(Error::Fee(format!( + "mwixnet fee is below the swap minimum {}", + amount_to_hr_string(minimum_fee, true) + ))); + } + let fee = FeeFields::try_from(fee_per_hop).map_err(|e| Error::Fee(e.to_string()))?; + let total_fee = fee_per_hop + .checked_mul(server_pubkeys.len() as u64) + .ok_or_else(|| Error::Fee("mwixnet fee overflow".to_string()))?; + let total_fee_fields = FeeFields::try_from(total_fee) + .map_err(|_| Error::Fee("mwixnet total fee exceeds FeeFields limit".to_string()))?; + let new_amount = amount + .checked_sub(total_fee) + .ok_or_else(|| Error::Fee("mwixnet fees exceed output value".to_string()))?; let new_output = build_output(w, keychain_mask, OutputFeatures::Plain, new_amount)?; let secp = keychain.secp(); @@ -1665,48 +1681,74 @@ where let hops: Vec = server_pubkeys .iter() .enumerate() - .map(|(i, &p)| { + .map(|(i, &p)| -> Result { if (i + 1) == server_pubkeys.len() { - Hop { + Ok(Hop { server_pubkey: p, - excess: blind_sum.secret_key(secp).unwrap(), - fee: FeeFields::from(fee as u32), + excess: blind_sum.secret_key(secp)?, + fee, rangeproof: Some(new_output.output.proof), - } + }) } else { let hop_excess = if use_test_rng { BlindingFactor::zero() } else { BlindingFactor::rand(secp) }; - blind_sum = blind_sum.split(&hop_excess, secp).unwrap(); - Hop { + blind_sum = blind_sum.split(&hop_excess, secp)?; + Ok(Hop { server_pubkey: p, - excess: hop_excess.secret_key(secp).unwrap(), - fee: FeeFields::from(fee as u32), + excess: hop_excess.secret_key(secp)?, + fee, rangeproof: None, - } + }) } }) - .collect(); + .collect::, _>>()?; - let onion = create_onion(commitment, &hops, use_test_rng).unwrap(); - let comsig = ComSignature::sign( - amount, - &input_blind, - &onion.serialize().unwrap(), - use_test_rng, - ) - .unwrap(); + let onion = create_onion(commitment, &hops, use_test_rng) + .map_err(|e| Error::GenericError(e.to_string()))?; + let onion_bytes = onion.serialize().map_err(Error::Deser)?; + let comsig = ComSignature::sign(amount, &input_blind, &onion_bytes, use_test_rng) + .map_err(|e| Error::Signature(e.to_string()))?; // Lock output if requested - if lock_output { + let tx_id = if lock_output { let mut batch = w.batch(keychain_mask)?; - let mut update_output = batch.get(&output.as_ref().unwrap().key_id, &None)?; - update_output.lock(); - batch.lock_output(&mut update_output)?; - batch.commit()?; - } + let log_id = batch.next_tx_log_id(&parent_key_id)?; + let mut tx = TxLogEntry::new(parent_key_id.clone(), TxLogEntryType::TxSent, log_id); + tx.amount_debited = amount; + tx.amount_credited = new_amount; + tx.num_inputs = 1; + tx.num_outputs = 1; + tx.fee = Some(total_fee_fields); + tx.kernel_lookup_min_height = Some(current_height); - Ok(SwapReq { comsig, onion }) + let mut update_output = batch.get(&output.key_id, &output.mmr_index)?; + update_output.tx_log_entry = Some(log_id); + batch.lock_output(&mut update_output)?; + batch.save(OutputData { + root_key_id: parent_key_id.clone(), + key_id: new_output.key_id.clone(), + n_child: new_output.key_id.to_path().last_path_index(), + commit: Some(new_output.output.commitment().to_hex()), + mmr_index: None, + value: new_amount, + status: OutputStatus::Unconfirmed, + height: current_height, + lock_height: 0, + is_coinbase: false, + tx_log_entry: Some(log_id), + })?; + batch.save_tx_log_entry(tx, &parent_key_id)?; + batch.commit()?; + Some(log_id) + } else { + None + }; + + Ok(MwixnetReqCreationResult { + request: SwapReq { comsig, onion }, + tx_id, + }) } diff --git a/libwallet/src/mwixnet/mod.rs b/libwallet/src/mwixnet/mod.rs index ebc5a9c..bb97287 100644 --- a/libwallet/src/mwixnet/mod.rs +++ b/libwallet/src/mwixnet/mod.rs @@ -14,11 +14,16 @@ //! Onion modules for mxmixnet pub mod onion; +mod response; mod types; pub use onion::{ create_onion, onion::Onion, onion::OnionError, util as onion_util, ComSigError, ComSignature, - MwixnetPublicKey, + MAX_MWIXNET_HOPS, }; -pub use types::{Hop, MixnetReqCreationParams, SwapReq}; +pub use response::{parse_mwixnet_response, MwixnetResponse, MwixnetResponseError}; + +pub use types::{ + Hop, MixnetReqCreationParams, MwixnetReqCreationResult, MwixnetServerPublicKey, SwapReq, +}; diff --git a/libwallet/src/mwixnet/onion/crypto/dalek.rs b/libwallet/src/mwixnet/onion/crypto/dalek.rs index 1d02d7f..66c5f69 100644 --- a/libwallet/src/mwixnet/onion/crypto/dalek.rs +++ b/libwallet/src/mwixnet/onion/crypto/dalek.rs @@ -36,48 +36,51 @@ pub enum DalekError { SigVerifyFailed, } -/// Encapsulates an ed25519_dalek::PublicKey and provides (de-)serialization +/// Ed25519 server identity key #[derive(Clone, Debug, PartialEq)] -pub struct DalekPublicKey(VerifyingKey); +pub struct MwixnetServerIdentityKey(VerifyingKey); -impl DalekPublicKey { - /// Convert DalekPublicKey to hex string +impl MwixnetServerIdentityKey { + /// Convert the identity key to hex pub fn to_hex(&self) -> String { self.0.to_hex() } - /// Convert hex string to DalekPublicKey. + /// Parse an identity key from hex pub fn from_hex(hex: &str) -> Result { let err = DalekError::HexError(format!("failed to decode {}", hex)); let bytes = grin_util::from_hex(hex).map_err(|_| err.clone())?; let b = <&[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| err.clone())?; let pk = VerifyingKey::from_bytes(b).map_err(|_| err)?; - Ok(DalekPublicKey(pk)) + Ok(MwixnetServerIdentityKey(pk)) } - /// Compute DalekPublicKey from a SecretKey + /// Derive the identity key from a secret key pub fn from_secret(key: &SecretKey) -> Self { let secret = ed25519_dalek::SigningKey::from_bytes(&key.0); let pk: VerifyingKey = (&secret).into(); - DalekPublicKey(pk) + MwixnetServerIdentityKey(pk) } } -impl AsRef for DalekPublicKey { +impl AsRef for MwixnetServerIdentityKey { fn as_ref(&self) -> &VerifyingKey { &self.0 } } -/// Serializes an Option to and from hex +/// Serialize an optional identity key as hex pub mod option_dalek_pubkey_serde { - use super::DalekPublicKey; + use super::MwixnetServerIdentityKey; use grin_util::ToHex; use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; /// Write the Ed25519 public key as hex, or null - pub fn serialize(pk: &Option, serializer: S) -> Result + pub fn serialize( + pk: &Option, + serializer: S, + ) -> Result where S: Serializer, { @@ -88,29 +91,31 @@ pub mod option_dalek_pubkey_serde { } /// Read an optional Ed25519 public key from hex - pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + pub fn deserialize<'de, D>( + deserializer: D, + ) -> Result, D::Error> where D: Deserializer<'de>, { Option::::deserialize(deserializer).and_then(|res| match res { - Some(string) => DalekPublicKey::from_hex(&string) + Some(string) => MwixnetServerIdentityKey::from_hex(&string) .map_err(|e| Error::custom(e.to_string())) - .map(|pk: DalekPublicKey| Some(pk)), + .map(|pk: MwixnetServerIdentityKey| Some(pk)), None => Ok(None), }) } } -impl Readable for DalekPublicKey { +impl Readable for MwixnetServerIdentityKey { fn read(reader: &mut R) -> Result { let bytes = reader.read_fixed_bytes(32)?; let b = <&[u8; 32]>::try_from(bytes.as_slice()).map_err(|_| ser::Error::CorruptedData)?; let pk = VerifyingKey::from_bytes(b).map_err(|_| ser::Error::CorruptedData)?; - Ok(DalekPublicKey(pk)) + Ok(MwixnetServerIdentityKey(pk)) } } -impl Writeable for DalekPublicKey { +impl Writeable for MwixnetServerIdentityKey { fn write(&self, writer: &mut W) -> Result<(), ser::Error> { writer.write_fixed_bytes(self.0.to_bytes())?; Ok(()) @@ -136,7 +141,7 @@ impl DalekSignature { /// Verifies DalekSignature #[allow(dead_code)] - pub fn verify(&self, pk: &DalekPublicKey, msg: &[u8]) -> Result<(), DalekError> { + pub fn verify(&self, pk: &MwixnetServerIdentityKey, msg: &[u8]) -> Result<(), DalekError> { pk.as_ref() .verify(msg, &self.0) .map_err(|_| DalekError::SigVerifyFailed) @@ -196,20 +201,21 @@ mod tests { #[derive(Serialize, Deserialize, PartialEq, Clone, Debug)] struct TestPubKeySerde { #[serde(with = "option_dalek_pubkey_serde", default)] - pk: Option, + pk: Option, } #[test] fn pubkey_test() -> Result<(), Box> { // Test from_hex let rand_pk = rand_keypair().1; - let pk_from_hex = DalekPublicKey::from_hex(rand_pk.0.to_hex().as_str()).unwrap(); + let pk_from_hex = MwixnetServerIdentityKey::from_hex(rand_pk.0.to_hex().as_str()).unwrap(); assert_eq!(rand_pk.0, pk_from_hex.0); // Test ser (de-)serialization let bytes = ser::ser_vec(&rand_pk, ProtocolVersion::local()).unwrap(); assert_eq!(bytes.len(), 32); - let pk_from_deser: DalekPublicKey = ser::deserialize_default(&mut &bytes[..]).unwrap(); + let pk_from_deser: MwixnetServerIdentityKey = + ser::deserialize_default(&mut &bytes[..]).unwrap(); assert_eq!(rand_pk.0, pk_from_deser.0); // Test serde with Some(rand_pk) @@ -260,7 +266,7 @@ mod tests { // Sign a message let s = Secp256k1::new(); let sk = SecretKey::from_slice(&s, &[1; 32]).unwrap(); - let pk = DalekPublicKey::from_secret(&sk); + let pk = MwixnetServerIdentityKey::from_secret(&sk); let msg: [u8; 16] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; let sig = sign(&sk, &msg).unwrap(); @@ -274,7 +280,7 @@ mod tests { // Wrong pubkey let wrong_sk = SecretKey::from_slice(&s, &[2; 32]).unwrap(); - let wrong_pk = DalekPublicKey::from_secret(&wrong_sk); + let wrong_pk = MwixnetServerIdentityKey::from_secret(&wrong_sk); assert!(sig.verify(&wrong_pk, &msg).is_err()); // Test from_hex diff --git a/libwallet/src/mwixnet/onion/mod.rs b/libwallet/src/mwixnet/onion/mod.rs index aa3d7c3..c56e69e 100644 --- a/libwallet/src/mwixnet/onion/mod.rs +++ b/libwallet/src/mwixnet/onion/mod.rs @@ -19,9 +19,7 @@ pub mod crypto; pub mod onion; pub mod util; -pub use crypto::{ - comsig_serde, dalek::DalekPublicKey as MwixnetPublicKey, ComSigError, ComSignature, -}; +pub use crypto::{comsig_serde, ComSigError, ComSignature}; use chacha20::cipher::StreamCipher; use grin_core::core::FeeFields; @@ -32,14 +30,18 @@ use grin_util::secp::{ use x25519_dalek::PublicKey as xPublicKey; use x25519_dalek::{SharedSecret, StaticSecret}; +use crate::mwixnet::MwixnetServerPublicKey; use crypto::secp::random_secret; use onion::{new_stream_cipher, Onion, OnionError, Payload, RawBytes}; +/// Maximum route length, including the swap server. +pub const MAX_MWIXNET_HOPS: usize = 8; + /// Onion hop struct #[derive(Clone)] pub struct Hop { /// Comsig server public key - pub server_pubkey: xPublicKey, + pub server_pubkey: MwixnetServerPublicKey, /// Kernel excess pub excess: SecretKey, /// Fee @@ -57,7 +59,7 @@ pub fn new_hop( proof: Option, ) -> Hop { Hop { - server_pubkey: xPublicKey::from(&StaticSecret::from(server_key.0)), + server_pubkey: MwixnetServerPublicKey::from_secret(server_key), excess: hop_excess.clone(), fee: FeeFields::from(fee), rangeproof: proof, @@ -70,6 +72,11 @@ pub fn create_onion( hops: &[Hop], use_test_rng: bool, ) -> Result { + if hops.len() > MAX_MWIXNET_HOPS { + return Err(OnionError::TooManyHops { + max: MAX_MWIXNET_HOPS, + }); + } if hops.is_empty() { return Ok(Onion { ephemeral_pubkey: xPublicKey::from([0u8; 32]), @@ -84,7 +91,10 @@ pub fn create_onion( let onion_ephemeral_pk = xPublicKey::from(&ephemeral_sk); for i in 0..hops.len() { let hop = &hops[i]; - let shared_secret = ephemeral_sk.diffie_hellman(&hop.server_pubkey); + let shared_secret = ephemeral_sk.diffie_hellman(&xPublicKey::from(hop.server_pubkey.0)); + if !shared_secret.was_contributory() { + return Err(OnionError::NonContributorySharedSecret); + } shared_secrets.push(shared_secret); ephemeral_sk = StaticSecret::from(random_secret(use_test_rng).0); @@ -123,7 +133,7 @@ pub fn create_onion( #[cfg(any(test, feature = "mwixnet-test"))] pub mod test_util { use super::*; - use crypto::dalek::DalekPublicKey; + use crypto::dalek::MwixnetServerIdentityKey; use crypto::secp; use grin_core::core::hash::Hash; @@ -154,23 +164,24 @@ pub mod test_util { } pub fn rand_commit() -> Commitment { - secp::commit(rand::thread_rng().next_u64(), &secp::random_secret(false)).unwrap() + secp::commit(thread_rng().next_u64(), &random_secret(false)).unwrap() } pub fn rand_hash() -> Hash { - Hash::from_hex(secp::random_secret(false).to_hex().as_str()).unwrap() + Hash::from_hex(random_secret(false).to_hex().as_str()).unwrap() } pub fn rand_proof() -> RangeProof { let secp = Secp256k1::new(); secp.bullet_proof( - rand::thread_rng().next_u64(), - secp::random_secret(false), - secp::random_secret(false), - secp::random_secret(false), + thread_rng().next_u64(), + random_secret(false), + random_secret(false), + random_secret(false), None, None, ) + .expect("failed to generate test bulletproof") } pub fn proof( @@ -188,21 +199,106 @@ pub mod test_util { let out_value = value - (fee as u64); - let rp = secp.bullet_proof( - out_value, - blind.clone(), - secp::random_secret(false), - secp::random_secret(false), - None, - None, - ); + let rp = secp + .bullet_proof( + out_value, + blind.clone(), + random_secret(false), + random_secret(false), + None, + None, + ) + .expect("failed to generate test bulletproof"); (secp::commit(out_value, &blind).unwrap(), rp) } - pub fn rand_keypair() -> (SecretKey, DalekPublicKey) { + pub fn rand_keypair() -> (SecretKey, MwixnetServerIdentityKey) { let sk = random_secret(false); - let pk = DalekPublicKey::from_secret(&sk); + let pk = MwixnetServerIdentityKey::from_secret(&sk); (sk, pk) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::mwixnet::MwixnetServerPublicKey; + + #[test] + fn rejects_zero_key() { + let commitment = test_util::rand_commit(); + let hop = Hop { + server_pubkey: MwixnetServerPublicKey([0u8; 32]), + excess: random_secret(false), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + + assert_eq!( + create_onion(&commitment, &[hop], false), + Err(OnionError::NonContributorySharedSecret) + ); + } + + #[test] + fn rejects_too_many_hops() { + let commitment = test_util::rand_commit(); + let hops: Vec = (0..=MAX_MWIXNET_HOPS) + .map(|_| new_hop(&random_secret(false), &random_secret(false), 1, None)) + .collect(); + + assert!(create_onion(&commitment, &hops[..MAX_MWIXNET_HOPS], false).is_ok()); + + assert_eq!( + create_onion(&commitment, &hops, false), + Err(OnionError::TooManyHops { + max: MAX_MWIXNET_HOPS + }) + ); + } + + #[test] + fn x25519_key_roundtrip() { + let server_key = SecretKey::from_slice( + &grin_util::secp::Secp256k1::new(), + &grin_util::from_hex( + "a129111d283b13bf93957c06bf6605c3417b4b89db4b5cb2e7dab2c15e36e0a4", + ) + .unwrap(), + ) + .unwrap(); + let public_key = MwixnetServerPublicKey::from_secret(&server_key); + assert_eq!( + public_key.to_hex(), + "96ced236bdf1aca722ef68b818445755e6ed4bacf23e19d7b71c43efc5f0077b" + ); + let identity_key = + crypto::dalek::MwixnetServerIdentityKey::from_secret(&server_key).to_hex(); + assert_ne!(identity_key, public_key.to_hex()); + + let commitment = crypto::secp::commit(1_000, &server_key).unwrap(); + let excess = server_key.clone(); + let hop = Hop { + server_pubkey: public_key, + excess: excess.clone(), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + let onion = create_onion(&commitment, &[hop], true).unwrap(); + let peeled = onion.peel_layer(&server_key).unwrap(); + + assert_eq!(peeled.payload.excess, excess); + assert_eq!(peeled.payload.fee, FeeFields::from(1u32)); + + let identity_key = MwixnetServerPublicKey::from_hex(&identity_key).unwrap(); + let wrong_hop = Hop { + server_pubkey: identity_key, + excess: server_key.clone(), + fee: FeeFields::from(1u32), + rangeproof: None, + }; + let wrong_onion = create_onion(&commitment, &[wrong_hop], true).unwrap(); + assert!(wrong_onion.peel_layer(&server_key).is_err()); + } +} diff --git a/libwallet/src/mwixnet/onion/onion.rs b/libwallet/src/mwixnet/onion/onion.rs index e135a52..e105f4c 100644 --- a/libwallet/src/mwixnet/onion/onion.rs +++ b/libwallet/src/mwixnet/onion/onion.rs @@ -336,6 +336,15 @@ pub enum OnionError { /// Invalid Key Length #[error("Invalid key length for MAC initialization")] InvalidKeyLength, + /// Non-contributory X25519 shared secret + #[error("Non-contributory X25519 shared secret")] + NonContributorySharedSecret, + /// Too many hops + #[error("Mwixnet routes support at most {max} hops")] + TooManyHops { + /// Maximum supported number of hops + max: usize, + }, /// Serialization Error #[error("Serialization error occurred: {0:?}")] SerializationError(ser::Error), @@ -397,14 +406,16 @@ mod tests { final_commit = secp::add_excess(&final_commit, &excess).unwrap(); let proof = if i == 4 { let n1 = random_secret(false); - let rp = secp.bullet_proof( - out_value, - final_blind.clone(), - n1.clone(), - n1.clone(), - None, - None, - ); + let rp = secp + .bullet_proof( + out_value, + final_blind.clone(), + n1.clone(), + n1.clone(), + None, + None, + ) + .expect("failed to generate test bulletproof"); assert!(secp.verify_bullet_proof(final_commit, rp, None).is_ok()); Some(rp) } else { diff --git a/libwallet/src/mwixnet/response.rs b/libwallet/src/mwixnet/response.rs new file mode 100644 index 0000000..a2e0c8c --- /dev/null +++ b/libwallet/src/mwixnet/response.rs @@ -0,0 +1,105 @@ +// Copyright 2026 The Grin Developers +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Mwixnet response parsing. + +use serde::Deserialize; +use serde_json::{self, Value}; + +/// Result returned by a mwixnet server after submitting a swap request. +#[derive(Debug, Eq, PartialEq)] +pub enum MwixnetResponse { + /// The swap request was accepted. + Accepted, + /// The swap request was rejected with a message. + //TODO: extend it with actual errors from mwixnet + Rejected(String), +} + +/// Error parsing or validating a mwixnet response. +#[derive(Debug, Eq, PartialEq, thiserror::Error)] +#[error("{0}")] +pub struct MwixnetResponseError(String); + +#[derive(Deserialize)] +struct JsonRpcResponse { + result: Option, + error: Option, + id: Value, + jsonrpc: Option, +} + +#[derive(Deserialize)] +struct JsonRpcError { + #[serde(rename = "code")] + _code: i32, + message: String, +} + +/// Parse and validate the JSON-RPC response returned by a mwixnet server. +pub fn parse_mwixnet_response(response: &str) -> Result { + let response: JsonRpcResponse = serde_json::from_str(response) + .map_err(|e| MwixnetResponseError(format!("Invalid mwixnet response: {}", e)))?; + + if response.jsonrpc.as_deref() != Some("2.0") { + return Err(MwixnetResponseError( + "Invalid mwixnet response version".to_string(), + )); + } + if response.id != serde_json::json!(1) { + return Err(MwixnetResponseError( + "Invalid mwixnet response ID".to_string(), + )); + } + if response.result.is_some() && response.error.is_some() { + return Err(MwixnetResponseError( + "Mwixnet response contains both result and error".to_string(), + )); + } + if let Some(error) = response.error { + return Ok(MwixnetResponse::Rejected(error.message)); + } + if response.result == Some(serde_json::json!("success")) { + return Ok(MwixnetResponse::Accepted); + } + + Err(MwixnetResponseError(format!( + "Unexpected mwixnet response result: {:?}", + response.result + ))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_mwixnet_response() { + assert_eq!( + parse_mwixnet_response(r#"{"jsonrpc":"2.0","result":"success","id":1}"#).unwrap(), + MwixnetResponse::Accepted + ); + + assert_eq!( + parse_mwixnet_response( + r#"{"jsonrpc":"2.0","error":{"code":-32602,"message":"invalid swap"},"id":1}"#, + ) + .unwrap(), + MwixnetResponse::Rejected("invalid swap".to_string()) + ); + + assert!(parse_mwixnet_response(r#"{"jsonrpc":"2.0","result":"success","id":2}"#).is_err()); + assert!(parse_mwixnet_response(r#"{"jsonrpc":"1.0","result":"success","id":1}"#).is_err()); + } +} diff --git a/libwallet/src/mwixnet/types.rs b/libwallet/src/mwixnet/types.rs index 1213f3a..04c253d 100644 --- a/libwallet/src/mwixnet/types.rs +++ b/libwallet/src/mwixnet/types.rs @@ -13,12 +13,15 @@ // limitations under the License. //! Types related to mwixnet requests required by rest of lib crate apis -//! Should rexport all needed types here +//! Should export all needed types here use super::onion::comsig_serde; -use grin_core::libtx::secp_ser::string_or_u64; +use grin_core::libtx::secp_ser::opt_string_or_u64; use grin_util::secp::key::SecretKey; -use serde::{Deserialize, Serialize}; +use grin_util::ToHex; +use serde::de::Error as SerdeError; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use x25519_dalek::{PublicKey, StaticSecret}; pub use super::onion::{onion::Onion, ComSignature, Hop}; @@ -32,12 +35,67 @@ pub struct SwapReq { pub onion: Onion, } -/// mwixnetRequest Creation Params +/// Result of creating a mwixnet request. +#[derive(Serialize, Deserialize, Debug)] +pub struct MwixnetReqCreationResult { + /// Request to submit to the first mwixnet server. + #[serde(flatten)] + pub request: SwapReq, + /// Transaction log ID when the wallet output was locked. + pub tx_id: Option, +} + +/// Public X25519 key of an mwixnet server. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct MwixnetServerPublicKey(pub(crate) [u8; 32]); + +impl MwixnetServerPublicKey { + /// Derive the public key published by a mwixnet server. + pub fn from_secret(key: &SecretKey) -> Self { + let key = PublicKey::from(&StaticSecret::from(key.0)); + Self(key.to_bytes()) + } + + /// Parse a public key from hexadecimal representation. + pub fn from_hex(value: &str) -> Result { + let bytes = grin_util::from_hex(value).map_err(|e| e.to_string())?; + let bytes: [u8; 32] = bytes + .try_into() + .map_err(|_| "mwixnet server public key must be 32 bytes".to_string())?; + Ok(Self(bytes)) + } + + /// Return the hexadecimal representation. + pub fn to_hex(self) -> String { + self.0.to_hex() + } +} + +impl Serialize for MwixnetServerPublicKey { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&self.to_hex()) + } +} + +impl<'de> Deserialize<'de> for MwixnetServerPublicKey { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let value = String::deserialize(deserializer)?; + Self::from_hex(&value).map_err(D::Error::custom) + } +} + +/// Mwixnet request creation params #[derive(Serialize, Deserialize, Debug)] pub struct MixnetReqCreationParams { - /// List of all the server keys - pub server_keys: Vec, - /// Fees per hop - #[serde(with = "string_or_u64")] - pub fee_per_hop: u64, + /// Ordered public keys of 1 to [`super::MAX_MWIXNET_HOPS`] participating servers + pub server_keys: Vec, + /// Optional fee per hop with the swap minimum as default + #[serde(default, with = "opt_string_or_u64")] + pub fee_per_hop: Option, } diff --git a/src/bin/grin-wallet.yml b/src/bin/grin-wallet.yml index 8abdbea..ea77e92 100644 --- a/src/bin/grin-wallet.yml +++ b/src/bin/grin-wallet.yml @@ -190,6 +190,36 @@ subcommands: short: a long: address_index takes_value: true + - mwixnet: + about: EXPERIMENTAL - Swap a wallet output through an mwixnet route using Arti only + args: + - output: + help: Commitment or minimum amount of the wallet output to swap, or 'max' for the largest eligible output + index: 1 + required: true + - server: + help: Ed25519 identity key or .onion address of the first mwixnet server + long: server + takes_value: true + required: true + - key: + help: X25519 onion key of an mwixnet server, repeated in route order + long: key + takes_value: true + multiple: true + number_of_values: 1 + required: true + - fee_per_hop: + help: Fee per mwixnet server in Grin, e.g. 0.0125, with the swap minimum as default + long: fee_per_hop + takes_value: true + required: false + - minimum_confirmations: + help: Minimum confirmations required for the selected output + short: c + long: min_conf + default_value: "10" + takes_value: true - unpack: about: Unpack and display an armored Slatepack Message, decrypting if possible args: diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index fdee2b4..7fef1b7 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -23,11 +23,14 @@ use crate::util::{Mutex, ZeroingString}; use grin_core as core; use grin_core::core::amount_to_hr_string; use grin_keychain as keychain; +use grin_util::secp::constants::PEDERSEN_COMMITMENT_SIZE; +use grin_util::secp::pedersen::Commitment; use grin_wallet_api::Owner; use grin_wallet_config::{GlobalWalletConfig, TorConfig, WalletConfig}; use grin_wallet_controller::command::GlobalArgs; use grin_wallet_controller::{command, Error}; use grin_wallet_impls::{DefaultLCProvider, DefaultWalletImpl}; +use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, MwixnetServerPublicKey}; use grin_wallet_libwallet::slatepack::SlatepackAddressIndex; use grin_wallet_libwallet::{self, Slate, SlatepackAddress, SlatepackArmor}; use grin_wallet_libwallet::{IssueInvoiceTxArgs, NodeClient, WalletInst, WalletLCProvider}; @@ -574,6 +577,64 @@ fn parse_address_index_arg(args: &ArgMatches) -> Result Result { + if output.eq_ignore_ascii_case("max") { + Ok(command::MwixnetOutput::Max) + } else if output.len() == PEDERSEN_COMMITMENT_SIZE * 2 { + let commitment = grin_util::from_hex(output) + .map_err(|e| ParseError::ArgumentError(format!("Invalid output commitment: {}", e)))?; + Ok(command::MwixnetOutput::Commitment(Commitment::from_vec( + commitment, + ))) + } else { + let amount = core::core::amount_from_hr_string(output).map_err(|e| { + ParseError::ArgumentError(format!( + "Output must be a commitment, an amount, or 'max': {}", + e + )) + })?; + Ok(command::MwixnetOutput::MinimumAmount(amount)) + } +} + +pub fn parse_mwixnet_args(args: &ArgMatches) -> Result { + let output = parse_mwixnet_output(parse_required(args, "output")?)?; + + let server = parse_required(args, "server")? + .try_into() + .map_err(|e| ParseError::ArgumentError(format!("Invalid mwixnet server: {}", e)))?; + let server_keys = args + .values_of("key") + .ok_or_else(|| { + ParseError::ArgumentError("At least one server key is required".to_string()) + })? + .map(|key| { + MwixnetServerPublicKey::from_hex(key).map_err(|e| { + ParseError::ArgumentError(format!("Invalid mwixnet server key: {}", e)) + }) + }) + .collect::, _>>()?; + let fee_per_hop = args + .value_of("fee_per_hop") + .map(core::core::amount_from_hr_string) + .transpose() + .map_err(|e| ParseError::ArgumentError(format!("Invalid fee_per_hop: {}", e)))?; + let minimum_confirmations = parse_u64( + parse_required(args, "minimum_confirmations")?, + "minimum_confirmations", + )?; + + Ok(command::MwixnetArgs { + server, + output, + minimum_confirmations, + params: MixnetReqCreationParams { + server_keys, + fee_per_hop, + }, + }) +} + pub fn parse_receive_args(args: &ArgMatches) -> Result { let input_file = parse_input_file_arg(args)?; @@ -1232,6 +1293,10 @@ where test_mode, ) } + ("mwixnet", Some(args)) => { + let a = arg_parse!(parse_mwixnet_args(args)); + command::mwixnet(owner_api, km, a) + } ("receive", Some(args)) => { let a = arg_parse!(parse_receive_args(args)); command::receive(owner_api, km, a, tor_config, test_mode) @@ -1326,3 +1391,75 @@ where } } } + +#[cfg(test)] +mod mwixnet_tests { + use super::*; + + #[test] + fn parses_mwixnet_optional_fee() { + let yaml = load_yaml!("../bin/grin-wallet.yml"); + let args = vec![ + "grin-wallet", + "mwixnet", + "max", + "--server", + "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion", + "--key", + "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a", + ]; + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(args.clone()) + .unwrap(); + let parsed = parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert_eq!(parsed.params.fee_per_hop, None); + + let mut custom_args = args; + custom_args.extend(["--fee_per_hop", "0.0125"]); + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(custom_args) + .unwrap(); + let parsed = parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert_eq!(parsed.params.fee_per_hop, Some(12_500_000)); + } + + #[test] + fn mwixnet_args() { + let yaml = load_yaml!("../bin/grin-wallet.yml"); + let key = "24308f58032819d05146db48e78246139f8e30770b1fd1585392df8374d6226a"; + for keys in [vec!["--key", key], vec!["--key", key, "--key", key]] { + let key_count = keys.len() / 2; + let mut args = vec![ + "grin-wallet", + "mwixnet", + "--server", + "mza3u6vkqodqc6kjjapfbcjrg7hgpkuw6nyq5xvfjqp5jm2lfeaocwqd.onion", + ]; + args.extend(keys); + args.push("max"); + let matches = clap::App::from_yaml(yaml) + .get_matches_from_safe(args) + .unwrap(); + let parsed = + parse_mwixnet_args(matches.subcommand_matches("mwixnet").unwrap()).unwrap(); + assert!(matches!(parsed.output, command::MwixnetOutput::Max)); + assert_eq!(parsed.params.server_keys.len(), key_count); + } + } + + #[test] + fn parses_mwixnet_output_selection() { + assert!(matches!( + parse_mwixnet_output("max").unwrap(), + command::MwixnetOutput::Max + )); + assert!(matches!( + parse_mwixnet_output("10").unwrap(), + command::MwixnetOutput::MinimumAmount(10_000_000_000) + )); + assert!(matches!( + parse_mwixnet_output(&format!("08{}", "00".repeat(32))).unwrap(), + command::MwixnetOutput::Commitment(_) + )); + } +}