Mwixnet wallet support (#783)

* Update rust edition to 2021 (#749)

* build: update rust edition 2021

* cargo: format all

* build: fix tests and warnings

* Save last scanned block info for wallet scanning (#748)

* scan: save last scanned block info for initial wallet scanning

* scan: save start height at scanned block info on outputs collecting

* scan: 10k blocks batches

* fix: include last height into batch on scan

* scan: save hash of last block

* scan: add larger window (2880 blocks) to scan outputs when updating wallet state

* add test batched scan and resume, add scan doc

* rename corrupted restore test

---------

Co-authored-by: Joerg <wiesche89@googlemail.com>

* Bump openssl from 0.10.68 to 0.10.80 (#752)

* Update lmdb (#755)

* wallet: update lmdb from store crate, migrate single backend from trait to struct, update tests cargo deps and design doc

* backend: do not panic on iter and directory creation

* return  iterator errors

* build: update to last node revision

* fix: height selection for scan, remove unused mutability for wallet

* wallet: remove unused mutability conversion

* tx: store slate state at database

* build: cargo fmt

* fix: do not return error when slate not found on tx slate state update

* lmdb: do not collect all tx log records at iterator, show read errors at log

* fix: save slate state, return error if slate not found

* tx: specify amount of bad txs on slate state update error

---------

Co-authored-by: Joerg <wiesche89@googlemail.com>

* Node submodules (#758)

* build: use node submodule as dependency

* ci: checkout submodules

* docs: add contributing and build instruction

* ci: update release build

* git: remove old submodule

* git: grin staging submodule

* git: add submodule dir

* Integrated Tor arti Client (#750)

* tor: integrated client for listener, update tokio to last version

* tor: send transaction with integrated client

* build: code format

* tor: optimize bootstrap percent check

* tor: handle config build error

* tor: do not show slatepack address if tor not launched

* tor: handle keystore errors

* tor: keep service launched

* tor: bootstrap timeout, clean cache before client launch

* tor: post request timeout

* fix: post timeout

* build: update deps after merge

* tor: store arti runtime

* tor: do not send over tor if `manual` arg presents or `skip_send_attempt` set at config

* fix: arg name

* tor: handle arti runtime creation error

* tor: handle connection error

* tor: handle bootstrap error

* tor: handle start service name error

* tor: handle service config creation error

* tor: service proxy errors

* tor: handle service key creation emptiness

* build: format code

* build: update arti to 0.43, hyper to 0.10.1

* api: start foreign listener before tor connection

* tor: handle json parse errors

* tor: prevent to create several client runtimes, ability to recreate

* tor: return bootstrap error

* tor: handle host parse error

* tor: restart proxy on error

* tor: do not use integrated client when config value use_integrated is missing, add logging

* build: update lock file

* Global Tor client state (#762)

* tor: global client state

* tor: optimize init client thread-safety

* tor: handle config change on client init

* tor: add logging for client reuse or reinit

* tor: do not reuse arti client for requests

* Optimize tor sync flow (#763)

* Connection timeout (#765)

* Update deps (#768)

* build: update grin submodule to last staging

* build: update grin submodule

* build: remove remove_dir_all dependency

* build: update rpassword

* build: update semver

* build: remove unused deps

* build: update ring

* build: update lock file deps

* build: update rustyline

* build: update ed25519-dalek

* build: update curve25519-dalek

* build: update age

* build: update uuid

* fix: uuid test

* build: update x25519-dalek

* fix: x25519-dalek build

* build: update arti

* build: update grin submodule

* build: update hyper

* fix: initialize rustls provider for tests

* build: update grin submodule

* fix: rustls install provider

* tor: share getting private key

* fix: show an error on node version parse

* cli: renamed prompt password method

* fix: replace into_boxed_slice with try_from

* fix: dalek tests for onion

* config: comment expanded secret key

* fix: import api body for controller

* password: handle prompt error

* wallet: parse node error message

* tests: do not use random values for sign messages

* build: make hook executable

* build: cargo format all

* rustls: do not install provider at tests and globally

* build: update grin submodule

* build: fix api channel from grin submodule

* args: use read_password for piped prompt

* build: remove unused dep

* test: fixed signature

* preserve piped pw input

---------

Co-authored-by: wiesche <wiesche89@googlemail.com>

* Bump lodash from 4.17.21 to 4.18.1 (#774)

* build: update lodash to 4.18.1

* fix: readme

* docs: add owner api authentication setup

* build: update package-lock.json to version 3

* fix: token result, inline some vars

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>

* Global config instance (#769)

* config: global instance

* fix: cli tests

* fix: owner api tests

* config: save tor config

* fix: owner rpc tests

* fix: set config file path on init and owner api call

* tor: store launched services, get global config at command loop, remove unused listen args, check for empty global config to set default, do not save empty tor config at owner

* api: update config in memory after successful file write

* arti: restart proxy in loop

* fix: comment for tor config save

* config: set or init, update without error

* config: scoped tor config

* build: update lock file

* config: ability to store multiple configurations at memory from config path

* tor: restart service on config change

* fix: owner api test

* foreign: pass tor config from args, stop service, error handling

* arti: move runtime wrapper to single file

* config: read existing config from file at create_config

* config: handle error on read

* arti: single dir for cache

* foreign: register config listener before launch

* config: save temp

* config: remove unused error type

* config: make path and members not optional, return an error on config creation if it exists, pass default tor config to send if not set

* arti: non public runtime wrapper

* config: migrate comments

* fix: rpc tests

* config: return from cache if exists

* config: save disabled tor config when null provided at owner and tor section was not set

* config: update tor with args at listener

* config: pass pathbuf directly on creation

* config: unique tmp file name, setting permissions and providing config version

* fix global config handling

* fix config persistence

* fix tor service restart

* fix config synchronization

* require wallet close before changing data directory

* unify global config updates

---------

Co-authored-by: wiesche <wiesche89@googlemail.com>

* Wrong Slatepack address fix (#773)

* Use native tls for client (#779)

* client: use native tls and disable default features for reqwest

* build: bring back reqwest default features except tls

* client: remove tls selection

* expose mwixnet onion apis (#781)

* Update jayson and uuid (#777)

* build: update jayson and uuid

* npm: update lock file to v3

* npm: update lock file

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>

* Optimize outputs scan and selection (#780)

* Make updater APIs public (#782)

* Add mwixnet wallet request support

* mwixnet key conversion tests

* validate and track mwixnet requests

* fix Arti HTTP POST request formatting

* add mwixnet wallet CLI submission

* unlock mwixnet outputs when requests are not sent

* support automatic mwixnet output selection

* move mwixnet response parsing to libwallet

* limit mwixnet hops

* centralize grin workspace dependencies

* fix tx filter

* handle unavailable terminal colors

* reject invalid invoice locking

* clarify bip32 derivation paths

* restore derivation path comments

* tor: downgrade arti to 0.43

* owner: put active account on top of list

* account table layout

* fix: some typos, imports, unwraps and formatting

* tx: lock outputs before sending with tor

* accounts: display balances at CLI and from owner API when min confirmations are set

* unpack plain slatepacks without password (#805)

* unpack plain slatepacks without password

* cli: better open wallet handling on wallet subcommand

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>

* account: do not skip info from serialization, fix owner rpc test

* reject zero send amounts (#799)

* cli: fix short for min confirmations at accounts subcommand

* accounts: optimize accounts selection

* owner: document minimum_confirmations for accounts

* accounts: optimize selection

* preserve accounts api compatibi and clean up balances

* avoid empty wallet seeds (#801)

* fix empty wallet seeds

* mnemonic: return actual error with entropy size on recovering

* seed: extend mnemonic error description

* seed: clarify mnemonic errors

* seed: clarify mnemonic errors, fix missing phrase test

* Clean up seed handling add test

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>

* owner: use same wallet lock for selecting and locking outputs on send

* fix: do not lock for late lock

* cli: explain how to cancel

* fix: error message for offline address and integrated tor

* test: late lock for cli and owner api

* wallet: persistence for active account

* fix: owner_rpc test

* fix: lock wallet till lock outputs on send

* fix: update docs when to call tx_lock_outputs

* build: update grin submodule

* tests: get rid of owner_single_use to use correct config path

* test: parallel send attempts

* fix: cancel hint

* fix: late lock test refresh balance

* fix: set active account at single batch

* owner: document persistence of set_active_account

* cli: error when create and active args are present at account

* fix: keep display account type as str

* restore windows test fixes

* fix locking docs cancel hint and tests

* test cli send failure

* fix current account flag

* fix active account use

* test account persistence

* fix cli account selection

* fix: cmd tests

* fix: cmd test

* fix account test

* Show HTTP status when node requests fail (#820)

* ci: cargo clippy

* fix submodule checkout

* update grin for clippy fixes

* isolate tests

* fix cli test

* fix clippy warnings

* fix mwixnet output lookup

* build: update grin submodule

* git: add clippy to hook

* fix review nits

* fix checks

* mwixnet: use MwixnetServerPublicKey wrapper for hop

* build: update grin submodule

* build: clippy fixes

* mwixnet: rename dalek public key

* simplify mwixnet keys

* clarify mwixnet docs

* clarify arti usage

* simplify mwixnet tests

* tidy mwixnet code and docs

* skip spent outputs

* simplify mwixnet send

* drop host clone

* fix mwixnet selection and arti errors

* make mwixnet fee optional

* mwixnet: use fee at amount format, show min on error

* fix: fee per hop test

* fix: fee error text check

* tor: increase circuit timeout to 60

* fix mwixnet refresh and help

* build: update grin submodule and mwixnet tests

* cli: do not update wallet state on cancellation of tx after failed mwixnet request

* mwixnet: create separate owner api method to send request, do not cancel tx on failed mwixnet request

* fix mwixnet cli args and error messages

---------

Co-authored-by: ardocrat <ardocrat@gri.mw>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
This commit is contained in:
wiesche
2026-10-15 21:15:56 +02:00
committed by GitHub
co-authored by Joerg ardocrat dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
parent b5c3818713
commit 90846a4212
18 changed files with 1161 additions and 244 deletions
Generated
+10 -10
View File
@@ -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",
+96 -17
View File
@@ -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<SwapReq, Error> {
let mut w_lock = self.wallet_inst.lock();
let w = w_lock.lc_provider()?.wallet_inst()?;
) -> Result<MwixnetReqCreationResult, Error> {
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,
/// &params,
/// &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<Option<String>, 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
+25 -25
View File
@@ -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<BuiltOutput, Error>;
/**
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<String>,
lock_output: bool,
server_keys: Vec<String>,
) -> Result<SwapReq, Error>;
) -> Result<MwixnetReqCreationResult, Error>;
}
impl<L, C, K> OwnerRpc for Owner<L, C, K>
@@ -2530,28 +2536,22 @@ where
&self,
token: Token,
commitment: String,
fee_per_hop: String,
fee_per_hop: Option<String>,
lock_output: bool,
server_keys: Vec<String>,
) -> Result<SwapReq, Error> {
) -> Result<MwixnetReqCreationResult, Error> {
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::<u64>()
.map_err(|_| Error::U64Deser(fee_per_hop))?,
.map(|fee| fee.parse::<u64>().map_err(|_| Error::U64Deser(fee)))
.transpose()?,
};
Owner::create_mwixnet_req(
+122 -1
View File
@@ -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<Option<String>, 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<L, C, K>(
owner_api: &mut Owner<L, C, K>,
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::*;
+158 -9
View File
@@ -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, &params, &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, &params, &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, &params, &last_output.commit, false)
.is_err());
// let logging finish
stopper.store(false, Ordering::Relaxed);
+1 -1
Submodule grin updated: 4182d34221...da955767a3
+1 -1
View File
@@ -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)
}
+1
View File
@@ -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;
+111 -34
View File
@@ -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<TorClient<TokioNativeTlsRuntime>>, 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<Request<Full<Bytes>>, 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<IN>(tor_config: &TorConfig, input: &IN, url: &str) -> Result<String, Error>
pub fn tor_post<IN>(tor_config: &TorConfig, input: &IN, url: &str) -> Result<String, TorPostError>
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<String, Error> = thread::spawn(move || {
let (client, _) =
init_client(&state_path, &cache_path, tor_config).map_err(TorPostError::NotSent)?;
let res: Result<String, TorPostError> = 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<Bytes>>(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<TorClient<TokioNativeTlsRuntime>>, 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");
}
}
+122 -80
View File
@@ -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<C, K>(
@@ -1043,18 +1043,20 @@ pub fn cancel_tx<'a, L, C, K>(
status_send_channel: &Option<Sender<StatusMessage>>,
tx_id: Option<u32>,
tx_slate_id: Option<Uuid>,
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<C, K>(
w: &mut WalletBackend<C, K>,
keychain_mask: Option<&SecretKey>,
@@ -1618,43 +1620,57 @@ pub fn create_mwixnet_req<C, K>(
commitment: &Commitment,
lock_output: bool,
use_test_rng: bool,
) -> Result<SwapReq, Error>
) -> Result<MwixnetReqCreationResult, Error>
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 = &params.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<Hop> = server_pubkeys
.iter()
.enumerate()
.map(|(i, &p)| {
.map(|(i, &p)| -> Result<Hop, Error> {
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::<Result<Vec<_>, _>>()?;
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,
})
}
+7 -2
View File
@@ -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,
};
+30 -24
View File
@@ -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<Self, DalekError> {
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<VerifyingKey> for DalekPublicKey {
impl AsRef<VerifyingKey> for MwixnetServerIdentityKey {
fn as_ref(&self) -> &VerifyingKey {
&self.0
}
}
/// Serializes an Option<DalekPublicKey> 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<S>(pk: &Option<DalekPublicKey>, serializer: S) -> Result<S::Ok, S::Error>
pub fn serialize<S>(
pk: &Option<MwixnetServerIdentityKey>,
serializer: S,
) -> Result<S::Ok, S::Error>
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<Option<DalekPublicKey>, D::Error>
pub fn deserialize<'de, D>(
deserializer: D,
) -> Result<Option<MwixnetServerIdentityKey>, D::Error>
where
D: Deserializer<'de>,
{
Option::<String>::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<R: Reader>(reader: &mut R) -> Result<Self, ser::Error> {
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<W: Writer>(&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<DalekPublicKey>,
pk: Option<MwixnetServerIdentityKey>,
}
#[test]
fn pubkey_test() -> Result<(), Box<dyn std::error::Error>> {
// 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
+119 -23
View File
@@ -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<RangeProof>,
) -> 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<Onion, OnionError> {
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<Hop> = (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());
}
}
+19 -8
View File
@@ -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 {
+105
View File
@@ -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<Value>,
error: Option<JsonRpcError>,
id: Value,
jsonrpc: Option<String>,
}
#[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<MwixnetResponse, MwixnetResponseError> {
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());
}
}
+67 -9
View File
@@ -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<u32>,
}
/// 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<Self, String> {
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<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_hex())
}
}
impl<'de> Deserialize<'de> for MwixnetServerPublicKey {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
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<SecretKey>,
/// 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<MwixnetServerPublicKey>,
/// Optional fee per hop with the swap minimum as default
#[serde(default, with = "opt_string_or_u64")]
pub fee_per_hop: Option<u64>,
}
+30
View File
@@ -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:
+137
View File
@@ -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<Option<SlatepackAddressI
Ok(address)
}
fn parse_mwixnet_output(output: &str) -> Result<command::MwixnetOutput, ParseError> {
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<command::MwixnetArgs, ParseError> {
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::<Result<Vec<_>, _>>()?;
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<command::ReceiveArgs, ParseError> {
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(_)
));
}
}