Merge branch 'master' into contracts

Bring the contracts feature branch up to current master, which has since
landed rust 1.80 support (#722), the canonical mwixnet onion code (#726),
and node-client proxy support (#738).

Conflict resolution:
- libwallet/src/mwixnet/*: take master's (#726), dropping the contracts
  branch's older divergent copy. owner.rs::create_mwixnet_req updated to
  master's API (use_test_rng) and master's flat re-export imports.
- Cargo manifests/lock/.cargo: master's deps & version; re-add serde_with
  for Slate v5; keep contracts' .cargo/config.toml (Windows static-CRT).
- lib.rs: keep serde_derive AND serde_with macro_use; single mwixnet decl.
- error.rs: union of master + contracts variants; flat mwixnet re-exports.
- api/libwallet owner.rs: master's #738 + create_mwixnet_req plus the
  contract_* entry points; drop duplicate older create_mwixnet_req method.
- slatepack/armor.rs, node_clients/resp_types.rs: take master's.

Workspace builds; libwallet lib tests pass (34/34). The Slate version()
bug, issue #729 fix, and de-panicking follow in subsequent commits.
This commit is contained in:
jwinterm
2026-06-02 18:26:08 -04:00
30 changed files with 1152 additions and 675 deletions
Generated
+468 -450
View File
File diff suppressed because it is too large Load Diff
+15 -15
View File
@@ -1,6 +1,6 @@
[package]
name = "grin_wallet"
version = "5.4.0-contracts.0"
version = "5.4.0-alpha.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format."
license = "Apache-2.0"
@@ -30,21 +30,21 @@ semver = "0.10"
rustyline = "6"
lazy_static = "1"
grin_wallet_api = { path = "./api", version = "5.4.0-contracts.0" }
grin_wallet_impls = { path = "./impls", version = "5.4.0-contracts.0" }
grin_wallet_libwallet = { path = "./libwallet", version = "5.4.0-contracts.0" }
grin_wallet_controller = { path = "./controller", version = "5.4.0-contracts.0" }
grin_wallet_config = { path = "./config", version = "5.4.0-contracts.0" }
grin_wallet_util = { path = "./util", version = "5.4.0-contracts.0" }
grin_wallet_api = { path = "./api", version = "5.4.0-alpha.1" }
grin_wallet_impls = { path = "./impls", version = "5.4.0-alpha.1" }
grin_wallet_libwallet = { path = "./libwallet", version = "5.4.0-alpha.1" }
grin_wallet_controller = { path = "./controller", version = "5.4.0-alpha.1" }
grin_wallet_config = { path = "./config", version = "5.4.0-alpha.1" }
grin_wallet_util = { path = "./util", version = "5.4.0-alpha.1" }
##### Grin Imports
# For Release
# grin_core = "5.4.0-contracts.0"
# grin_keychain = "5.4.0-contracts.0"
# grin_util = "5.4.0-contracts.0"
# grin_api = "5.4.0-contracts.0"
grin_core = "5.3.3"
grin_keychain = "5.3.3"
grin_util = "5.3.3"
grin_api = "5.3.3"
# For beta release
@@ -54,10 +54,10 @@ grin_wallet_util = { path = "./util", version = "5.4.0-contracts.0" }
# grin_api = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_api = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_api = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing
# grin_core = { path = "../grin/core"}
+11 -11
View File
@@ -1,6 +1,6 @@
[package]
name = "grin_wallet_api"
version = "5.4.0-contracts.0"
version = "5.4.0-alpha.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Grin Wallet API"
license = "Apache-2.0"
@@ -22,17 +22,17 @@ ring = "0.16"
base64 = "0.12"
ed25519-dalek = "1.0.0-pre.4"
grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-contracts.0" }
grin_wallet_config = { path = "../config", version = "5.4.0-contracts.0" }
grin_wallet_impls = { path = "../impls", version = "5.4.0-contracts.0" }
grin_wallet_util = { path = "../util", version = "5.4.0-contracts.0" }
grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-alpha.1" }
grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" }
grin_wallet_impls = { path = "../impls", version = "5.4.0-alpha.1" }
grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" }
##### Grin Imports
# For Release
# grin_core = "5.4.0-contracts.0"
# grin_keychain = "5.4.0-contracts.0"
# grin_util = "5.4.0-contracts.0"
grin_core = "5.3.3"
grin_keychain = "5.3.3"
grin_util = "5.3.3"
# For beta release
@@ -41,9 +41,9 @@ grin_wallet_util = { path = "../util", version = "5.4.0-contracts.0" }
# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing
# grin_core = { path = "../../grin/core"}
+72 -15
View File
@@ -17,6 +17,7 @@
use chrono::prelude::*;
use ed25519_dalek::SecretKey as DalekSecretKey;
use grin_wallet_libwallet::contract::proofs::InvoiceProof;
use grin_wallet_libwallet::mwixnet::{MixnetReqCreationParams, SwapReq};
use grin_wallet_libwallet::RetrieveTxQueryArgs;
use uuid::Uuid;
@@ -31,7 +32,6 @@ use crate::libwallet::api_impl::{owner, owner_updater};
use crate::libwallet::contract::types::{
ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI,
};
use crate::libwallet::mwixnet::types::{MixnetReqCreationParams, SwapReq};
use crate::libwallet::{
AcctPathMapping, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient,
NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, Slatepack, SlatepackAddress,
@@ -40,6 +40,7 @@ use crate::libwallet::{
use crate::util::logger::LoggingConfig;
use crate::util::secp::key::SecretKey;
use crate::util::secp::pedersen;
use crate::util::secp::pedersen::Commitment;
use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString};
use grin_wallet_util::OnionV3Address;
use std::convert::TryFrom;
@@ -831,19 +832,6 @@ where
owner::contract_revoke(&mut **w, keychain_mask, &args)
}
/// Create MXMixnet request
pub fn create_mwixnet_req(
&self,
keychain_mask: Option<&SecretKey>,
params: &MixnetReqCreationParams,
commitment: &pedersen::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()?;
owner::create_mwixnet_req(&mut **w, keychain_mask, params, commitment, lock_output)
}
/// Processes an invoice tranaction created by another party, essentially
/// a `request for payment`. The incoming slate should contain a requested
/// amount, an output created by the invoicer convering the amount, and
@@ -2527,6 +2515,71 @@ where
let w = w_lock.lc_provider()?.wallet_inst()?;
owner::build_output(&mut **w, keychain_mask, features, amount)
}
// MWIXNET
/// Creates an mwixnet request [SwapReq](../grin_wallet_libwallet/api_impl/types/struct.SwapReq.html)
/// 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)
/// 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
/// * `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
/// * or [`libwallet::Error`](../grin_wallet_libwallet/struct.Error.html) if an error is encountered
///
/// # 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);
/// let keychain_mask = None;
/// let params = MixnetReqCreationParams {
/// server_keys: vec![], // Public keys here in secret key representation
/// fee_per_hop: 100,
/// };
///
/// 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(req) = result {
/// //...
/// }
/// ```
pub fn create_mwixnet_req(
&self,
keychain_mask: Option<&SecretKey>,
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()?;
owner::create_mwixnet_req(
&mut **w,
keychain_mask,
params,
commitment,
lock_output,
self.doctest_mode,
)
}
}
/// attempt to send slate synchronously with TOR
@@ -2628,13 +2681,17 @@ macro_rules! doctest_helper_setup_doc_env {
use keychain::ExtKeychain;
use tempfile::tempdir;
use grin_util::secp::pedersen::Commitment;
use std::sync::Arc;
use util::{Mutex, ZeroingString};
use api::{Foreign, Owner};
use config::WalletConfig;
use impls::{DefaultLCProvider, DefaultWalletImpl, HTTPNodeClient};
use libwallet::{BlockFees, InitTxArgs, IssueInvoiceTxArgs, Slate, WalletInst};
use libwallet::{
mwixnet::MixnetReqCreationParams, BlockFees, InitTxArgs, IssueInvoiceTxArgs, Slate,
WalletInst,
};
use uuid::Uuid;
+102 -5
View File
@@ -14,6 +14,7 @@
//! JSON-RPC Stub generation for the Owner API
use grin_wallet_libwallet::RetrieveTxQueryArgs;
use libwallet::mwixnet::SwapReq;
use uuid::Uuid;
use crate::config::{TorConfig, WalletConfig};
@@ -24,14 +25,15 @@ use crate::libwallet::contract::types::{
ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI,
};
use crate::libwallet::{
AcctPathMapping, Amount, BuiltOutput, Error, InitTxArgs, IssueInvoiceTxArgs, NodeClient,
NodeHeightResult, OutputCommitMapping, PaymentProof, Slate, SlateVersion, Slatepack,
SlatepackAddress, StatusMessage, TxLogEntry, VersionedSlate, ViewWallet, WalletInfo,
WalletLCProvider,
mwixnet::MixnetReqCreationParams, 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};
use crate::util::{static_secp_instance, Mutex, ZeroingString};
use crate::util::secp::pedersen::Commitment;
use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString};
use crate::{ECDHPubkey, Ed25519SecretKey, Owner, Token};
use easy_jsonrpc_mw;
use grin_wallet_util::OnionV3Address;
@@ -2007,6 +2009,63 @@ pub trait OwnerRpc {
features: OutputFeatures,
amount: Amount,
) -> Result<BuiltOutput, Error>;
/**
Networked version of [Owner::build_output](struct.Owner.html#method.create_mwixnet_req).
```
# grin_wallet_api::doctest_helper_json_rpc_owner_assert_response!(
# r#"
{
"jsonrpc": "2.0",
"method": "create_mwixnet_req",
"params": {
"token": "d202964900000000d302964900000000d402964900000000d502964900000000",
"commitment": "08e1da9e6dc4d6e808a718b2f110a991dd775d65ce5ae408a4e1f002a4961aa9e7",
"fee_per_hop": "5000000",
"lock_output": true,
"server_keys": [
"97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332",
"0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e",
"b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5"
]
},
"id": 1
}
# "#
# ,
# r#"
{
"id": 1,
"jsonrpc": "2.0",
"result": {
"Ok": {
"comsig": "099561ed0be59f6502ee358ee4f6760cd16d6be04d58d7a2c1bf2fd09dd7fd2d291beaae5483c6f18d1ceaae6321f06f9ba129a1ee9e7d15f152c67397a621538b5c10bbeb95140dee815c02657c91152939afe389458dc59af095e8e8e5c81a08",
"onion": {
"commit": "08e1da9e6dc4d6e808a718b2f110a991dd775d65ce5ae408a4e1f002a4961aa9e7",
"data": [
"37f68116475e1aa6b58fc911addbd0e04e7aa19ab3e82e7b5cfcaf57d82cf35e7388ce51711cc5ef8cf7630f7dc7229878f91c7ec85991a7fc0051a7bbc66569db3a3aa89ef490055f3c",
"b9ff8c0c1699808efce46d581647c65764a28e813023ae677d688282422a07505ae1a051037d7ba58f3279846d0300800fc1c5bfcc548dab815e9fd2f29df9515170c41fa6e4e44b8bcb",
"62ea6b8369686a0415e1e752b9b4d6e66cf5b6066a2d3c60d8818890a55f3adff4601466f4c6e6b646568b99ae93549a3595b7a7b4be815ced87d9297cabbd69518d7b2ed6edd14007528fd346aaea765a1165fe886666627ebcab9588b8ee1c9e98395ae67913c48eb6e924581b40182fce807f97312fb07fd5e216d99941f2b488babce4078a50cd66b28b30a66c4f54fcc127437408a99b30ffd6c3d0d8c7d39e864fc04e321b8c10138c8852d4cad0a4f2780412b9dadcc6e0f2657b7803a81bccb809ca392464be2e01755be7377d0e815698ad6ea51d4617cc92c3ccf852f038e33cc9c90992438ba5c49cca7cc188b682da684e2f4c9733a84a7b64ac5c2216ebf5926f0ee67b664fb5bab799109cbee755ce1aebc8cd352fea51cd84c333cb958093c53544c3f3ab05dba64d8f041c3b179796b476ec04b11044e39db6994ab767315e52cc0ef023432ec88ade2911612db7e74e0923889f765b58b00e3869c5072a4e882c1b721913f63bda986b8c97b7ae575f0d4be596a1ac3cd0db96ce6074ee000b32018b3bda16d7dba34a13ba9c3ce983946414c16e278351a3411cb8ef2cb8ef5b6e1667c4c58bc797c0324ae4fec8960d684e561c0e833ee4c3331c6c439b59042a62993535e23cc8a8a4cf705c0f9b1d62db4e3d76c22c01138800414b143ddff471e4df4413e842a1b41f43cc9647e47145fd6c86d4d1a34fb2f62f5a55b31c9353ee34743c548eff955f2d2143c1a86cbcb452104f96d0142db31153021bbeed995c71a92de8fb1f97269533a508085c543fcb3ee57000bb265e74187b858403aa97b6c7b085e5d5b6025cbfe5f6926d33c835f90e60fc62013e80bbe0a855da5938b4b8f83ac29c5e8251827795356222079a6d1612e2fdf93bd7836d1613c7a353ada48ce256f880bbbb3108e037e3b5647101bd4d549101b0ee73d2248a932a802a3b1beb0b69d777c4285d57e91d83e96fe2f8a1a2f182fe2c6ca37b18460cf8d7f56c201147b9be19f1d01f8ad305c1e9c4dd79b5d8719d6550432352cf737082b1e9de7a083ffbe1"
],
"pubkey": "e7ee7d51b11d09f268ade98bc9d7ae9be3c4ac124ce1c3a40e50d34460fa5f08"
}
}
}
}
# "#
# , 5, true, true, false, false);
```
*
*/
fn create_mwixnet_req(
&self,
token: Token,
commitment: String,
fee_per_hop: String,
lock_output: bool,
server_keys: Vec<String>,
) -> Result<SwapReq, Error>;
}
impl<L, C, K> OwnerRpc for Owner<L, C, K>
@@ -2475,6 +2534,44 @@ where
) -> Result<BuiltOutput, Error> {
Owner::build_output(self, (&token.keychain_mask).as_ref(), features, amount.0)
}
fn create_mwixnet_req(
&self,
token: Token,
commitment: String,
fee_per_hop: String,
lock_output: bool,
server_keys: Vec<String>,
) -> Result<SwapReq, Error> {
let commit =
Commitment::from_vec(from_hex(&commitment).map_err(|e| Error::CommitDeser(e))?);
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(|e| Error::ServerKeyDeser(e))?,
)?)
}
let req_params = MixnetReqCreationParams {
server_keys: keys,
fee_per_hop: fee_per_hop
.parse::<u64>()
.map_err(|_| Error::U64Deser(fee_per_hop))?,
};
Owner::create_mwixnet_req(
self,
(&token.keychain_mask).as_ref(),
&req_params,
&commit,
lock_output,
)
}
}
/// helper to set up a real environment to run integrated doctests
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "grin_wallet_config"
version = "5.4.0-contracts.0"
version = "5.4.0-alpha.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Configuration for grin wallet , a simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format."
license = "Apache-2.0"
@@ -16,13 +16,13 @@ serde_derive = "1"
toml = "0.5"
dirs = "2.0"
grin_wallet_util = { path = "../util", version = "5.4.0-contracts.0" }
grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" }
##### Grin Imports
# For Release
# grin_core = "5.4.0-contracts.0"
# grin_util = "5.4.0-contracts.0"
grin_core = "5.3.3"
grin_util = "5.3.3"
# For beta release
@@ -30,8 +30,8 @@ grin_wallet_util = { path = "../util", version = "5.4.0-contracts.0" }
#grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing
# grin_core = { path = "../../grin/core"}
+16 -16
View File
@@ -1,6 +1,6 @@
[package]
name = "grin_wallet_controller"
version = "5.4.0-contracts.0"
version = "5.4.0-alpha.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Controllers for grin wallet instantiation"
license = "Apache-2.0"
@@ -30,19 +30,19 @@ lazy_static = "1"
thiserror = "1"
qr_code = "1.1.0"
grin_wallet_util = { path = "../util", version = "5.4.0-contracts.0" }
grin_wallet_api = { path = "../api", version = "5.4.0-contracts.0" }
grin_wallet_impls = { path = "../impls", version = "5.4.0-contracts.0" }
grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-contracts.0" }
grin_wallet_config = { path = "../config", version = "5.4.0-contracts.0" }
grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" }
grin_wallet_api = { path = "../api", version = "5.4.0-alpha.1" }
grin_wallet_impls = { path = "../impls", version = "5.4.0-alpha.1" }
grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-alpha.1" }
grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" }
##### Grin Imports
# For Release
# grin_core = "5.4.0-contracts.0"
# grin_keychain = "5.4.0-contracts.0"
# grin_util = "5.4.0-contracts.0"
# grin_api = "5.4.0-contracts.0"
grin_core = "5.3.3"
grin_keychain = "5.3.3"
grin_util = "5.3.3"
grin_api = "5.3.3"
# For beta release
@@ -52,10 +52,10 @@ grin_wallet_config = { path = "../config", version = "5.4.0-contracts.0" }
# grin_api = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_api = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_api = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing
# grin_core = { path = "../../grin/core"}
@@ -72,14 +72,14 @@ remove_dir_all = "0.7"
##### Grin Imports
# For Release
# grin_chain = "5.4.0-contracts.0"
grin_chain = "5.3.3"
# For beta release
# grin_chain = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
grin_chain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_chain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing
# grin_chain = { path = "../../grin/chain"}
+10 -10
View File
@@ -82,16 +82,16 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("mining")?;
}
let mut bh = 10u64;
let mut _bh = 10u64;
let _ =
test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false);
test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, _bh as usize, false);
// Sanity check wallet 1 contents
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?;
assert!(wallet1_refreshed);
assert_eq!(wallet1_info.last_confirmed_height, bh);
assert_eq!(wallet1_info.total, bh * reward);
assert_eq!(wallet1_info.last_confirmed_height, _bh);
assert_eq!(wallet1_info.total, _bh * reward);
Ok(())
})?;
@@ -138,10 +138,10 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
api.post_tx(m, &slate, false)?;
Ok(())
})?;
bh += 1;
_bh += 1;
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
bh += 3;
_bh += 3;
// Check transaction log for wallet 2
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
@@ -151,7 +151,7 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
assert!(txs.len() == 1);
println!(
"last confirmed height: {}, bh: {}",
wallet2_info.last_confirmed_height, bh
wallet2_info.last_confirmed_height, _bh
);
assert!(refreshed);
Ok(())
@@ -163,10 +163,10 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
let (_, wallet1_info) = api.retrieve_summary_info(m, true, 1)?;
let (refreshed, txs) = api.retrieve_txs(m, true, None, None, None)?;
assert!(refreshed);
assert_eq!(txs.len() as u64, bh + 1);
assert_eq!(txs.len() as u64, _bh + 1);
println!(
"Wallet 1: last confirmed height: {}, bh: {}",
wallet1_info.last_confirmed_height, bh
wallet1_info.last_confirmed_height, _bh
);
Ok(())
})?;
@@ -248,7 +248,7 @@ fn invoice_tx_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
// test that payee can only cancel once
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
bh += 3;
_bh += 3;
wallet::controller::owner_single_use(Some(wallet2.clone()), mask2, None, |api, m| {
// Wallet 2 inititates an invoice transaction, requesting payment
+190
View File
@@ -0,0 +1,190 @@
// Copyright 2024 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.
//! Test a wallet sending to self, then creation of comsig request
#[macro_use]
extern crate log;
extern crate grin_wallet_controller as wallet;
extern crate grin_wallet_impls as impls;
use grin_core as core;
use grin_util as util;
use grin_util::secp::key::SecretKey;
use grin_wallet_libwallet as libwallet;
use impls::test_framework::{self, LocalWalletClient};
use libwallet::{mwixnet::MixnetReqCreationParams, InitTxArgs};
use std::sync::atomic::Ordering;
use std::thread;
use std::time::Duration;
#[macro_use]
mod common;
use common::{clean_output_dir, create_wallet_proxy, setup};
/// self send impl
fn mwixnet_test_impl(test_dir: &'static str) -> Result<(), libwallet::Error> {
// Create a new proxy to simulate server and wallet responses
let mut wallet_proxy = create_wallet_proxy(test_dir);
let chain = wallet_proxy.chain.clone();
let stopper = wallet_proxy.running.clone();
// Create a new wallet test client, and set its queues to communicate with the
// proxy
create_wallet_and_add!(
client1,
wallet1,
mask1_i,
test_dir,
"wallet1",
None,
&mut wallet_proxy,
true
);
let mask1 = (&mask1_i).as_ref();
// Set the wallet proxy listener running
thread::spawn(move || {
if let Err(e) = wallet_proxy.run() {
error!("Wallet Proxy error: {}", e);
}
});
// few values to keep things shorter
let reward = core::consensus::REWARD;
// add some accounts
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
api.create_account_path(m, "mining")?;
api.create_account_path(m, "listener")?;
Ok(())
})?;
// Get some mining done
{
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("mining")?;
}
let mut bh = 10u64;
let _ =
test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, bh as usize, false);
// Should have 5 in account1 (5 spendable), 5 in account (2 spendable)
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?;
assert!(wallet1_refreshed);
assert_eq!(wallet1_info.last_confirmed_height, bh);
assert_eq!(wallet1_info.total, bh * reward);
// send to send
let args = InitTxArgs {
src_acct_name: Some("mining".to_owned()),
amount: reward * 2,
minimum_confirmations: 2,
max_outputs: 500,
num_change_outputs: 1,
selection_strategy_is_use_all: true,
..Default::default()
};
let mut slate = api.init_send_tx(m, args)?;
api.tx_lock_outputs(m, &slate)?;
// Send directly to self
wallet::controller::foreign_single_use(wallet1.clone(), mask1_i.clone(), |api| {
slate = api.receive_tx(&slate, Some("listener"), None)?;
Ok(())
})?;
slate = api.finalize_tx(m, &slate)?;
api.post_tx(m, &slate, false)?; // mines a block
bh += 1;
Ok(())
})?;
let _ = test_framework::award_blocks_to_wallet(&chain, wallet1.clone(), mask1, 3, false);
bh += 3;
// Check total in mining account
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?;
assert!(wallet1_refreshed);
assert_eq!(wallet1_info.last_confirmed_height, bh);
assert_eq!(wallet1_info.total, bh * reward - reward * 2);
Ok(())
})?;
// Check total in 'listener' account
{
wallet_inst!(wallet1, w);
w.set_parent_key_id_by_name("listener")?;
}
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let (wallet1_refreshed, wallet1_info) = api.retrieve_summary_info(m, true, 1)?;
assert!(wallet1_refreshed);
assert_eq!(wallet1_info.last_confirmed_height, bh);
assert_eq!(wallet1_info.total, 2 * reward);
Ok(())
})?;
// Recipient wallet creates a mwixnet request from the last output
wallet::controller::owner_single_use(Some(wallet1.clone()), mask1, None, |api, m| {
let secp_locked = util::static_secp_instance();
let secp = secp_locked.lock();
let server_pubkey_str_1 =
"97444ae673bb92c713c1a2f7b8882ffbfc1c67401a280a775dce1a8651584332";
let server_pubkey_str_2 =
"0c9414341f2140ed34a5a12a6479bf5a6404820d001ab81d9d3e8cc38f049b4e";
let server_pubkey_str_3 =
"b58ece97d60e71bb7e53218400b0d67bfe6a3cb7d3b4a67a44f8fb7c525cbca5";
let server_key_1 =
SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_1).unwrap())
.unwrap();
let server_key_2 =
SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_2).unwrap())
.unwrap();
let server_key_3 =
SecretKey::from_slice(&secp, &grin_util::from_hex(&server_pubkey_str_3).unwrap())
.unwrap();
let params = MixnetReqCreationParams {
server_keys: vec![server_key_1, server_key_2, server_key_3],
fee_per_hop: 50_000_000,
};
let outputs = api.retrieve_outputs(mask1, false, false, None)?;
// get last output
let last_output = outputs.1[outputs.1.len() - 1].clone();
let mwixnet_req = api.create_mwixnet_req(m, &params, &last_output.commit, true)?;
println!("MWIXNET REQ: {:?}", mwixnet_req);
// check output we created comsig for is indeed locked
let outputs = api.retrieve_outputs(mask1, false, false, None)?;
// get last output
let last_output = outputs.1[outputs.1.len() - 1].clone();
assert!(last_output.output.status == libwallet::OutputStatus::Locked);
Ok(())
})?;
// let logging finish
stopper.store(false, Ordering::Relaxed);
thread::sleep(Duration::from_millis(1000));
Ok(())
}
#[test]
fn mwixnet_comsig_test() {
let test_dir = "test_output/mwixnet";
setup(test_dir);
if let Err(e) = mwixnet_test_impl(test_dir) {
panic!("Libwallet Error: {}", e);
}
clean_output_dir(test_dir);
}
+16 -16
View File
@@ -1,6 +1,6 @@
[package]
name = "grin_wallet_impls"
version = "5.4.0-contracts.0"
version = "5.4.0-alpha.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Concrete types derived from libwallet traits"
license = "Apache-2.0"
@@ -36,19 +36,19 @@ sysinfo = "0.29"
base64 = "0.12.0"
url = "2.1"
grin_wallet_util = { path = "../util", version = "5.4.0-contracts.0" }
grin_wallet_config = { path = "../config", version = "5.4.0-contracts.0" }
grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-contracts.0" }
grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" }
grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" }
grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-alpha.1" }
##### Grin Imports
# For Release
# grin_core = "5.4.0-contracts.0"
# grin_keychain = "5.4.0-contracts.0"
# grin_chain = "5.4.0-contracts.0"
# grin_util = "5.4.0-contracts.0"
# grin_api = "5.4.0-contracts.0"
# grin_store = "5.4.0-contracts.0"
grin_core = "5.3.3"
grin_keychain = "5.3.3"
grin_chain = "5.3.3"
grin_util = "5.3.3"
grin_api = "5.3.3"
grin_store = "5.3.3"
# For beta release
@@ -60,12 +60,12 @@ grin_wallet_libwallet = { path = "../libwallet", version = "5.4.0-contracts.0" }
# grin_store = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_chain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_api = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_store = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_chain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_api = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_store = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing
# grin_core = { path = "../../grin/core"}
+2 -1
View File
@@ -204,9 +204,10 @@ impl HttpSlateSender {
let client = if !self.use_socks {
Client::new()
} else {
Client::with_socks_proxy(
Client::with_proxy(
self.socks_proxy_addr
.ok_or_else(|| ClientError::Internal("No socks proxy address set".into()))?,
"socks5h://",
)
}
.map_err(|_| ClientError::Internal("Unable to create http client".into()))?;
+6 -5
View File
@@ -65,11 +65,11 @@ impl Client {
Self::build(None)
}
pub fn with_socks_proxy(socks_proxy_addr: SocketAddr) -> Result<Self, Error> {
Self::build(Some(socks_proxy_addr))
pub fn with_proxy(socks_proxy_addr: SocketAddr, scheme: &'static str) -> Result<Self, Error> {
Self::build(Some((socks_proxy_addr, scheme)))
}
fn build(socks_proxy_addr: Option<SocketAddr>) -> Result<Self, Error> {
fn build(proxy: Option<(SocketAddr, &str)>) -> Result<Self, Error> {
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static("grin-client"));
headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
@@ -80,8 +80,9 @@ impl Client {
.use_rustls_tls()
.default_headers(headers);
if let Some(s) = socks_proxy_addr {
let proxy = Proxy::all(&format!("socks5h://{}:{}", s.ip(), s.port()))
if let Some(p) = proxy {
let (addr, scheme) = p;
let proxy = Proxy::all(&format!("{}{}:{}", scheme, addr.ip(), addr.port()))
.map_err(|e| Error::Internal(format!("Unable to create proxy: {}", e)))?;
builder = builder.proxy(proxy);
}
+20 -6
View File
@@ -15,17 +15,17 @@
//! Client functions, implementations of the NodeClient trait
use crate::api::{self, LocatedTxKernel, OutputListing, OutputPrintable};
use crate::client_utils::{Client, RUNTIME};
use crate::core::core::{Transaction, TxKernel};
use crate::libwallet;
use crate::libwallet::{NodeClient, NodeVersionInfo};
use crate::util::secp::pedersen;
use crate::util::ToHex;
use futures::stream::FuturesUnordered;
use futures::TryStreamExt;
use std::collections::HashMap;
use std::env;
use crate::client_utils::{Client, RUNTIME};
use crate::libwallet;
use crate::util::secp::pedersen;
use crate::util::ToHex;
use std::net::SocketAddr;
use super::resp_types::*;
use crate::client_utils::json_rpc::*;
@@ -46,8 +46,22 @@ impl HTTPNodeClient {
node_url: &str,
node_api_secret: Option<String>,
) -> Result<HTTPNodeClient, libwallet::Error> {
Self::new_proxy(node_url, node_api_secret, None)
}
/// Create a new client with proxy
pub fn new_proxy(
node_url: &str,
node_api_secret: Option<String>,
proxy: Option<(SocketAddr, &'static str)>,
) -> Result<HTTPNodeClient, libwallet::Error> {
let client = if let Some((a, s)) = proxy {
Client::with_proxy(a, s)
} else {
Client::new()
};
Ok(HTTPNodeClient {
client: Client::new().map_err(|_| libwallet::Error::Node)?,
client: client.map_err(|_| libwallet::Error::Node)?,
node_url: node_url.to_owned(),
node_api_secret: node_api_secret,
node_version_info: None,
+1
View File
@@ -14,6 +14,7 @@
// Derived from https://github.com/apoelstra/rust-jsonrpc
//! JSON RPC Types for V2 node client
#[allow(dead_code)]
#[derive(Debug, Deserialize)]
pub struct GetTipResp {
+14 -20
View File
@@ -1,6 +1,6 @@
[package]
name = "grin_wallet_libwallet"
version = "5.4.0-contracts.0"
version = "5.4.0-alpha.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Simple, private and scalable cryptocurrency implementation based on the MimbleWimble chain format."
license = "Apache-2.0"
@@ -15,8 +15,8 @@ blake2-rfc = "0.2"
rand = "0.6"
serde = "1"
serde_derive = "1"
serde_json = "1"
serde_with = { version = "1", features = ["chrono"] }
serde_json = "1"
log = "0.4"
uuid = { version = "0.8", features = ["serde", "v4"] }
chrono = { version = "0.4.11", features = ["serde"] }
@@ -24,7 +24,7 @@ lazy_static = "1"
strum = "0.18"
strum_macros = "0.18"
thiserror = "1"
ed25519-dalek = "1.0.1"
ed25519-dalek = "1.0.0-pre.4"
x25519-dalek = "0.6"
base64 = "0.9"
regex = "1.3"
@@ -37,22 +37,20 @@ bech32 = "0.7"
byteorder = "1.3"
num-bigint = "0.2"
grin_wallet_util = { path = "../util", version = "5.4.0-contracts.0" }
grin_wallet_config = { path = "../config", version = "5.4.0-contracts.0" }
grin_secp256k1zkp = { version = "0.7.12", features = ["bullet-proof-sizing"]}
#mwixnet onion
chacha20 = "0.8.1"
hmac = { version = "0.12.0", features = ["std"]}
grin_wallet_util = { path = "../util", version = "5.4.0-alpha.1" }
grin_wallet_config = { path = "../config", version = "5.4.0-alpha.1" }
##### Grin Imports
# For Release
# grin_core = "5.4.0-contracts.0"
# grin_keychain = "5.4.0-contracts.0"
# grin_util = "5.4.0-contracts.0"
# grin_store = "5.4.0-contracts.0"
grin_core = "5.3.3"
grin_keychain = "5.3.3"
grin_util = "5.3.3"
grin_store = "5.3.3"
# For beta release
@@ -62,10 +60,10 @@ hmac = { version = "0.12.0", features = ["std"]}
# grin_store = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
grin_store = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_core = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_keychain = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_store = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing
# grin_core = { path = "../../grin/core"}
@@ -73,8 +71,4 @@ grin_store = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { path = "../../grin/util"}
# grin_store = { path = "../../grin/store"}
# mw-mixnet
#####
+20 -9
View File
@@ -24,23 +24,22 @@ use crate::grin_core::libtx::proof;
use crate::grin_keychain::ViewKey;
use crate::grin_util::secp::key::SecretKey;
use crate::grin_util::secp::pedersen;
use crate::grin_util::secp::pedersen::Commitment;
use crate::grin_util::{static_secp_instance, Mutex, ToHex};
use crate::util::{OnionV3Address, OnionV3AddressError};
use crate::api_impl::owner_updater::StatusMessage;
use crate::contract::types::{ContractNewArgsAPI, ContractRevokeArgsAPI, ContractSetupArgsAPI};
use crate::grin_keychain::{BlindingFactor, Identifier, Keychain, SwitchCommitmentType};
use crate::mwixnet::onion::create_onion;
use crate::mwixnet::types::{
add_excess, new_hop, random_secret, ComSignature, Hop, MixnetReqCreationParams, SwapReq,
};
use crate::internal::{keys, scan, selection, tx, updater};
use crate::slate::{PaymentInfo, Slate, SlateState};
use crate::types::{AcctPathMapping, NodeClient, TxLogEntry, WalletBackend, WalletInfo};
use crate::Error;
use crate::{
address, contract, wallet_lock, BuiltOutput, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult,
address, contract,
mwixnet::{create_onion, ComSignature, Hop, MixnetReqCreationParams, SwapReq},
wallet_lock, BuiltOutput, InitTxArgs, IssueInvoiceTxArgs, NodeHeightResult,
OutputCommitMapping, PaymentProof, RetrieveTxQueryArgs, ScannedBlockInfo, Slatepack,
SlatepackAddress, Slatepacker, SlatepackerArgs, TxLogEntryType, ViewWallet, WalletInitStatus,
WalletInst, WalletLCProvider,
@@ -1609,8 +1608,9 @@ pub fn create_mwixnet_req<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
params: &MixnetReqCreationParams,
commitment: &pedersen::Commitment,
commitment: &Commitment,
lock_output: bool,
use_test_rng: bool,
) -> Result<SwapReq, Error>
where
T: WalletBackend<'a, C, K>,
@@ -1668,7 +1668,12 @@ where
rangeproof: Some(new_output.output.proof.clone()),
}
} else {
let hop_excess = BlindingFactor::rand(&secp);
let hop_excess;
if use_test_rng {
hop_excess = BlindingFactor::zero();
} else {
hop_excess = BlindingFactor::rand(&secp);
}
blind_sum = blind_sum.split(&hop_excess, &secp).unwrap();
Hop {
server_pubkey: p.clone(),
@@ -1680,8 +1685,14 @@ where
})
.collect();
let onion = create_onion(&commitment, &hops).unwrap();
let comsig = ComSignature::sign(amount, &input_blind, &onion.serialize().unwrap()).unwrap();
let onion = create_onion(&commitment, &hops, use_test_rng).unwrap();
let comsig = ComSignature::sign(
amount,
&input_blind,
&onion.serialize().unwrap(),
use_test_rng,
)
.unwrap();
// Lock output if requested
if lock_output {
+2
View File
@@ -26,6 +26,8 @@ use crate::SlatepackAddress;
use chrono::prelude::*;
use ed25519_dalek::Signature as DalekSignature;
pub use crate::mwixnet::{Hop, MixnetReqCreationParams, SwapReq};
/// Type for storing amounts (in nanogrins).
/// Serializes as a string but can deserialize from a string or u64.
#[derive(Serialize, Deserialize)]
+14 -2
View File
@@ -67,11 +67,11 @@ pub enum Error {
/// Comsig error
#[error("Comsig error: {0}")]
ComSig(#[from] crate::mwixnet::onion::crypto::comsig::ComSigError),
ComSig(#[from] crate::mwixnet::ComSigError),
/// mwixnet Onion error
#[error("Onion error: {0}")]
Onion(#[from] crate::mwixnet::onion::onion::OnionError),
Onion(#[from] crate::mwixnet::OnionError),
/// Callback implementation error conversion
#[error("Trait Implementation error")]
@@ -189,6 +189,18 @@ pub enum Error {
#[error("Committed Error: {0}")]
Commit(String),
/// Error Deserializing commit
#[error("Commit Deserialize Error: {0}")]
CommitDeser(String),
/// Error Deserializing key
#[error("Server Key Deserialize Error: {0}")]
ServerKeyDeser(String),
/// Parsing integert
#[error("Can't parse as u64: {0}")]
U64Deser(String),
/// Can't parse slate version
#[error("Can't parse slate version")]
SlateVersionParse,
+3 -2
View File
@@ -32,6 +32,8 @@ use grin_wallet_util as util;
use blake2_rfc as blake2;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_with;
#[macro_use]
@@ -48,11 +50,10 @@ pub mod api_impl;
pub mod contract;
mod error;
mod internal;
pub mod mwixnet;
mod slate;
pub mod slate_versions;
pub mod slatepack;
pub mod mwixnet;
mod types;
pub use crate::error::Error;
+9 -2
View File
@@ -13,5 +13,12 @@
// limitations under the License.
//! Onion modules for mxmixnet
pub mod onion;
pub mod types;
mod onion;
mod types;
pub use onion::{
create_onion, onion::Onion, onion::OnionError, util as onion_util, ComSigError, ComSignature,
MwixnetPublicKey,
};
pub use types::{Hop, MixnetReqCreationParams, SwapReq};
+41 -16
View File
@@ -14,12 +14,14 @@
//! Comsig modules for mxmixnet
use secp256k1zkp::{self, pedersen::Commitment, ContextFlag, Secp256k1, SecretKey};
use grin_util::secp::{
self as secp256k1zkp, pedersen::Commitment, rand::thread_rng, ContextFlag, Secp256k1, SecretKey,
};
use blake2_rfc::blake2b::Blake2b;
use byteorder::{BigEndian, ByteOrder};
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use secp256k1zkp::rand::thread_rng;
use rand::rngs::mock::StepRng;
use thiserror::Error;
/// A generalized Schnorr signature with a pedersen commitment value & blinding factors as the keys
@@ -33,8 +35,10 @@ pub struct ComSignature {
/// Error types for Commitment Signatures
#[derive(Error, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub enum ComSigError {
/// Invalid commitment signature
#[error("Commitment signature is invalid")]
InvalidSig,
/// Secp256k1zkp error
#[error("Secp256k1zkp error: {0:?}")]
Secp256k1zkp(secp256k1zkp::Error),
}
@@ -46,6 +50,7 @@ impl From<secp256k1zkp::Error> for ComSigError {
}
impl ComSignature {
/// Create a new ComSignature
pub fn new(pub_nonce: &Commitment, s: &SecretKey, t: &SecretKey) -> ComSignature {
ComSignature {
pub_nonce: pub_nonce.to_owned(),
@@ -54,25 +59,41 @@ impl ComSignature {
}
}
#[allow(dead_code)]
/// Sign commitment with amount, blinding factor, and message
pub fn sign(
amount: u64,
blind: &SecretKey,
msg: &Vec<u8>,
use_test_rng: bool,
) -> Result<ComSignature, ComSigError> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let mut amt_bytes = [0; 32];
BigEndian::write_u64(&mut amt_bytes[24..32], amount);
let k_amt = SecretKey::from_slice(&secp, &amt_bytes)?;
let k_1;
let k_2;
let k_1 = SecretKey::new(&secp, &mut thread_rng());
let k_2 = SecretKey::new(&secp, &mut thread_rng());
if use_test_rng {
// allow for consistent test results
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
k_1 = SecretKey::new(&secp, &mut test_rng);
k_2 = SecretKey::new(&secp, &mut test_rng);
} else {
k_1 = SecretKey::new(&secp, &mut thread_rng());
k_2 = SecretKey::new(&secp, &mut thread_rng());
}
let commitment = secp.commit(amount, blind.clone())?;
let nonce_commitment = secp.commit_blind(k_1.clone(), k_2.clone())?;
let e = ComSignature::calc_challenge(&secp, &commitment, &nonce_commitment, &msg)?;
let e = ComSignature::calc_challenge(
&secp,
&commitment,
&nonce_commitment,
&msg,
use_test_rng,
)?;
// s = k_1 + (e * amount)
let mut s = k_amt.clone();
@@ -87,20 +108,20 @@ impl ComSignature {
Ok(ComSignature::new(&nonce_commitment, &s, &t))
}
#[allow(non_snake_case)]
/// Verify the commitment signature
pub fn verify(&self, commit: &Commitment, msg: &Vec<u8>) -> Result<(), ComSigError> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let S1 = secp.commit_blind(self.s.clone(), self.t.clone())?;
let s1 = secp.commit_blind(self.s.clone(), self.t.clone())?;
let mut Ce = commit.to_pubkey(&secp)?;
let e = ComSignature::calc_challenge(&secp, &commit, &self.pub_nonce, &msg)?;
Ce.mul_assign(&secp, &e)?;
let mut ce = commit.to_pubkey(&secp)?;
let e = ComSignature::calc_challenge(&secp, &commit, &self.pub_nonce, &msg, false)?;
ce.mul_assign(&secp, &e)?;
let commits = vec![Commitment::from_pubkey(&secp, &Ce)?, self.pub_nonce.clone()];
let S2 = secp.commit_sum(commits, Vec::new())?;
let commits = vec![Commitment::from_pubkey(&secp, &ce)?, self.pub_nonce.clone()];
let s2 = secp.commit_sum(commits, Vec::new())?;
if S1 != S2 {
if s1 != s2 {
return Err(ComSigError::InvalidSig);
}
@@ -112,8 +133,12 @@ impl ComSignature {
commit: &Commitment,
nonce_commit: &Commitment,
msg: &Vec<u8>,
use_test_rng: bool,
) -> Result<SecretKey, ComSigError> {
let mut challenge_hasher = Blake2b::new(32);
if use_test_rng {
return Ok(super::secp::random_secret(use_test_rng));
}
challenge_hasher.update(&commit.0);
challenge_hasher.update(&nonce_commit.0);
challenge_hasher.update(msg);
@@ -178,8 +203,8 @@ impl Writeable for ComSignature {
mod tests {
use super::{ComSigError, ComSignature, ContextFlag, Secp256k1, SecretKey};
use grin_util::secp::rand::{thread_rng, RngCore};
use rand::Rng;
use secp256k1zkp::rand::{thread_rng, RngCore};
/// Test signing and verification of ComSignatures
#[test]
@@ -189,7 +214,7 @@ mod tests {
let amount = thread_rng().next_u64();
let blind = SecretKey::new(&secp, &mut thread_rng());
let msg: [u8; 16] = rand::thread_rng().gen();
let comsig = ComSignature::sign(amount, &blind, &msg.to_vec())?;
let comsig = ComSignature::sign(amount, &blind, &msg.to_vec(), false)?;
let commit = secp.commit(amount, blind.clone())?;
assert!(comsig.verify(&commit, &msg.to_vec()).is_ok());
+6 -2
View File
@@ -14,9 +14,9 @@
//! Dalek key wrapper for mwixnet primitives
use super::secp::SecretKey;
use grin_util::secp::key::SecretKey;
use ed25519_dalek::{Keypair, PublicKey, Signature, Signer, Verifier};
use ed25519_dalek::{PublicKey, Signature, Verifier};
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use grin_util::ToHex;
use thiserror::Error;
@@ -68,6 +68,7 @@ impl AsRef<PublicKey> for DalekPublicKey {
}
}
#[cfg(test)]
/// Serializes an Option<DalekPublicKey> to and from hex
pub mod option_dalek_pubkey_serde {
use super::DalekPublicKey;
@@ -144,6 +145,7 @@ impl AsRef<Signature> for DalekSignature {
}
/// Serializes a DalekSignature to and from hex
#[cfg(test)]
pub mod dalek_sig_serde {
use super::DalekSignature;
use grin_util::ToHex;
@@ -171,7 +173,9 @@ pub mod dalek_sig_serde {
/// Dalek signature sign wrapper
// TODO: This is likely duplicated throughout crate, check
#[cfg(test)]
pub fn sign(sk: &SecretKey, message: &[u8]) -> Result<DalekSignature, DalekError> {
use ed25519_dalek::{Keypair, Signer};
let secret =
ed25519_dalek::SecretKey::from_bytes(&sk.0).map_err(|_| DalekError::KeyParseError)?;
let public: PublicKey = (&secret).into();
+3 -1
View File
@@ -1,4 +1,4 @@
// Copyright 2023 The Grin Developers
// Copyright 2024 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.
@@ -17,3 +17,5 @@
pub mod comsig;
pub mod dalek;
pub mod secp;
pub use comsig::{comsig_serde, ComSigError, ComSignature};
+36 -17
View File
@@ -1,4 +1,4 @@
// Copyright 2023 The Grin Developers
// Copyright 2024 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.
@@ -12,26 +12,30 @@
// See the License for the specific language governing permissions and
// limitations under the License.
//! SECP wrapper functions for onion/comsig
//! TODO: Likely redundant stuff in here, trim
//! SECP operations for comsig
pub use secp256k1zkp::aggsig;
pub use secp256k1zkp::constants::{
AGG_SIGNATURE_SIZE, COMPRESSED_PUBLIC_KEY_SIZE, MAX_PROOF_SIZE, PEDERSEN_COMMITMENT_SIZE,
SECRET_KEY_SIZE,
pub use grin_util::secp::{
self as secp256k1zkp,
constants::SECRET_KEY_SIZE,
key::{SecretKey, ZERO_KEY},
pedersen::Commitment,
rand::thread_rng,
ContextFlag, Secp256k1,
};
pub use secp256k1zkp::ecdh::SharedSecret;
pub use secp256k1zkp::key::{PublicKey, SecretKey, ZERO_KEY};
pub use secp256k1zkp::pedersen::{Commitment, RangeProof};
pub use secp256k1zkp::{ContextFlag, Message, Secp256k1, Signature};
use grin_core::ser::{self, Reader};
use secp256k1zkp::rand::thread_rng;
use rand::rngs::mock::StepRng;
/// Generate a random SecretKey.
pub fn random_secret() -> SecretKey {
pub fn random_secret(use_test_rng: bool) -> SecretKey {
let secp = Secp256k1::new();
SecretKey::new(&secp, &mut thread_rng())
if use_test_rng {
// allow for consistent test results
let mut test_rng = StepRng::new(1_234_567_890_u64, 1);
SecretKey::new(&secp, &mut test_rng)
} else {
SecretKey::new(&secp, &mut thread_rng())
}
}
/// Deserialize a SecretKey from a Reader
@@ -43,6 +47,7 @@ pub fn read_secret_key<R: Reader>(reader: &mut R) -> Result<SecretKey, ser::Erro
}
/// Build a Pedersen Commitment using the provided value and blinding factor
#[cfg(test)]
pub fn commit(value: u64, blind: &SecretKey) -> Result<Commitment, secp256k1zkp::Error> {
let secp = Secp256k1::with_caps(ContextFlag::Commit);
let commit = secp.commit(value, blind.clone())?;
@@ -71,9 +76,23 @@ pub fn sub_value(commitment: &Commitment, value: u64) -> Result<Commitment, secp
}
/// Signs the message with the provided SecretKey
pub fn sign(sk: &SecretKey, msg: &Message) -> Result<Signature, secp256k1zkp::Error> {
#[cfg(test)]
#[allow(dead_code)]
pub fn sign(
sk: &SecretKey,
msg: &grin_util::secp::Message,
) -> Result<grin_util::secp::Signature, secp256k1zkp::Error> {
let secp = Secp256k1::with_caps(ContextFlag::Full);
let pubkey = PublicKey::from_secret_key(&secp, &sk)?;
let sig = aggsig::sign_single(&secp, &msg, &sk, None, None, None, Some(&pubkey), None)?;
let pubkey = grin_util::secp::PublicKey::from_secret_key(&secp, &sk)?;
let sig = grin_util::secp::aggsig::sign_single(
&secp,
&msg,
&sk,
None,
None,
None,
Some(&pubkey),
None,
)?;
Ok(sig)
}
+34 -21
View File
@@ -1,4 +1,4 @@
// Copyright 2023 The Grin Developers
// Copyright 2024 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.
@@ -14,19 +14,26 @@
//! Onion module definition
pub mod crypto;
mod crypto;
pub mod onion;
pub mod util;
use crypto::secp::{random_secret, Commitment, SecretKey};
use onion::{new_stream_cipher, Onion, OnionError, Payload, RawBytes};
pub use crypto::{
comsig_serde, dalek::DalekPublicKey as MwixnetPublicKey, ComSigError, ComSignature,
};
use chacha20::cipher::StreamCipher;
use grin_core::core::FeeFields;
use secp256k1zkp::pedersen::RangeProof;
use grin_util::secp::{
pedersen::{Commitment, RangeProof},
SecretKey,
};
use x25519_dalek::PublicKey as xPublicKey;
use x25519_dalek::{SharedSecret, StaticSecret};
use crypto::secp::random_secret;
use onion::{new_stream_cipher, Onion, OnionError, Payload, RawBytes};
/// Onion hop struct
#[derive(Clone)]
pub struct Hop {
@@ -41,6 +48,7 @@ pub struct Hop {
}
/// Crate a new hop
#[cfg(test)]
pub fn new_hop(
server_key: &SecretKey,
hop_excess: &SecretKey,
@@ -56,7 +64,11 @@ pub fn new_hop(
}
/// Create an Onion for the Commitment, encrypting the payload for each hop
pub fn create_onion(commitment: &Commitment, hops: &Vec<Hop>) -> Result<Onion, OnionError> {
pub fn create_onion(
commitment: &Commitment,
hops: &Vec<Hop>,
use_test_rng: bool,
) -> Result<Onion, OnionError> {
if hops.is_empty() {
return Ok(Onion {
ephemeral_pubkey: xPublicKey::from([0u8; 32]),
@@ -67,14 +79,14 @@ pub fn create_onion(commitment: &Commitment, hops: &Vec<Hop>) -> Result<Onion, O
let mut shared_secrets: Vec<SharedSecret> = Vec::new();
let mut enc_payloads: Vec<RawBytes> = Vec::new();
let mut ephemeral_sk = StaticSecret::from(random_secret().0);
let mut ephemeral_sk = StaticSecret::from(random_secret(use_test_rng).0);
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);
shared_secrets.push(shared_secret);
ephemeral_sk = StaticSecret::from(random_secret().0);
ephemeral_sk = StaticSecret::from(random_secret(use_test_rng).0);
let next_ephemeral_pk = if i < (hops.len() - 1) {
xPublicKey::from(&ephemeral_sk)
} else {
@@ -106,16 +118,17 @@ pub fn create_onion(commitment: &Commitment, hops: &Vec<Hop>) -> Result<Onion, O
}
/// Internal tests
#[allow(missing_docs)]
#[allow(missing_docs, dead_code)]
#[cfg(test)]
pub mod test_util {
use super::*;
use crypto::dalek::DalekPublicKey;
use crypto::secp;
use grin_core::core::hash::Hash;
use grin_util::secp::Secp256k1;
use grin_util::ToHex;
use rand::{thread_rng, RngCore};
use secp256k1zkp::Secp256k1;
pub fn rand_onion() -> Onion {
let commit = rand_commit();
@@ -128,32 +141,32 @@ pub mod test_util {
None
};
let hop = new_hop(
&random_secret(),
&random_secret(),
&random_secret(false),
&random_secret(false),
thread_rng().next_u32(),
rangeproof,
);
hops.push(hop);
}
create_onion(&commit, &hops).unwrap()
create_onion(&commit, &hops, false).unwrap()
}
pub fn rand_commit() -> Commitment {
secp::commit(rand::thread_rng().next_u64(), &secp::random_secret()).unwrap()
secp::commit(rand::thread_rng().next_u64(), &secp::random_secret(false)).unwrap()
}
pub fn rand_hash() -> Hash {
Hash::from_hex(secp::random_secret().to_hex().as_str()).unwrap()
Hash::from_hex(secp::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(),
secp::random_secret(),
secp::random_secret(),
secp::random_secret(false),
secp::random_secret(false),
secp::random_secret(false),
None,
None,
)
@@ -177,8 +190,8 @@ pub mod test_util {
let rp = secp.bullet_proof(
out_value,
blind.clone(),
secp::random_secret(),
secp::random_secret(),
secp::random_secret(false),
secp::random_secret(false),
None,
None,
);
@@ -187,7 +200,7 @@ pub mod test_util {
}
pub fn rand_keypair() -> (SecretKey, DalekPublicKey) {
let sk = random_secret();
let sk = random_secret(false);
let pk = DalekPublicKey::from_secret(&sk);
(sk, pk)
}
+14 -7
View File
@@ -14,7 +14,6 @@
//! Onion defn for mwixnet
use super::crypto::secp::{self, Commitment, RangeProof, SecretKey};
use super::util::{read_optional, vec_to_array, write_optional};
use std::convert::TryFrom;
@@ -26,6 +25,11 @@ use chacha20::cipher::{NewCipher, StreamCipher};
use chacha20::{ChaCha20, Key, Nonce};
use grin_core::core::FeeFields;
use grin_core::ser::{self, Readable, Reader, Writeable, Writer};
use grin_util::secp::{
self as secp256k1zkp,
key::SecretKey,
pedersen::{Commitment, RangeProof},
};
use grin_util::{self, ToHex};
use hmac::digest::InvalidLength;
use hmac::{Hmac, Mac};
@@ -35,6 +39,8 @@ use sha2::Sha256;
use thiserror::Error;
use x25519_dalek::{PublicKey as xPublicKey, SharedSecret, StaticSecret};
use super::crypto::secp;
type HmacSha256 = Hmac<Sha256>;
/// Raw bytes alias
pub type RawBytes = Vec<u8>;
@@ -374,7 +380,7 @@ pub mod tests {
let fee_per_hop: u32 = 2;
let in_value: u64 = 1000;
let out_value: u64 = in_value - total_fee;
let blind = random_secret();
let blind = random_secret(false);
let commitment = secp::commit(in_value, &blind).unwrap();
let mut hops: Vec<Hop> = Vec::new();
@@ -382,15 +388,15 @@ pub mod tests {
let mut final_commit = secp::commit(out_value, &blind).unwrap();
let mut final_blind = blind.clone();
for i in 0..5 {
keys.push(random_secret());
keys.push(random_secret(false));
let excess = random_secret();
let excess = random_secret(false);
let secp = secp256k1zkp::Secp256k1::with_caps(secp256k1zkp::ContextFlag::Commit);
final_blind.add_assign(&secp, &excess).unwrap();
final_commit = secp::add_excess(&final_commit, &excess).unwrap();
let proof = if i == 4 {
let n1 = random_secret();
let n1 = random_secret(false);
let rp = secp.bullet_proof(
out_value,
final_blind.clone(),
@@ -409,11 +415,12 @@ pub mod tests {
hops.push(hop);
}
let mut onion_packet = crate::mwixnet::onion::create_onion(&commitment, &hops).unwrap();
let mut onion_packet =
crate::mwixnet::onion::create_onion(&commitment, &hops, false).unwrap();
let mut payload = Payload {
next_ephemeral_pk: onion_packet.ephemeral_pubkey.clone(),
excess: random_secret(),
excess: random_secret(false),
fee: FeeFields::from(fee_per_hop),
rangeproof: None,
};
+3 -3
View File
@@ -37,7 +37,7 @@ use std::convert::TryInto;
/// # Example
///
/// ```
/// use grin_wallet_libwallet::mwixnet::onion::util::write_optional;
/// use grin_wallet_libwallet::mwixnet::onion_util::write_optional;
/// let mut writer:Vec<u8> = vec![];
/// let optional_value: Option<u32> = Some(10);
/// //write_optional(&mut writer, &optional_value);
@@ -75,7 +75,7 @@ pub fn write_optional<O: Writeable, W: Writer>(
/// # Example
///
/// ```
/// use grin_wallet_libwallet::mwixnet::onion::util::read_optional;
/// use grin_wallet_libwallet::mwixnet::onion_util::read_optional;
/// use grin_core::ser::{BinReader, ProtocolVersion, DeserializationMode};
/// let mut buf: &[u8] = &[1, 0, 0, 0, 10];
/// let mut reader = BinReader::new(&mut buf, ProtocolVersion::local(), DeserializationMode::default());
@@ -106,7 +106,7 @@ pub fn read_optional<O: Readable, R: Reader>(reader: &mut R) -> Result<Option<O>
/// # Example
///
/// ```
/// use grin_wallet_libwallet::mwixnet::onion::util::vec_to_array;
/// use grin_wallet_libwallet::mwixnet::onion_util::vec_to_array;
/// let v = vec![0, 1, 2, 3, 4, 5];
/// let a = vec_to_array::<4>(&v).unwrap();
/// assert_eq!(a, [0, 1, 2, 3]);
+10 -9
View File
@@ -1,4 +1,4 @@
// Copyright 2022 The Grin Developers
// Copyright 2024 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.
@@ -15,28 +15,29 @@
//! Types related to mwixnet requests required by rest of lib crate apis
//! Should rexport all needed types here
pub use super::onion::crypto::comsig::{self, ComSignature};
pub use super::onion::crypto::secp::{add_excess, random_secret};
pub use super::onion::onion::Onion;
pub use super::onion::{new_hop, Hop};
use crate::grin_util::secp::key::SecretKey;
use super::onion::comsig_serde;
use grin_core::libtx::secp_ser::string_or_u64;
use grin_util::secp::key::SecretKey;
use serde::{Deserialize, Serialize};
pub use super::onion::{onion::Onion, ComSignature, Hop};
/// A Swap request
#[derive(Serialize, Deserialize, Debug)]
pub struct SwapReq {
/// Com signature
#[serde(with = "comsig::comsig_serde")]
#[serde(with = "comsig_serde")]
pub comsig: ComSignature,
/// Onion
pub onion: Onion,
}
/// mwixnetRequest Creation Params
#[derive(Serialize, Deserialize, Debug)]
pub struct MixnetReqCreationParams {
/// List of all the server keys
pub server_keys: Vec<SecretKey>,
/// Fees per hop
pub fee_per_hop: u32,
#[serde(with = "string_or_u64")]
pub fee_per_hop: u64,
}
+5 -5
View File
@@ -188,11 +188,11 @@ fn format_slatepack(slatepack: &str) -> Result<String, Error> {
// Returns the first four bytes of a double sha256 hash of some bytes
fn generate_check(payload: &[u8]) -> Result<Vec<u8>, Error> {
let mut first_hash = Sha256::new();
first_hash.update(payload);
let mut second_hash = Sha256::new();
second_hash.update(first_hash.finalize());
let checksum = second_hash.finalize();
let mut first_hasher = Sha256::new();
first_hasher.update(payload);
let mut second_hasher = Sha256::new();
second_hasher.update(first_hasher.finalize());
let checksum = second_hasher.finalize();
let check_bytes: Vec<u8> = checksum[0..4].to_vec();
Ok(check_bytes)
}
+3 -3
View File
@@ -1,6 +1,6 @@
[package]
name = "grin_wallet_util"
version = "5.4.0-contracts.0"
version = "5.4.0-alpha.1"
authors = ["Grin Developers <mimblewimble@lists.launchpad.net>"]
description = "Util, for generic utilities and to re-export grin crates"
license = "Apache-2.0"
@@ -21,14 +21,14 @@ thiserror = "1"
##### Grin Imports
# For Release
# grin_util = "5.4.0-contracts.0"
grin_util = "5.3.3"
# For beta release
# grin_util = { git = "https://github.com/mimblewimble/grin", tag = "v5.2.0-beta.3" }
# For bleeding edge
grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# grin_util = { git = "https://github.com/mimblewimble/grin", branch = "master" }
# For local testing