From cf488920db93e279ab92eb81bc3ffc1e1fe4030a Mon Sep 17 00:00:00 2001 From: wiesche Date: Mon, 14 Sep 2026 07:42:44 +0200 Subject: [PATCH] clean up wallet code --- controller/src/command.rs | 30 +++++----------- libwallet/src/api_impl/owner.rs | 4 +-- libwallet/src/backend.rs | 2 +- libwallet/src/contract/actions/view.rs | 5 ++- libwallet/src/contract/context.rs | 7 ++-- libwallet/src/contract/slate.rs | 2 +- libwallet/src/contract/utils.rs | 2 +- libwallet/src/internal/tx.rs | 6 ++-- libwallet/src/payment_proof.rs | 10 +++--- libwallet/src/slate.rs | 34 +++++++------------ libwallet/src/slate_versions/common.rs | 2 +- libwallet/src/slate_versions/ser.rs | 16 ++++----- libwallet/src/slate_versions/v5_bin.rs | 6 ++-- src/cmd/wallet_args.rs | 47 +++++++++++++------------- 14 files changed, 74 insertions(+), 99 deletions(-) diff --git a/controller/src/command.rs b/controller/src/command.rs index bf8a7e6..3194d4b 100644 --- a/controller/src/command.rs +++ b/controller/src/command.rs @@ -596,7 +596,7 @@ where )?; if lock { - owner_api.tx_lock_outputs(keychain_mask, &slate)?; + owner_api.tx_lock_outputs(keychain_mask, slate)?; } println!("{}", out_file_name); @@ -702,7 +702,7 @@ where // For now, we don't compact slates with sl.compact(). We first make them work without compaction. // Writing the file, serializing and encrypting can all fail for ordinary reasons, so // report them through the normal CLI error path rather than unwrapping. - let slate_out = prepare_slatepack(api, keychain_mask, &slate, counterparty_addr, out_file)?; + let slate_out = prepare_slatepack(api, keychain_mask, slate, counterparty_addr, out_file)?; slate_out.print(as_json); Ok(()) } @@ -734,9 +734,9 @@ where let slate_out = SlatepackOut { is_encrypted: dest.is_some(), - is_finalized: is_finalized, + is_finalized, out_file: out_file_name, - message: message, + message, }; Ok(slate_out) @@ -767,7 +767,7 @@ where Some(message) => packer.deser_slatepack(message.trim_start().as_bytes(), false)?, None => { let msg = "No slate provided via file or direct input"; - return Err(Error::GenericError(msg.into()).into()); + return Err(Error::GenericError(msg.into())); } }, }; @@ -1757,21 +1757,14 @@ impl ContractNewArgs { ttl_blocks: self.ttl_blocks, setup_args: ContractSetupArgsAPI { fee_rate: self.fee_rate, - src_acct_name: match self.src_acct_name.as_ref() { - Some(v) => Some(v.to_string()), - None => None, - }, + src_acct_name: self.src_acct_name.clone(), net_change: Some(net_change), num_participants: self.num_participants, add_outputs: self.add_outputs, selection_args: OutputSelectionArgs { minimum_confirmations: Some(self.minimum_confirmations), - use_inputs: match self.use_inputs.as_ref() { - Some(v) => Some(v.to_string()), - None => None, - }, + use_inputs: self.use_inputs.clone(), make_outputs: self.make_outputs.clone(), - ..Default::default() }, proof_args: contract_proof_args( self.proof_type, @@ -1779,7 +1772,6 @@ impl ContractNewArgs { self.receive.unwrap_or(0) > 0, )?, }, - ..Default::default() }) } } @@ -1850,15 +1842,11 @@ impl ContractSetupArgs { }; Ok(ContractSetupArgsAPI { fee_rate: self.fee_rate, - net_change: net_change, + net_change, selection_args: OutputSelectionArgs { minimum_confirmations: self.minimum_confirmations, - use_inputs: match self.use_inputs.as_ref() { - Some(v) => Some(v.to_string()), - None => None, - }, + use_inputs: self.use_inputs.clone(), make_outputs: self.make_outputs.clone(), - ..Default::default() }, proof_args: contract_proof_args( self.proof_type, diff --git a/libwallet/src/api_impl/owner.rs b/libwallet/src/api_impl/owner.rs index b01a02a..c38b2c1 100644 --- a/libwallet/src/api_impl/owner.rs +++ b/libwallet/src/api_impl/owner.rs @@ -1602,7 +1602,7 @@ where C: NodeClient, K: Keychain, { - contract::sign(&mut *w, keychain_mask, slate, &args) + contract::sign(&mut *w, keychain_mask, slate, args) } /// Revoke transaction contract @@ -1615,7 +1615,7 @@ where C: NodeClient, K: Keychain, { - contract::revoke(&mut *w, keychain_mask, &args) + contract::revoke(&mut *w, keychain_mask, args) } /// Create MXMixnet request diff --git a/libwallet/src/backend.rs b/libwallet/src/backend.rs index 3e8cbda..be27342 100644 --- a/libwallet/src/backend.rs +++ b/libwallet/src/backend.rs @@ -618,7 +618,7 @@ where Ok(self .db .get_ser(Some(DERIV_PREFIX), &parent_id.to_bytes(), None)? - .unwrap_or_else(|| 0)) + .unwrap_or(0)) } /// Save last stored child index of a given parent. diff --git a/libwallet/src/contract/actions/view.rs b/libwallet/src/contract/actions/view.rs index b0f32a8..fd28c64 100644 --- a/libwallet/src/contract/actions/view.rs +++ b/libwallet/src/contract/actions/view.rs @@ -135,14 +135,13 @@ where let ct_view = ContractView { num_participants: slate.num_participants, - suggested_net_change: suggested_net_change, + suggested_net_change, agreed_net_change, own_fee, balance_change, num_sigs: num_sigs as u8, - is_executed: is_executed, + is_executed, own_commitment_status, - ..Default::default() }; Ok(ct_view) } diff --git a/libwallet/src/contract/context.rs b/libwallet/src/contract/context.rs index bf83930..89d3df3 100644 --- a/libwallet/src/contract/context.rs +++ b/libwallet/src/contract/context.rs @@ -87,8 +87,7 @@ where // Fee contribution estimation let net_change = setup_args.required_net_change()?; // select inputs to estimate fee cost - let (inputs, _, my_fee) = - prepare_outputs(w, &parent_key_id, current_height, &setup_args, None)?; + let (inputs, _, my_fee) = prepare_outputs(w, parent_key_id, current_height, setup_args, None)?; // The number of outputs we expect is the number of custom outputs plus one change output debug!( "My fee contribution estimation: {} for n_inputs: {}, n_outputs: {}, n_kernels: {}, num_participants: {}", @@ -110,7 +109,7 @@ where // Create a Context for this slate let keychain = w.keychain(keychain_mask)?; // is_initiator only affects the deterministic test RNG; contracts always pass true. - let mut context = Context::new(keychain.secp(), &parent_key_id, use_test_rng, true); + let mut context = Context::new(keychain.secp(), parent_key_id, use_test_rng, true); // Context.fee will hold _our_ fee contribution and not the total slate fee context.fee = my_fee.as_opt(); // Context.amount is not used in contracts, but we set it anyway. @@ -160,7 +159,7 @@ where &mut *w, parent_key_id, current_height, - &setup_args, + setup_args, context.fee, )?; // An old or damaged context, or a future change to the fee schedule, can reach this diff --git a/libwallet/src/contract/slate.rs b/libwallet/src/contract/slate.rs index f9d047b..f3209b8 100644 --- a/libwallet/src/contract/slate.rs +++ b/libwallet/src/contract/slate.rs @@ -113,7 +113,7 @@ where add_outputs_to_slate(w, keychain_mask, slate, context)?; // Adjust the offset for the added input and outputs let keychain = &w.keychain(keychain_mask)?; - slate.adjust_offset(keychain, &context)?; + slate.adjust_offset(keychain, context)?; Ok(()) } diff --git a/libwallet/src/contract/utils.rs b/libwallet/src/contract/utils.rs index 4c7d1ba..9d7e505 100644 --- a/libwallet/src/contract/utils.rs +++ b/libwallet/src/contract/utils.rs @@ -254,7 +254,7 @@ where key_id: key_id.clone(), mmr_index: None, n_child: key_id.to_path().last_path_index(), - commit: commit, + commit, value: amount, status: OutputStatus::Unconfirmed, height: current_height, diff --git a/libwallet/src/internal/tx.rs b/libwallet/src/internal/tx.rs index dcebdbb..ca06c76 100644 --- a/libwallet/src/internal/tx.rs +++ b/libwallet/src/internal/tx.rs @@ -361,7 +361,7 @@ where Some(&parent_key_id), false, )?; - if tx_vec.len() == 0 { + if tx_vec.is_empty() { return Err(Error::TransactionDoesntExist(tx_id_string)); } // Collect the entries and their outputs first: the batch that cancels them borrows the @@ -385,7 +385,7 @@ where keychain_mask, false, Some(tx.id), - Some(&parent_key_id), + Some(parent_key_id), )?; let outputs = res.iter().map(|m| m.output.clone()).collect(); to_cancel.push((tx, outputs)); @@ -431,7 +431,7 @@ where if let Some(ref p) = slate.clone().payment_proof { if let Some(saddr) = p.sender_address { - let derivation_index = context.payment_proof_derivation_index.unwrap_or_else(|| 0); + let derivation_index = context.payment_proof_derivation_index.unwrap_or(0); let keychain = wallet.keychain(keychain_mask)?; let parent_key_id = wallet.parent_key_id(); let excess = slate.calc_excess(keychain.secp())?; diff --git a/libwallet/src/payment_proof.rs b/libwallet/src/payment_proof.rs index 1fb75dc..61ee61a 100644 --- a/libwallet/src/payment_proof.rs +++ b/libwallet/src/payment_proof.rs @@ -161,7 +161,7 @@ impl Writeable for PromiseBin<'_> { writer.write_u8(self.0.proof_type.as_u8())?; match self.0.proof_type { PaymentProofType::Invoice => write_amount(writer, self.0.amount)?, - PaymentProofType::SenderNonce => writer.write_fixed_bytes(&[0; 7])?, + PaymentProofType::SenderNonce => writer.write_fixed_bytes([0; 7])?, PaymentProofType::Legacy => { return Err(grin_ser::Error::CorruptedData); } @@ -261,7 +261,7 @@ impl EarlyPaymentProof { .ok_or_else(|| Error::PaymentProof("Missing proof timestamp".to_string()))? .timestamp(), p.memo.clone(), - p.promise_signature.clone(), + p.promise_signature, ), None => (PaymentProofType::Invoice, 0, None, None), }; @@ -292,7 +292,7 @@ impl EarlyPaymentProof { )); } if let Some(base_public) = base_public_nonce.as_ref() { - let mut expected = base_public.clone(); + let mut expected = *base_public; expected.add_exp_assign(secp, &sender_nonce_tweak(secp, base_public, self)?)?; if PublicKey::from_secret_key(secp, secret_nonce)? != expected { return Err(Error::PaymentProofValidation( @@ -377,7 +377,7 @@ impl EarlyPaymentProof { let sender_nonce = wd.sender_public_nonce.as_ref().ok_or_else(|| { Error::PaymentProofValidation("Missing sender nonce witness".into()) })?; - let mut expected_sender_nonce = sender_nonce.clone(); + let mut expected_sender_nonce = *sender_nonce; expected_sender_nonce.add_exp_assign( &static_secp, &sender_nonce_tweak(&static_secp, sender_nonce, self)?, @@ -419,7 +419,7 @@ impl EarlyPaymentProof { &pub_nonce_sum, &self.receiver_public_excess, &pub_blind_sum, - &msg, + msg, ) .is_ok() }) { diff --git a/libwallet/src/slate.rs b/libwallet/src/slate.rs index 9cd2715..71bbe0e 100644 --- a/libwallet/src/slate.rs +++ b/libwallet/src/slate.rs @@ -443,7 +443,7 @@ impl Slate { VersionedSlate::V4(s) => s.into(), VersionedSlate::V5(s) => s.into(), }; - Ok(internal.into()) + Ok(internal) } /// Compact the slate for initial sending, storing the excess + offset explicit /// and removing my input/output data @@ -656,7 +656,7 @@ impl Slate { return Ok(i); } } - return Err(Error::ContextToIndex); + Err(Error::ContextToIndex) } /// Completes caller's part of round 2, completing signatures pub fn fill_round_2( @@ -1003,17 +1003,13 @@ impl From<&Slate> for SlateV5 { let feat = *kernel_features; let ttl = *ttl; let off = offset.clone(); - let participant_data = map_vec!(participant_data, |data| ParticipantDataV5::from(data)); + let participant_data = map_vec!(participant_data, ParticipantDataV5::from); let ver = VersionCompatInfoV5::from(version_info); - let payment_proof = match payment_proof { - Some(p) => Some(PaymentInfoV5::from(p)), - None => None, - }; + let payment_proof = payment_proof.as_ref().map(PaymentInfoV5::from); let sta = SlateStateV5::from(state); - let feat_args = match kernel_features_args { - Some(a) => Some(KernelFeaturesArgsV5::from(a)), - None => None, - }; + let feat_args = kernel_features_args + .as_ref() + .map(KernelFeaturesArgsV5::from); SlateV5 { num_parts, id, @@ -1070,7 +1066,7 @@ impl From<&PaymentInfo> for PaymentInfoV5 { raddr: receiver_address, psig: promise_signature, ts: timestamp, - memo: memo, + memo, } } } @@ -1094,16 +1090,10 @@ impl From for Slate { proof: payment_proof, feat_args, } = slate; - let participant_data = map_vec!(participant_data, |data| ParticipantData::from(data)); + let participant_data = map_vec!(participant_data, ParticipantData::from); let version_info = VersionCompatInfo::from(&ver); - let payment_proof = match &payment_proof { - Some(p) => Some(PaymentInfo::from(p)), - None => None, - }; - let kernel_features_args = match &feat_args { - Some(a) => Some(KernelFeaturesArgs::from(a)), - None => None, - }; + let payment_proof = payment_proof.as_ref().map(PaymentInfo::from); + let kernel_features_args = feat_args.as_ref().map(KernelFeaturesArgs::from); let state = SlateState::from(&sta); Slate { num_participants, @@ -1232,7 +1222,7 @@ impl From<&PaymentInfoV5> for PaymentInfo { proof_type, sender_address, receiver_address, - promise_signature: promise_signature, + promise_signature, timestamp, memo, } diff --git a/libwallet/src/slate_versions/common.rs b/libwallet/src/slate_versions/common.rs index 0d3e870..4d918bf 100644 --- a/libwallet/src/slate_versions/common.rs +++ b/libwallet/src/slate_versions/common.rs @@ -38,7 +38,7 @@ pub enum SlateState { Invoice1, /// Invoice flow, return journey Invoice2, - /// Invoice flow, ready for tranasction posting + /// Invoice flow, ready for transaction posting Invoice3, } diff --git a/libwallet/src/slate_versions/ser.rs b/libwallet/src/slate_versions/ser.rs index 75d4e63..2dc8825 100644 --- a/libwallet/src/slate_versions/ser.rs +++ b/libwallet/src/slate_versions/ser.rs @@ -266,7 +266,7 @@ pub mod option_pubkey_serde { use serde::de::Error; use serde::{Deserialize, Deserializer, Serializer}; - /// + /// Serialize an optional public key as compressed hex pub fn serialize(key: &Option, serializer: S) -> Result where S: Serializer, @@ -281,7 +281,7 @@ pub mod option_pubkey_serde { } } - /// + /// Read an optional public key from hex pub fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, @@ -566,7 +566,7 @@ pub mod version_info_v4 { if v.len() != 2 { return Err(Error::custom("Cannot parse version")); } - match u16::from_str_radix(v[0], 10) { + match v[0].parse::() { // VersionedSlate is untagged, so the declared version must be checked here: // otherwise a slate is silently parsed as the wrong variant. Ok(4) => retval.version = 4, @@ -578,7 +578,7 @@ pub mod version_info_v4 { } Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } - match u16::from_str_radix(v[1], 10) { + match v[1].parse::() { Ok(u) => retval.block_header_version = u, Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } @@ -594,7 +594,7 @@ pub mod version_info_v5 { use crate::slate_versions::v5::VersionCompatInfoV5; - /// + /// Write the slate and block header versions separated by a colon pub fn serialize(v: &VersionCompatInfoV5, serializer: S) -> Result where S: Serializer, @@ -602,7 +602,7 @@ pub mod version_info_v5 { serializer.serialize_str(&format!("{}:{}", v.version, v.block_header_version)) } - /// + /// Read the versions and require a V5 slate pub fn deserialize<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, @@ -616,7 +616,7 @@ pub mod version_info_v5 { if v.len() != 2 { return Err(Error::custom("Cannot parse version")); } - match u16::from_str_radix(v[0], 10) { + match v[0].parse::() { // See the V4 deserializer: the declared version disambiguates the // untagged VersionedSlate variants. Ok(5) => retval.version = 5, @@ -628,7 +628,7 @@ pub mod version_info_v5 { } Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } - match u16::from_str_radix(v[1], 10) { + match v[1].parse::() { Ok(u) => retval.block_header_version = u, Err(e) => return Err(Error::custom(format!("Cannot parse version: {}", e))), } diff --git a/libwallet/src/slate_versions/v5_bin.rs b/libwallet/src/slate_versions/v5_bin.rs index 3a67282..7663cfe 100644 --- a/libwallet/src/slate_versions/v5_bin.rs +++ b/libwallet/src/slate_versions/v5_bin.rs @@ -61,10 +61,10 @@ impl<'a> Writeable for SlateOptStructsRef<'a> { }; writer.write_u8(status)?; if let Some(c) = self.coms { - ComsWrapRef(&c).write(writer)?; + ComsWrapRef(c).write(writer)?; } if let Some(p) = self.proof { - ProofWrapRef(&p).write(writer)?; + ProofWrapRef(p).write(writer)?; } Ok(()) } @@ -111,7 +111,7 @@ impl<'a> Writeable for ProofWrapRef<'a> { match self.0.psig { Some(s) => { writer.write_u8(1)?; - writer.write_fixed_bytes(&s.to_bytes().to_vec())?; + writer.write_fixed_bytes(s.to_bytes())?; } None => writer.write_u8(0)?, } diff --git a/src/cmd/wallet_args.rs b/src/cmd/wallet_args.rs index 8d596e4..fe52627 100644 --- a/src/cmd/wallet_args.rs +++ b/src/cmd/wallet_args.rs @@ -1142,15 +1142,15 @@ pub fn parse_contract_new_args( }; Ok(command::ContractNewArgs { - counterparty_addr: counterparty_addr, - receive: receive, - send: send, - src_acct_name: src_acct_name, - num_participants: num_participants, - as_json: as_json, - add_outputs: add_outputs, - use_inputs: use_inputs, - make_outputs: make_outputs, + counterparty_addr, + receive, + send, + src_acct_name, + num_participants, + as_json, + add_outputs, + use_inputs, + make_outputs, minimum_confirmations, fee_rate, ttl_blocks, @@ -1163,10 +1163,7 @@ pub fn parse_contract_new_args( pub fn parse_contract_setup_args( args: &ArgMatches, ) -> Result { - let counterparty_addr = match args.value_of("encrypt-for") { - Some(v) => Some(String::from(v)), - None => None, - }; + let counterparty_addr = args.value_of("encrypt-for").map(String::from); let (receive, send) = parse_contract_amounts(args)?; let as_json = args.is_present("as-json"); let minimum_confirmations = match args.value_of("minimum_confirmations") { @@ -1179,12 +1176,12 @@ pub fn parse_contract_setup_args( let (use_inputs, make_outputs) = parse_contract_selection(args)?; Ok(command::ContractSetupArgs { - counterparty_addr: counterparty_addr, - receive: receive, - send: send, - as_json: as_json, - use_inputs: use_inputs, - make_outputs: make_outputs, + counterparty_addr, + receive, + send, + as_json, + use_inputs, + make_outputs, minimum_confirmations, fee_rate, outfile, @@ -1575,24 +1572,26 @@ where ("contract", Some(args)) => match args.subcommand() { ("new", Some(new_args)) => { let account = &global_wallet_args.account; - let a = arg_parse!(parse_contract_new_args(&new_args, account)); + let a = arg_parse!(parse_contract_new_args(new_args, account)); command::contract_new(owner_api, km, a) } ("sign", Some(sign_args)) => { // Sign command takes setup_args so we use the same parser - let setup_args = arg_parse!(parse_contract_setup_args(&sign_args)); + let setup_args = arg_parse!(parse_contract_setup_args(sign_args)); let broadcast_tx = !sign_args.is_present("no-broadcast"); command::contract_sign(owner_api, km, setup_args, broadcast_tx) } ("view", Some(view_args)) => { - let a = arg_parse!(parse_contract_view_args(&view_args)); + let a = arg_parse!(parse_contract_view_args(view_args)); command::contract_view(owner_api, km, a) } ("revoke", Some(revoke_args)) => { - let a = arg_parse!(parse_contract_revoke_args(&revoke_args)); + let a = arg_parse!(parse_contract_revoke_args(revoke_args)); command::contract_revoke(owner_api, km, a) } - _ => Err(Error::ArgumentError(String::from("Unknown contract subcommand.")).into()), + _ => Err(Error::ArgumentError(String::from( + "Unknown contract subcommand.", + ))), }, _ => { let msg = "Unknown wallet command, use 'grin-wallet help' for details".to_string();