Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/backend_task/core/refresh_wallet_info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl AppContext {
// Step 2: Iterate over each address and update balances
for address in &addresses {
// Fetch balance for the address from Dash Core
match self.core_client.get_received_by_address(address, Some(0)) {
match self.core_client.get_received_by_address(address, None) {
Ok(new_balance) => {
// Update the wallet's address_balances and database
{
Expand Down
3 changes: 3 additions & 0 deletions src/backend_task/identity/register_identity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@ impl AppContext {
match wallet.asset_lock_transaction(
sdk.network,
amount,
true,
identity_index,
Some(self),
) {
Expand All @@ -188,6 +189,7 @@ impl AppContext {
wallet.asset_lock_transaction(
sdk.network,
amount,
true,
identity_index,
Some(self),
)?
Expand Down Expand Up @@ -409,6 +411,7 @@ impl AppContext {
wallet
.unused_asset_locks
.retain(|(tx, _, _, _, _)| tx.txid() != tx_id);
wallet.identities.insert(wallet_identity_index, identity);
}

self.db
Expand Down
8 changes: 6 additions & 2 deletions src/cpu_compatibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@ pub fn check_cpu_compatibility() {
MessageDialog::new()
.set_type(native_dialog::MessageType::Error)
.set_title("Compatibility Error")
.set_text("Your CPU does not support AVX instructions. Please use a compatible CPU.")
.set_text(
"Your CPU does not support AVX instructions. Please use a compatible CPU.",
)
.show_alert()
.unwrap();
std::process::exit(1);
Expand All @@ -25,7 +27,9 @@ pub fn check_cpu_compatibility() {
MessageDialog::new()
.set_type(native_dialog::MessageType::Error)
.set_title("Compatibility Error")
.set_text("Your CPU does not support AVX2 instructions. Please use a compatible CPU.")
.set_text(
"Your CPU does not support AVX2 instructions. Please use a compatible CPU.",
)
.show_alert()
.unwrap();
std::process::exit(1);
Expand Down
64 changes: 42 additions & 22 deletions src/model/wallet/asset_lock_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@ impl Wallet {
&mut self,
network: Network,
amount: u64,
allow_take_fee_from_amount: bool,
identity_index: u32,
register_addresses: Option<&AppContext>,
) -> Result<
(
Transaction,
PrivateKey,
Address,
Option<Address>,
BTreeMap<OutPoint, (TxOut, Address)>,
),
String,
Expand All @@ -37,53 +38,72 @@ impl Wallet {

let one_time_key_hash = asset_lock_public_key.pubkey_hash();
let fee = 3_000;
let (utxos, change) = self
.take_unspent_utxos_for(amount + fee)

let (utxos, change_option) = self
.take_unspent_utxos_for(amount, fee, allow_take_fee_from_amount)
.ok_or("take_unspent_utxos_for() returned None".to_string())?;

let change_address = self.change_address(network, register_addresses)?;
let actual_amount = if change_option.is_none() && allow_take_fee_from_amount {
// The amount has been adjusted by taking the fee from the amount
// Calculate the adjusted amount based on the total value of the UTXOs minus the fee
let total_input_value: u64 = utxos.iter().map(|(_, (tx_out, _))| tx_out.value).sum();
total_input_value - fee
} else {
amount
};
Comment on lines +46 to +53

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Ensure total_input_value is greater than or equal to fee to prevent underflow

When calculating actual_amount, if total_input_value is less than fee, subtracting fee could cause an underflow. Consider adding a check to ensure total_input_value >= fee before performing the subtraction.

Apply this diff to add the check:

let actual_amount = if change_option.is_none() && allow_take_fee_from_amount {
    // The amount has been adjusted by taking the fee from the amount
    // Calculate the adjusted amount based on the total value of the UTXOs minus the fee
    let total_input_value: u64 = utxos.iter().map(|(_, (tx_out, _))| tx_out.value).sum();
+    if total_input_value < fee {
+        return Err("Total input value is less than the fee.".to_string());
+    }
    total_input_value - fee
} else {
    amount
};
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
let actual_amount = if change_option.is_none() && allow_take_fee_from_amount {
// The amount has been adjusted by taking the fee from the amount
// Calculate the adjusted amount based on the total value of the UTXOs minus the fee
let total_input_value: u64 = utxos.iter().map(|(_, (tx_out, _))| tx_out.value).sum();
total_input_value - fee
} else {
amount
};
let actual_amount = if change_option.is_none() && allow_take_fee_from_amount {
// The amount has been adjusted by taking the fee from the amount
// Calculate the adjusted amount based on the total value of the UTXOs minus the fee
let total_input_value: u64 = utxos.iter().map(|(_, (tx_out, _))| tx_out.value).sum();
if total_input_value < fee {
return Err("Total input value is less than the fee.".to_string());
}
total_input_value - fee
} else {
amount
};


let payload_output = TxOut {
value: amount,
value: actual_amount,
script_pubkey: ScriptBuf::new_p2pkh(&one_time_key_hash),
};
let burn_output = TxOut {
value: amount,
value: actual_amount,
script_pubkey: ScriptBuf::new_op_return(&[]),
};
if change < fee {
return Err("Change < Fee in asset_lock_transaction()".to_string());
}
let change_output = TxOut {
value: change - fee,
script_pubkey: change_address.script_pubkey(),

let (change_output, change_address) = if let Some(change) = change_option {
let change_address = self.change_address(network, register_addresses)?;
(
Some(TxOut {
value: change,
script_pubkey: change_address.script_pubkey(),
}),
Some(change_address),
)
} else {
(None, None)
};

let payload = AssetLockPayload {
version: 1,
credit_outputs: vec![payload_output],
};

// we need to get all inputs from utxos to add them to the transaction

// Collect inputs from UTXOs
let inputs = utxos
.iter()
.map(|(utxo, _)| {
let mut tx_in = TxIn::default();
tx_in.previous_output = utxo.clone();
tx_in
.map(|(utxo, _)| TxIn {
previous_output: utxo.clone(),
..Default::default()
})
.collect();

let sighash_u32 = 1u32;

let mut tx: Transaction = Transaction {
let mut tx = Transaction {
version: 3,
lock_time: 0,
input: inputs,
output: vec![burn_output, change_output],
output: {
let mut outputs = vec![burn_output];
if let Some(change_output) = change_output {
outputs.push(change_output);
}
outputs
},
Comment on lines +95 to +101

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

payload_output is not included in the transaction outputs

The transaction outputs currently include burn_output and optionally change_output, but payload_output is not added to the outputs. This might be unintended, as payload_output should likely be included in the transaction outputs.

Apply this diff to include payload_output in the outputs:

let mut outputs = vec![burn_output];
+    outputs.push(payload_output);
    if let Some(change_output) = change_output {
        outputs.push(change_output);
    }

Committable suggestion skipped: line range outside the PR's diff.

special_transaction_payload: Some(TransactionPayload::AssetLockPayloadType(payload)),
};

let sighash_u32 = 1u32;

let cache = SighashCache::new(&tx);

// Next, collect the sighashes for each input since that's what we need from the
Expand Down
6 changes: 5 additions & 1 deletion src/model/wallet/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,11 @@ impl Wallet {
}

pub fn max_balance(&self) -> u64 {
self.address_balances.values().sum::<Duffs>()
self.utxos
.values()
.map(|outpoints_to_tx_out| outpoints_to_tx_out.values().map(|tx_out| tx_out.value))
.flatten()
.sum::<Duffs>()
}

fn seed_bytes(&self) -> Result<&[u8; 64], String> {
Expand Down
67 changes: 52 additions & 15 deletions src/model/wallet/utxos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ impl Wallet {
pub fn take_unspent_utxos_for(
&mut self,
amount: u64,
) -> Option<(BTreeMap<OutPoint, (TxOut, Address)>, u64)> {
fee: u64,
allow_take_fee_from_amount: bool,
) -> Option<(BTreeMap<OutPoint, (TxOut, Address)>, Option<u64>)> {
// Ensure UTXOs exist
let utxos = &mut self.utxos;

let mut required: i64 = amount as i64;
let mut required: i64 = (amount + fee) as i64;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Avoid casting from u64 to i64 to prevent potential integer overflows

Casting u64 values to i64 can lead to integer overflows when dealing with large amounts, potentially causing incorrect calculations or negative values. It's safer to use u128 or consistently use u64 to handle large values without loss of precision.

Apply the following changes to use u128 instead of i64:

- let mut required: i64 = (amount + fee) as i64;
+ let mut required: u128 = amount + fee as u128;

...

- required -= tx_out.value as i64;
+ required = required.saturating_sub(tx_out.value as u64);

...

- if required > 0 {
+ if required > 0 {

...

- let total_collected = (amount + fee) as i64 - required;
+ let total_collected = (amount + fee) as u128 - required;

...

- let adjusted_amount = amount as i64 - missing_fee;
+ let adjusted_amount = amount as u128 - missing_fee;

...

- let total_input = (amount + fee) as i64 - required;
+ let total_input = (amount + fee) as u128 - required;

...

// Adjust all subsequent calculations and conditionals to use `u128`.

Also applies to: 28-28, 39-39, 44-44, 79-79

let mut taken_utxos = BTreeMap::new();
let mut utxos_to_remove = Vec::new();

Expand All @@ -31,23 +33,58 @@ impl Wallet {
}
}

// If not enough UTXOs were found, return None
// If not enough UTXOs were found, try to adjust if allowed
if required > 0 {
return None;
}

// Remove the collected UTXOs from the wallet's UTXO map
for (address, outpoint) in utxos_to_remove {
if let Some(outpoints) = utxos.get_mut(&address) {
outpoints.remove(&outpoint);
if outpoints.is_empty() {
utxos.remove(&address);
if allow_take_fee_from_amount {
let total_collected = (amount + fee) as i64 - required;
if total_collected >= amount as i64 {
// We have enough to cover the amount, but not the fee
// So we can reduce the amount by the missing fee
let missing_fee = required; // required > 0
let adjusted_amount = amount as i64 - missing_fee;
if adjusted_amount <= 0 {
// Cannot adjust amount to cover missing fee
return None;
}
// Remove UTXOs from wallet
for (address, outpoint) in utxos_to_remove {
if let Some(outpoints) = utxos.get_mut(&address) {
outpoints.remove(&outpoint);
if outpoints.is_empty() {
utxos.remove(&address);
}
}
}
// Return collected UTXOs and None for change
Some((taken_utxos, None))
} else {
// Not enough to cover amount even after adjusting
return None;
}
} else {
// Not enough UTXOs and not allowed to take fee from amount
return None;
}
}
} else {
// Remove the collected UTXOs from the wallet's UTXO map
for (address, outpoint) in utxos_to_remove {
if let Some(outpoints) = utxos.get_mut(&address) {
outpoints.remove(&outpoint);
if outpoints.is_empty() {
utxos.remove(&address);
}
}
}
// Calculate change amount
let total_input = (amount + fee) as i64 - required; // total input collected
let change = total_input as u64 - amount - fee;

// Return the collected UTXOs and the remaining amount (which should be zero or positive)
Some((taken_utxos, required.abs() as u64))
// If change is zero, return None
let change_option = if change > 0 { Some(change) } else { None };

// Return the collected UTXOs and the change amount
Some((taken_utxos, change_option))
}
}

pub fn reload_utxos(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,15 @@ impl AddNewIdentityScreen {

self.show_wallet_balance(ui);

step_number += 1;
ui.add_space(10.0);

ui.heading(format!(
"{}. How much of your wallet balance would you like to transfer?",
step_number
));

step_number += 1;

self.render_funding_amount_input(ui);

// Extract the step from the RwLock to minimize borrow scope
Expand Down
31 changes: 18 additions & 13 deletions src/ui/identities/add_new_identity_screen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -517,19 +517,24 @@ impl AddNewIdentityScreen {
*step = AddNewIdentityWalletFundedScreenStep::ReadyToCreate;
}
}
// if has_balance {
// if ui
// .selectable_value(
// &mut *funding_method,
// FundingMethod::UseWalletBalance,
// "Use Wallet Balance",
// )
// .changed()
// {
// let mut step = self.step.write().unwrap(); // Write lock on step
// *step = AddNewIdentityWalletFundedScreenStep::ReadyToCreate;
// }
// }
if has_balance {
if ui
.selectable_value(
&mut *funding_method,
FundingMethod::UseWalletBalance,
"Use Wallet Balance",
)
.changed()
{
if let Some(wallet) = &self.selected_wallet {
let wallet = wallet.read().unwrap(); // Read lock on the wallet
let max_amount = wallet.max_balance();
self.funding_amount = format!("{:.4}", max_amount as f64 * 1e-8);
}
let mut step = self.step.write().unwrap(); // Write lock on step
*step = AddNewIdentityWalletFundedScreenStep::ReadyToCreate;
}
}
Comment on lines +520 to +537

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider improving wallet balance handling and validation.

The wallet balance funding implementation could be enhanced in several ways:

  1. The funding amount formatting uses fixed precision which might truncate significant digits.
  2. There's no validation to ensure the wallet has sufficient balance for transaction fees.
  3. The satoshi-to-DASH conversion factor is hardcoded.

Consider applying these improvements:

 if has_balance {
     if ui
         .selectable_value(
             &mut *funding_method,
             FundingMethod::UseWalletBalance,
             "Use Wallet Balance",
         )
         .changed()
     {
         if let Some(wallet) = &self.selected_wallet {
             let wallet = wallet.read().unwrap();
             let max_amount = wallet.max_balance();
-            self.funding_amount = format!("{:.4}", max_amount as f64 * 1e-8);
+            // Reserve some balance for transaction fees
+            let reserved_for_fees = 1_000_000; // 0.01 DASH
+            let available_amount = max_amount.saturating_sub(reserved_for_fees);
+            const SATS_PER_DASH: f64 = 100_000_000.0;
+            self.funding_amount = format!("{}", available_amount as f64 / SATS_PER_DASH);
         }
         let mut step = self.step.write().unwrap();
         *step = AddNewIdentityWalletFundedScreenStep::ReadyToCreate;
     }
 }

Committable suggestion skipped: line range outside the PR's diff.

if ui
.selectable_value(
&mut *funding_method,
Expand Down
2 changes: 1 addition & 1 deletion src/ui/identities/withdraw_from_identity_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ impl WithdrawalScreen {
ui.text_edit_singleline(&mut self.withdrawal_amount);

if ui.button("Max").clicked() {
let expected_max_amount = self.max_amount.saturating_sub(5000000) as f64 * 1e-8;
let expected_max_amount = self.max_amount.saturating_sub(5000000) as f64 * 1e-11;

// Use flooring and format the result with 4 decimal places
let floored_amount = (expected_max_amount * 10_000.0).floor() / 10_000.0;
Expand Down
36 changes: 18 additions & 18 deletions src/ui/wallet/wallets_screen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ impl WalletsBalancesScreen {
.resizable(true)
.cell_layout(egui::Layout::left_to_right(egui::Align::Center))
.column(Column::auto()) // Address
// .column(Column::initial(100.0)) // Balance
.column(Column::initial(100.0)) // Balance
.column(Column::initial(60.0)) // UTXOs
.column(Column::initial(150.0)) // Total Received
.column(Column::initial(100.0)) // Type
Expand All @@ -412,19 +412,19 @@ impl WalletsBalancesScreen {
self.toggle_sort(SortColumn::Address);
}
});
// header.col(|ui| {
// let label = if self.sort_column == SortColumn::Balance {
// match self.sort_order {
// SortOrder::Ascending => "Balance (DASH) ^",
// SortOrder::Descending => "Balance (DASH) v",
// }
// } else {
// "Balance (DASH)"
// };
// if ui.button(label).clicked() {
// self.toggle_sort(SortColumn::Balance);
// }
// });
header.col(|ui| {
let label = if self.sort_column == SortColumn::Balance {
match self.sort_order {
SortOrder::Ascending => "Total Received (DASH) ^",
SortOrder::Descending => "Total Received (DASH) v",
}
} else {
"Total Received (DASH)"
};
if ui.button(label).clicked() {
self.toggle_sort(SortColumn::Balance);
}
});
Comment on lines +415 to +427

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix inconsistencies in column headers and sorting logic

There are several issues in the column header implementation:

  1. The sorting enum SortColumn::Balance is used for "Total Received" column, which is inconsistent.
  2. Both Balance and TotalReceived columns show the same header "Total Received (DASH)".
  3. The term "Total Received" might be misleading for a balance column.

Consider applying these changes:

-                                    let label = if self.sort_column == SortColumn::Balance {
+                                    let label = if self.sort_column == SortColumn::Balance {
                                         match self.sort_order {
-                                            SortOrder::Ascending => "Total Received (DASH) ^",
-                                            SortOrder::Descending => "Total Received (DASH) v",
+                                            SortOrder::Ascending => "Balance (DASH) ^",
+                                            SortOrder::Descending => "Balance (DASH) v",
                                         }
                                     } else {
-                                        "Total Received (DASH)"
+                                        "Balance (DASH)"
                                     };

Also, consider updating the SortColumn enum to better reflect the column's purpose:

 enum SortColumn {
     Address,
-    Balance,
+    CurrentBalance,
     UTXOs,
     TotalReceived,
     // ... rest of the enum
 }

Committable suggestion skipped: line range outside the PR's diff.

header.col(|ui| {
let label = if self.sort_column == SortColumn::UTXOs {
match self.sort_order {
Expand Down Expand Up @@ -497,10 +497,10 @@ impl WalletsBalancesScreen {
row.col(|ui| {
ui.label(data.address.to_string());
});
// row.col(|ui| {
// let dash_balance = data.balance as f64 * 1e-8;
// ui.label(format!("{:.8}", dash_balance));
// });
row.col(|ui| {
let dash_balance = data.balance as f64 * 1e-8;
ui.label(format!("{:.8}", dash_balance));
});
Comment on lines +500 to +503

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Improve balance conversion implementation

The current implementation has several potential issues:

  1. Uses magic number 1e-8 without explanation
  2. Direct floating-point multiplication could lead to precision issues
  3. No validation for potential overflow scenarios

Consider implementing a dedicated conversion function:

+ const DUFFS_PER_DASH: f64 = 1e8;
+
+ /// Converts an amount from Duffs to DASH
+ /// Returns None if the conversion would overflow
+ fn duffs_to_dash(duffs: u64) -> Option<f64> {
+     let dash = (duffs as f64) / DUFFS_PER_DASH;
+     if dash.is_finite() {
+         Some(dash)
+     } else {
+         None
+     }
+ }
+
                                         row.col(|ui| {
-                                            let dash_balance = data.balance as f64 * 1e-8;
-                                            ui.label(format!("{:.8}", dash_balance));
+                                            match duffs_to_dash(data.balance) {
+                                                Some(dash_balance) => ui.label(format!("{:.8}", dash_balance)),
+                                                None => ui.label("Error: Invalid balance"),
+                                            }
                                         });

Committable suggestion skipped: line range outside the PR's diff.

row.col(|ui| {
ui.label(format!("{}", data.utxo_count));
});
Expand Down