Skip to content

Commit

Permalink
implementation of comsig given an output commit
Browse files Browse the repository at this point in the history
  • Loading branch information
yeastplume committed Sep 2, 2024
1 parent d5c64d5 commit fc33d9b
Show file tree
Hide file tree
Showing 11 changed files with 85 additions and 61 deletions.
5 changes: 3 additions & 2 deletions api/src/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ use crate::libwallet::{
};
use crate::util::logger::LoggingConfig;
use crate::util::secp::key::SecretKey;
use crate::util::secp::pedersen;
use crate::util::{from_hex, static_secp_instance, Mutex, ZeroingString};
use grin_wallet_util::OnionV3Address;
use std::convert::TryFrom;
Expand Down Expand Up @@ -835,12 +836,12 @@ where
&self,
keychain_mask: Option<&SecretKey>,
params: &MixnetReqCreationParams,
slate: &Slate,
commitment: &pedersen::Commitment,
// 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, slate)
owner::create_mwixnet_req(&mut **w, keychain_mask, params, commitment)
}

/// Processes an invoice tranaction created by another party, essentially
Expand Down
1 change: 0 additions & 1 deletion controller/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1671,7 +1671,6 @@ impl ContractNewArgs {
net_change: Some(net_change),
num_participants: self.num_participants,
add_outputs: self.add_outputs,
delete_context_on_final_sign: true,
selection_args: OutputSelectionArgs {
use_inputs: match self.use_inputs.as_ref() {
Some(v) => Some(v.to_string()),
Expand Down
20 changes: 18 additions & 2 deletions controller/tests/contract_srs_mwmixnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet:
// Send wallet finalizes and posts
wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| {
let args = &mut ContractSetupArgsAPI {
delete_context_on_final_sign: false,
..Default::default()
};
args.proof_args.suppress_proof = true;
Expand All @@ -84,6 +83,17 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet:
assert_eq!(slate.state, SlateState::Standard3);

wallet::controller::owner_single_use(Some(send_wallet.clone()), send_mask, None, |api, m| {
api.post_tx(m, &slate, false)?;
Ok(())
})?;
bh += 1;

let _ =
test_framework::award_blocks_to_wallet(&chain, send_wallet.clone(), send_mask, 3, false);
bh += 3;

// Recipient wallet sends outputs to mwixnet
wallet::controller::owner_single_use(Some(recv_wallet.clone()), recv_mask, None, |api, m| {
let secp_locked = static_secp_instance();
let secp = secp_locked.lock();
let server_pubkey_str_1 =
Expand All @@ -105,7 +115,13 @@ fn contract_srs_mwixnet_tx_impl(test_dir: &'static str) -> Result<(), libwallet:
server_keys: vec![server_key_1, server_key_2, server_key_3],
fee_per_hop: 50_000_000,
};
api.create_mwixnet_req(send_mask, &params, &slate)?;
let outputs = api.retrieve_outputs(recv_mask, 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)?;

println!("MWIXNET REQ: {:?}", mwixnet_req);
Ok(())
})?;

Expand Down
97 changes: 61 additions & 36 deletions libwallet/src/api_impl/owner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ use uuid::Uuid;
use crate::api_impl::foreign::finalize_tx as foreign_finalize;
use crate::contract::proofs::{InvoiceProof, ProofWitness};
use crate::grin_core::core::hash::Hashed;
use crate::grin_core::core::{Output, OutputFeatures, Transaction};
use crate::grin_core::core::{FeeFields, Output, OutputFeatures, Transaction};
use crate::grin_core::libtx::proof;
use crate::grin_keychain::ViewKey;
use crate::grin_util::secp::key::SecretKey;
Expand Down Expand Up @@ -49,6 +49,7 @@ use chrono::prelude::{DateTime, NaiveDateTime, Utc};
use ed25519_dalek::PublicKey as DalekPublicKey;
use ed25519_dalek::SecretKey as DalekSecretKey;
use ed25519_dalek::Verifier;
use x25519_dalek::{PublicKey as xPublicKey, StaticSecret};

use std::convert::{TryFrom, TryInto};
use std::sync::mpsc::Sender;
Expand Down Expand Up @@ -1608,54 +1609,78 @@ pub fn create_mwixnet_req<'a, T: ?Sized, C, K>(
w: &mut T,
keychain_mask: Option<&SecretKey>,
params: &MixnetReqCreationParams,
slate: &Slate,
// use_test_rng: bool,
commitment: &pedersen::Commitment,
) -> Result<SwapReq, Error>
where
T: WalletBackend<'a, C, K>,
C: NodeClient + 'a,
K: Keychain + 'a,
{
let context = w.get_private_context(keychain_mask, slate.id.as_bytes())?;

let my_keys = context.get_private_keys();
let kernel = slate.tx_or_err()?.kernels()[0];
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 msg = kernel.msg_to_sign()?;
let mut output = None;
for o in &outputs {
if o.commit == *commitment {
output = Some(o.output.clone());
break;
}
}

let comsig = ComSignature::sign(slate.amount, &my_keys.0, &msg.to_hex().as_bytes().to_vec())?;
if output.is_none() {
return Err(Error::GenericError(String::from("output not found")));
}

let mut hops: Vec<Hop> = Vec::new();
let mut final_commit = kernel.excess.clone();
let mut final_blind = my_keys.0.clone();
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() {
let excess = params.server_keys[i].clone();

let secp = secp256k1zkp::Secp256k1::with_caps(secp256k1zkp::ContextFlag::Commit);
final_blind.add_assign(&secp, &excess).unwrap();
final_commit = add_excess(&final_commit, &excess).unwrap();
let proof = if i == params.server_keys.len() - 1 {
let n1 = random_secret();
let rp = secp.bullet_proof(
slate.amount - (params.fee_per_hop * params.server_keys.len() as u32) as u64,
final_blind.clone(),
n1.clone(),
n1.clone(),
None,
None,
);
assert!(secp.verify_bullet_proof(final_commit, rp, None).is_ok());
Some(rp)
} else {
None
};

let hop = new_hop(&params.server_keys[i], &excess, params.fee_per_hop, proof);
hops.push(hop);
server_pubkeys.push(xPublicKey::from(&StaticSecret::from(
params.server_keys[i].0,
)));
}

let onion = create_onion(&kernel.excess, &hops)?;
let fee = grin_core::libtx::tx_fee(1, 1, 1);
let new_amount = amount - (fee * server_pubkeys.len() as u64);
let new_output = build_output(w, keychain_mask, OutputFeatures::Plain, new_amount)?;
let secp = keychain.secp();

let mut blind_sum = new_output
.blind
.split(&BlindingFactor::from_secret_key(input_blind.clone()), &secp)?;

let hops = server_pubkeys
.iter()
.enumerate()
.map(|(i, &p)| {
if (i + 1) == server_pubkeys.len() {
Hop {
server_pubkey: p.clone(),
excess: blind_sum.secret_key(&secp).unwrap(),
fee: FeeFields::from(fee as u32),
rangeproof: Some(new_output.output.proof.clone()),
}
} else {
let hop_excess = BlindingFactor::rand(&secp);
blind_sum = blind_sum.split(&hop_excess, &secp).unwrap();
Hop {
server_pubkey: p.clone(),
excess: hop_excess.secret_key(&secp).unwrap(),
fee: FeeFields::from(fee as u32),
rangeproof: None,
}
}
})
.collect();

let onion = create_onion(&commitment, &hops).unwrap();
let comsig = ComSignature::sign(amount, &input_blind, &onion.serialize().unwrap()).unwrap();

Ok(SwapReq { comsig, onion })

Expand Down
1 change: 0 additions & 1 deletion libwallet/src/contract/actions/new.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ where
&mut context,
setup_args.add_outputs,
false,
setup_args.delete_context_on_final_sign,
)?;

Ok(slate)
Expand Down
2 changes: 0 additions & 2 deletions libwallet/src/contract/actions/revoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,6 @@ where
net_change: Some(0), // self-spend
num_participants: 1,
add_outputs: false,
delete_context_on_final_sign: true,
selection_args: OutputSelectionArgs {
use_inputs: Some(String::from(input_commit)),
..Default::default()
Expand All @@ -91,7 +90,6 @@ where
net_change: None, // we already have it in the context as 0 now
num_participants: 1,
add_outputs: false,
delete_context_on_final_sign: true,
selection_args: OutputSelectionArgs {
use_inputs: Some(String::from(input_commit)),
..Default::default()
Expand Down
1 change: 0 additions & 1 deletion libwallet/src/contract/actions/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ where
&mut context,
setup_args.add_outputs,
false,
setup_args.delete_context_on_final_sign,
)?;

Ok(slate)
Expand Down
10 changes: 1 addition & 9 deletions libwallet/src/contract/actions/sign.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,15 +44,7 @@ where
let (sl, mut context) = compute(w, keychain_mask, slate, setup_args)?;

// Atomically commit state
contract::utils::save_step(
w,
keychain_mask,
&sl,
&mut context,
will_add_outputs,
true,
setup_args.delete_context_on_final_sign,
)?;
contract::utils::save_step(w, keychain_mask, &sl, &mut context, will_add_outputs, true)?;

Ok(sl)
}
Expand Down
4 changes: 0 additions & 4 deletions libwallet/src/contract/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,6 @@ pub struct ContractSetupArgsAPI {
pub add_outputs: bool,
/// Output selection arguments
pub selection_args: OutputSelectionArgs,
/// If false, don't delete context when finalizing (to facilitate mwixnet transactions)
pub delete_context_on_final_sign: bool,
/// Proof arguments
pub proof_args: ProofArgs,
}
Expand All @@ -150,7 +148,6 @@ impl Default for ContractSetupArgsAPI {
net_change: None,
num_participants: 2,
add_outputs: false,
delete_context_on_final_sign: true,
selection_args: OutputSelectionArgs {
..Default::default()
},
Expand Down Expand Up @@ -180,7 +177,6 @@ impl Default for ContractNewArgsAPI {
net_change: None,
num_participants: 2,
add_outputs: false,
delete_context_on_final_sign: true,
selection_args: OutputSelectionArgs {
..Default::default()
},
Expand Down
3 changes: 1 addition & 2 deletions libwallet/src/contract/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,6 @@ pub fn save_step<'a, T: ?Sized, C, K>(
context: &mut Context,
step_added_outputs: bool,
is_signed: bool,
delete_on_final: bool,
) -> Result<(), Error>
where
T: WalletBackend<'a, C, K>,
Expand Down Expand Up @@ -278,7 +277,7 @@ where
}

// Update context
if is_signed && !is_step2 && delete_on_final {
if is_signed && !is_step2 {
// NOTE: We MUST forget the context when we sign. Ideally, these two would be atomic or perhaps
// when we call slate::sigadd_partial_signaturen we could swap the secret key with a temporary one just to be safe.
// The reason we don't delete if we are at step2 is because in case we want to do safe cancel,
Expand Down
2 changes: 1 addition & 1 deletion libwallet/src/mwixnet/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use crate::grin_util::secp::key::SecretKey;
use serde::{Deserialize, Serialize};

/// A Swap request
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug)]
pub struct SwapReq {
/// Com signature
#[serde(with = "comsig::comsig_serde")]
Expand Down

0 comments on commit fc33d9b

Please sign in to comment.