Skip to content

Commit

Permalink
move logic to node_api.rs
Browse files Browse the repository at this point in the history
  • Loading branch information
ubbabeck committed Dec 19, 2023
1 parent f3b6055 commit 3433d82
Show file tree
Hide file tree
Showing 12 changed files with 89 additions and 30 deletions.
1 change: 1 addition & 0 deletions libs/sdk-bindings/src/breez_sdk.udl
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ dictionary LnPaymentDetails {
string? ln_address;
string? lnurl_withdraw_endpoint;
SwapInfo? swap_info;
u32? htlc_expiry;
};

dictionary ClosedChannelPaymentDetails {
Expand Down
26 changes: 2 additions & 24 deletions libs/sdk-core/src/breez_services.rs
Original file line number Diff line number Diff line change
Expand Up @@ -910,34 +910,12 @@ impl BreezServices {
let closed_channel_tx = self.closed_channel_to_transaction(closed_channel).await?;
closed_channel_payments.push(closed_channel_tx);
}
let peers = self.node_api.list_peers().await?;

for p in peers {
for h in p.channels {
let htlcs = h.htlc;
if let Some(hh) = htlcs {
for cc in hh {
info!("htlc info {:?}{:?}", cc.payment_hash, cc.expiry);
let payment_hash = hex::encode(cc.payment_hash);

if let Ok(Some(payment)) = self.persister.get_payment_by_hash(&payment_hash)
{
info!(
"htlc payment is {:?}",
payment.status == PaymentStatus::Pending
);
}
}
}
}
}

// todo add payement filters
// update both closed channels and lightning transaction payments
let mut payments = closed_channel_payments;
payments.extend(new_data.payments.clone());
self.persister.insert_or_update_payments(&payments, true)?;

info!("payment list consist of {:?}", payments);
let duration = start.elapsed();
info!("Sync duration: {:?}", duration);

Expand Down Expand Up @@ -1007,7 +985,7 @@ impl BreezServices {
lnurl_metadata: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None // TODO insert here
htlc_expiry: None,
},
},
}],
Expand Down
1 change: 1 addition & 0 deletions libs/sdk-core/src/bridge_generated.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1248,6 +1248,7 @@ impl support::IntoDart for LnPaymentDetails {
self.lnurl_metadata.into_dart(),
self.lnurl_withdraw_endpoint.into_dart(),
self.swap_info.into_dart(),
self.htlc_expiry.into_dart(),
]
.into_dart()
}
Expand Down
49 changes: 47 additions & 2 deletions libs/sdk-core/src/greenlight/node_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ use tonic::Streaming;
use crate::invoice::{parse_invoice, validate_network, InvoiceError, RouteHintHop};
use crate::models::*;
use crate::node_api::{NodeAPI, NodeError, NodeResult};

use crate::persist::db::SqliteStorage;
use crate::{Channel, ChannelState, NodeConfig, PrepareSweepRequest, PrepareSweepResponse};
use std::iter::Iterator;
Expand Down Expand Up @@ -703,7 +704,6 @@ impl NodeAPI for Greenlight {
all_channels.clone().into_iter().map(|c| c.into()).collect();
all_channel_models.extend(forgotten_closed_channels?);

info!("in flight htlc {:?}", all_channel_models);
// calculate onchain balance
let onchain_balance = self.on_chain_balance(funds.clone()).await?;
let utxos = self.utxos(funds).await?;
Expand Down Expand Up @@ -731,7 +731,6 @@ impl NodeAPI for Greenlight {
let max_allowed_to_receive_msats =
MAX_INBOUND_LIQUIDITY_MSAT.saturating_sub(channels_balance);
let node_pubkey = hex::encode(node_info.id);
// perhaps add inflight htlc to NodeState
// construct the node state
let node_state = NodeState {
id: node_pubkey.clone(),
Expand Down Expand Up @@ -1443,13 +1442,54 @@ async fn pull_transactions(
.map(TryInto::try_into)
.collect();

let res = c
.list_peers(cln::ListpeersRequest::default())
.await?
.into_inner();
let peers_models: Vec<Peer> = res.peers.into_iter().map(|p| p.into()).collect();

let outbound_transactions: NodeResult<Vec<Payment>> =
htlc_expiry(outbound_transactions.unwrap(), peers_models);

let mut transactions: Vec<Payment> = Vec::new();
transactions.extend(received_transactions?);
transactions.extend(outbound_transactions?);

Ok(transactions)
}

fn htlc_expiry(payments: Vec<Payment>, peers: Vec<Peer>) -> NodeResult<Vec<Payment>> {
let mut pending_payments: Vec<Payment> = vec![];
if peers.is_empty() {
return Ok(pending_payments);
}
for peer in peers {
for channel in peer.channels {
let htlcs = channel.htlc;
if let Some(htlc) = htlcs {
info!("We have inflight htlcs {:?}", htlc);
for h in htlc {
let payment_hash = hex::encode(h.clone().payment_hash);
info!("htlc payment hash is {:?}", payment_hash);
for mut payment in payments.clone() {
let new_data = payment.clone().details;
if let PaymentDetails::Ln { data } = new_data {
if data.payment_hash == payment_hash {
info!("payment hashes match let add the htlc");
info!("adding htlc to payment {:?}", h);
payment.details.add_htlc_expiry(h.clone());
pending_payments.push(payment)
}
}
}
}
}
}
}
info!("pending htlc payments {:?}", pending_payments);
Ok(pending_payments)
}

//pub(crate) fn offchain_payment_to_transaction
impl TryFrom<OffChainPayment> for Payment {
type Error = NodeError;
Expand Down Expand Up @@ -1478,6 +1518,7 @@ impl TryFrom<OffChainPayment> for Payment {
ln_address: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None,
},
},
})
Expand Down Expand Up @@ -1517,6 +1558,7 @@ impl TryFrom<gl_client::signer::model::greenlight::Invoice> for Payment {
ln_address: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None,
},
},
})
Expand Down Expand Up @@ -1571,6 +1613,7 @@ impl TryFrom<gl_client::signer::model::greenlight::Payment> for Payment {
ln_address: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None,
},
},
})
Expand Down Expand Up @@ -1612,6 +1655,7 @@ impl TryFrom<cln::ListinvoicesInvoices> for Payment {
ln_address: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None,
},
},
})
Expand Down Expand Up @@ -1676,6 +1720,7 @@ impl TryFrom<cln::ListpaysPays> for Payment {
ln_address: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None,
},
},
})
Expand Down
9 changes: 9 additions & 0 deletions libs/sdk-core/src/models.rs
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,15 @@ pub enum PaymentDetails {
},
}

