feat: use checked addition for u64

This commit is contained in:
thesimplekid
2025-02-12 12:27:05 +00:00
parent fedd4b9e58
commit 85ea5fff74
7 changed files with 29 additions and 6 deletions

View File

@@ -11,6 +11,9 @@ pub enum Error {
/// Unknown invoice
#[error("Unknown invoice")]
UnknownInvoice,
/// Amount overflow
#[error("Amount overflow")]
AmountOverflow,
/// Anyhow error
#[error(transparent)]
Anyhow(#[from] anyhow::Error),

View File

@@ -205,7 +205,13 @@ impl MintLightning for LNbits {
false => MeltQuoteState::Paid,
};
let total_spent = Amount::from((invoice_info.amount + invoice_info.fee).unsigned_abs());
let total_spent = Amount::from(
(invoice_info
.amount
.checked_add(invoice_info.fee)
.ok_or(Error::AmountOverflow)?)
.unsigned_abs(),
);
Ok(PayInvoiceResponse {
payment_lookup_id: pay_response.payment_hash,

View File

@@ -27,6 +27,9 @@ pub enum Error {
/// Missing last hop in route
#[error("LND missing last hop in route")]
MissingLastHop,
/// Amount overflow
#[error("Amount overflow")]
AmountOverflow,
/// Errors coming from the backend
#[error("LND error: `{0}`")]
LndError(Status),

View File

@@ -506,7 +506,13 @@ impl MintLightning for Lnd {
payment_lookup_id: payment_hash.to_string(),
payment_preimage: Some(update.payment_preimage),
status: MeltQuoteState::Paid,
total_spent: Amount::from((update.value_sat + update.fee_sat) as u64),
total_spent: Amount::from(
(update
.value_sat
.checked_add(update.fee_sat)
.ok_or(Error::AmountOverflow)?)
as u64,
),
unit: CurrencyUnit::Sat,
},
PaymentStatus::Failed => PayInvoiceResponse {

View File

@@ -14,6 +14,9 @@ pub enum Error {
/// Unsupported unit
#[error("Unit Unsupported")]
UnsupportedUnit,
/// Amount overflow
#[error("Amount overflow")]
AmountOverflow,
/// phd error
#[error(transparent)]
Phd(#[from] phoenixd_rs::Error),

View File

@@ -176,7 +176,7 @@ impl MintLightning for Phoenixd {
};
// Fee in phoenixd is always 0.04 + 4 sat
fee += 4;
fee = fee.checked_add(4).ok_or(Error::AmountOverflow)?;
Ok(PaymentQuoteResponse {
request_lookup_id: melt_quote_request.request.payment_hash().to_string(),

View File

@@ -15,7 +15,7 @@ pub fn calculate_fee(
proofs_count: &HashMap<Id, u64>,
keyset_fee: &HashMap<Id, u64>,
) -> Result<Amount, Error> {
let mut sum_fee = 0;
let mut sum_fee: u64 = 0;
for (keyset_id, proof_count) in proofs_count {
let keyset_fee_ppk = keyset_fee
@@ -24,10 +24,12 @@ pub fn calculate_fee(
let proofs_fee = keyset_fee_ppk * proof_count;
sum_fee += proofs_fee;
sum_fee = sum_fee
.checked_add(proofs_fee)
.ok_or(Error::AmountOverflow)?;
}
let fee = (sum_fee + 999) / 1000;
let fee = (sum_fee.checked_add(999).ok_or(Error::AmountOverflow)?) / 1000;
Ok(fee.into())
}