impl PaymentDetails {
pub fn add_htlc_expiry(&mut self, htlc: Htlc) {
info!("adding htlc expiry to payment details{:?}", htlc);
if let PaymentDetails::Ln { data } = self {
data.htlc_expiry = Some(htlc.expiry)
}
}
}

/// Details of a LN payment, as included in a [Payment]
#[derive(PartialEq, Eq, Debug, Clone, Deserialize, Serialize)]
pub struct LnPaymentDetails {
Expand Down
2 changes: 1 addition & 1 deletion libs/sdk-core/src/persist/channels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ impl SqliteStorage {
alias_local: row.get(7)?,
alias_remote: row.get(8)?,
closing_txid: row.get(9)?,
htlc: None,
htlc: None, // TODO add htlc list here
})
})?
.map(|i| i.unwrap())
Expand Down
7 changes: 6 additions & 1 deletion libs/sdk-core/src/persist/transactions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,8 @@ impl SqliteStorage {
data.lnurl_withdraw_endpoint = row.get(11)?;
data.swap_info = self
.get_swap_info_by_hash(&hex::decode(&payment.id).unwrap_or_default())
.unwrap_or(None)
.unwrap_or(None);
data.htlc_expiry = None; // TODO add expiry
}

// In case we have a record of the open channel fee, let's use it.
Expand Down Expand Up @@ -473,6 +474,7 @@ fn test_ln_transactions() -> PersistResult<(), Box<dyn std::error::Error>> {
ln_address: Some(test_ln_address.to_string()),
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None,
},
},
},
Expand All @@ -498,6 +500,7 @@ fn test_ln_transactions() -> PersistResult<(), Box<dyn std::error::Error>> {
ln_address: None,
lnurl_withdraw_endpoint: Some(lnurl_withdraw_url.to_string()),
swap_info: None,
htlc_expiry: None,
},
},
},
Expand All @@ -523,6 +526,7 @@ fn test_ln_transactions() -> PersistResult<(), Box<dyn std::error::Error>> {
ln_address: None,
lnurl_withdraw_endpoint: None,
swap_info: Some(swap_info.clone()),
htlc_expiry: None,
},
},
},
Expand All @@ -549,6 +553,7 @@ fn test_ln_transactions() -> PersistResult<(), Box<dyn std::error::Error>> {
ln_address: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None,
},
},
}];
Expand Down
1 change: 1 addition & 0 deletions libs/sdk-core/src/swap_in/swap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,7 @@ mod tests {
ln_address: None,
lnurl_withdraw_endpoint: None,
swap_info: None,
htlc_expiry: None,
},
},
};
Expand Down
7 changes: 6 additions & 1 deletion libs/sdk-flutter/lib/bridge_generated.dart
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,9 @@ class LnPaymentDetails {
/// Only set for [PaymentType::Received] payments that were received in the context of a swap
final SwapInfo? swapInfo;

/// Only set for [PaymentType::Pending] payments that are inflight.
final int? htlcExpiry;

const LnPaymentDetails({
required this.paymentHash,
required this.label,
Expand All @@ -715,6 +718,7 @@ class LnPaymentDetails {
this.lnurlMetadata,
this.lnurlWithdrawEndpoint,
this.swapInfo,
this.htlcExpiry,
});
}

Expand Down Expand Up @@ -3097,7 +3101,7 @@ class BreezSdkCoreImpl implements BreezSdkCore {

LnPaymentDetails _wire2api_ln_payment_details(dynamic raw) {
final arr = raw as List<dynamic>;
if (arr.length != 11) throw Exception('unexpected arr length: expect 11 but see ${arr.length}');
if (arr.length != 12) throw Exception('unexpected arr length: expect 12 but see ${arr.length}');
return LnPaymentDetails(
paymentHash: _wire2api_String(arr[0]),
label: _wire2api_String(arr[1]),
Expand All @@ -3110,6 +3114,7 @@ class BreezSdkCoreImpl implements BreezSdkCore {
lnurlMetadata: _wire2api_opt_String(arr[8]),
lnurlWithdrawEndpoint: _wire2api_opt_String(arr[9]),
swapInfo: _wire2api_opt_box_autoadd_swap_info(arr[10]),
htlcExpiry: _wire2api_opt_box_autoadd_u32(arr[11]),
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,7 @@ fun asLnPaymentDetails(lnPaymentDetails: ReadableMap): LnPaymentDetails? {
null
}
val swapInfo = if (hasNonNullKey(lnPaymentDetails, "swapInfo")) lnPaymentDetails.getMap("swapInfo")?.let { asSwapInfo(it) } else null
val htlcExpiry = if (hasNonNullKey(lnPaymentDetails, "htlcExpiry")) lnPaymentDetails.getInt("htlcExpiry").toUInt() else null
return LnPaymentDetails(
paymentHash,
label,
Expand All @@ -859,6 +860,7 @@ fun asLnPaymentDetails(lnPaymentDetails: ReadableMap): LnPaymentDetails? {
lnAddress,
lnurlWithdrawEndpoint,
swapInfo,
htlcExpiry,
)
}

Expand All @@ -875,6 +877,7 @@ fun readableMapOf(lnPaymentDetails: LnPaymentDetails): ReadableMap {
"lnAddress" to lnPaymentDetails.lnAddress,
"lnurlWithdrawEndpoint" to lnPaymentDetails.lnurlWithdrawEndpoint,
"swapInfo" to lnPaymentDetails.swapInfo?.let { readableMapOf(it) },
"htlcExpiry" to lnPaymentDetails.htlcExpiry,
)
}

Expand Down
12 changes: 11 additions & 1 deletion libs/sdk-react-native/ios/BreezSDKMapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -952,6 +952,14 @@ enum BreezSDKMapper {
swapInfo = try asSwapInfo(swapInfo: swapInfoTmp)
}

var htlcExpiry: UInt32?
if hasNonNilKey(data: lnPaymentDetails, key: "htlcExpiry") {
guard let htlcExpiryTmp = lnPaymentDetails["htlcExpiry"] as? UInt32 else {
throw SdkError.Generic(message: errUnexpectedValue(fieldName: "htlcExpiry"))
}
htlcExpiry = htlcExpiryTmp
}

return LnPaymentDetails(
paymentHash: paymentHash,
label: label,
Expand All @@ -963,7 +971,8 @@ enum BreezSDKMapper {
lnurlMetadata: lnurlMetadata,
lnAddress: lnAddress,
lnurlWithdrawEndpoint: lnurlWithdrawEndpoint,
swapInfo: swapInfo
swapInfo: swapInfo,
htlcExpiry: htlcExpiry
)
}

Expand All @@ -980,6 +989,7 @@ enum BreezSDKMapper {
"lnAddress": lnPaymentDetails.lnAddress == nil ? nil : lnPaymentDetails.lnAddress,
"lnurlWithdrawEndpoint": lnPaymentDetails.lnurlWithdrawEndpoint == nil ? nil : lnPaymentDetails.lnurlWithdrawEndpoint,
"swapInfo": lnPaymentDetails.swapInfo == nil ? nil : dictionaryOf(swapInfo: lnPaymentDetails.swapInfo!),
"htlcExpiry": lnPaymentDetails.htlcExpiry == nil ? nil : lnPaymentDetails.htlcExpiry,
]
}

Expand Down
1 change: 1 addition & 0 deletions libs/sdk-react-native/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ export type LnPaymentDetails = {
lnAddress?: string
lnurlWithdrawEndpoint?: string
swapInfo?: SwapInfo
htlcExpiry?: number
}

export type LnUrlAuthRequestData = {
Expand Down

0 comments on commit 3433d82

Please sign in to comment.