Skip to content

Commit 04841ac

Browse files
authored
Merge pull request #2595 from TheBlueMatt/2023-09-117-bindings-part1
Various cleanups to make bindings generation simpler
2 parents a938fec + 7a583bb commit 04841ac

File tree

15 files changed

+183
-131
lines changed

15 files changed

+183
-131
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ impl chain::Watch<TestChannelSigner> for TestChainMonitor {
155155
};
156156
let deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<TestChannelSigner>)>::
157157
read(&mut Cursor::new(&map_entry.get().1), (&*self.keys, &*self.keys)).unwrap().1;
158-
deserialized_monitor.update_monitor(update, &&TestBroadcaster{}, &FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }, &self.logger).unwrap();
158+
deserialized_monitor.update_monitor(update, &&TestBroadcaster{}, &&FuzzEstimator { ret_val: atomic::AtomicU32::new(253) }, &self.logger).unwrap();
159159
let mut ser = VecWriter(Vec::new());
160160
deserialized_monitor.write(&mut ser).unwrap();
161161
map_entry.insert((update.update_id, ser.0));

lightning-background-processor/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1181,7 +1181,7 @@ mod tests {
11811181
let network_graph = Arc::new(NetworkGraph::new(network, logger.clone()));
11821182
let scorer = Arc::new(Mutex::new(TestScorer::new()));
11831183
let seed = [i as u8; 32];
1184-
let router = Arc::new(DefaultRouter::new(network_graph.clone(), logger.clone(), seed, scorer.clone(), ()));
1184+
let router = Arc::new(DefaultRouter::new(network_graph.clone(), logger.clone(), seed, scorer.clone(), Default::default()));
11851185
let chain_source = Arc::new(test_utils::TestChainSource::new(Network::Bitcoin));
11861186
let kv_store = Arc::new(FilesystemStore::new(format!("{}_persister_{}", &persist_dir, i).into()));
11871187
let now = Duration::from_secs(genesis_block.header.time as u64);

lightning-invoice/src/payment.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99

1010
//! Convenient utilities for paying Lightning invoices.
1111
12-
use crate::{Bolt11Invoice, Vec};
12+
use crate::Bolt11Invoice;
13+
use crate::prelude::*;
1314

1415
use bitcoin_hashes::Hash;
1516

lightning/src/chain/chainmonitor.rs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -324,7 +324,6 @@ where C::Target: chain::Filter,
324324
if self.update_monitor_with_chain_data(header, best_height, txdata, &process, funding_outpoint, &monitor_state).is_err() {
325325
// Take the monitors lock for writing so that we poison it and any future
326326
// operations going forward fail immediately.
327-
core::mem::drop(monitor_state);
328327
core::mem::drop(monitor_lock);
329328
let _poison = self.monitors.write().unwrap();
330329
log_error!(self.logger, "{}", err_str);
@@ -767,7 +766,7 @@ where C::Target: chain::Filter,
767766
Some(monitor_state) => {
768767
let monitor = &monitor_state.monitor;
769768
log_trace!(self.logger, "Updating ChannelMonitor for channel {}", log_funding_info!(monitor));
770-
let update_res = monitor.update_monitor(update, &self.broadcaster, &*self.fee_estimator, &self.logger);
769+
let update_res = monitor.update_monitor(update, &self.broadcaster, &self.fee_estimator, &self.logger);
771770

772771
let update_id = MonitorUpdateId::from_monitor_update(update);
773772
let mut pending_monitor_updates = monitor_state.pending_monitor_updates.lock().unwrap();

lightning/src/chain/channelmonitor.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1311,7 +1311,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
13111311
&self,
13121312
updates: &ChannelMonitorUpdate,
13131313
broadcaster: &B,
1314-
fee_estimator: F,
1314+
fee_estimator: &F,
13151315
logger: &L,
13161316
) -> Result<(), ()>
13171317
where
@@ -2615,7 +2615,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
26152615
self.pending_monitor_events.push(MonitorEvent::HolderForceClosed(self.funding_info.0));
26162616
}
26172617

2618-
pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: F, logger: &L) -> Result<(), ()>
2618+
pub fn update_monitor<B: Deref, F: Deref, L: Deref>(&mut self, updates: &ChannelMonitorUpdate, broadcaster: &B, fee_estimator: &F, logger: &L) -> Result<(), ()>
26192619
where B::Target: BroadcasterInterface,
26202620
F::Target: FeeEstimator,
26212621
L::Target: Logger,
@@ -2655,7 +2655,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
26552655
panic!("Attempted to apply ChannelMonitorUpdates out of order, check the update_id before passing an update to update_monitor!");
26562656
}
26572657
let mut ret = Ok(());
2658-
let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&*fee_estimator);
2658+
let bounded_fee_estimator = LowerBoundedFeeEstimator::new(&**fee_estimator);
26592659
for update in updates.updates.iter() {
26602660
match update {
26612661
ChannelMonitorUpdateStep::LatestHolderCommitmentTXInfo { commitment_tx, htlc_outputs, claimed_htlcs, nondust_htlc_sources } => {
@@ -4581,7 +4581,7 @@ mod tests {
45814581

45824582
let broadcaster = TestBroadcaster::with_blocks(Arc::clone(&nodes[1].blocks));
45834583
assert!(
4584-
pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
4584+
pre_update_monitor.update_monitor(&replay_update, &&broadcaster, &&chanmon_cfgs[1].fee_estimator, &nodes[1].logger)
45854585
.is_err());
45864586
// Even though we error'd on the first update, we should still have generated an HTLC claim
45874587
// transaction

lightning/src/ln/channelmanager.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -840,6 +840,9 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L> =
840840
>;
841841

842842
/// A trivial trait which describes any [`ChannelManager`].
843+
///
844+
/// This is not exported to bindings users as general cover traits aren't useful in other
845+
/// languages.
843846
pub trait AChannelManager {
844847
/// A type implementing [`chain::Watch`].
845848
type Watch: chain::Watch<Self::Signer> + ?Sized;

lightning/src/ln/outbound_payment.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,10 +594,26 @@ impl RecipientOnionFields {
594594
/// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
595595
/// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
596596
/// This is validated when setting this field using [`Self::with_custom_tlvs`].
597+
#[cfg(not(c_bindings))]
597598
pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
598599
&self.custom_tlvs
599600
}
600601

602+
/// Gets the custom TLVs that will be sent or have been received.
603+
///
604+
/// Custom TLVs allow sending extra application-specific data with a payment. They provide
605+
/// additional flexibility on top of payment metadata, as while other implementations may
606+
/// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
607+
/// do not have this restriction.
608+
///
609+
/// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
610+
/// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
611+
/// This is validated when setting this field using [`Self::with_custom_tlvs`].
612+
#[cfg(c_bindings)]
613+
pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
614+
self.custom_tlvs.clone()
615+
}
616+
601617
/// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
602618
/// have to make sure that some fields match exactly across the parts. For those that aren't
603619
/// required to match, if they don't match we should remove them so as to not expose data

lightning/src/ln/payment_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3781,7 +3781,7 @@ fn test_retry_custom_tlvs() {
37813781
payment_hash, Some(payment_secret), events.pop().unwrap(), true, None).unwrap();
37823782
match payment_claimable {
37833783
Event::PaymentClaimable { onion_fields, .. } => {
3784-
assert_eq!(onion_fields.unwrap().custom_tlvs(), &custom_tlvs);
3784+
assert_eq!(&onion_fields.unwrap().custom_tlvs()[..], &custom_tlvs[..]);
37853785
},
37863786
_ => panic!("Unexpected event"),
37873787
};

lightning/src/offers/offer.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
366366
/// The chains that may be used when paying a requested invoice (e.g., bitcoin mainnet).
367367
/// Payments must be denominated in units of the minimal lightning-payable unit (e.g., msats)
368368
/// for the selected chain.
369-
pub fn chains(&$self) -> Vec<$crate::bitcoin::blockdata::constants::ChainHash> {
369+
pub fn chains(&$self) -> Vec<bitcoin::blockdata::constants::ChainHash> {
370370
$contents.chains()
371371
}
372372

@@ -418,7 +418,7 @@ macro_rules! offer_accessors { ($self: ident, $contents: expr) => {
418418
}
419419

420420
/// The public key used by the recipient to sign invoices.
421-
pub fn signing_pubkey(&$self) -> $crate::bitcoin::secp256k1::PublicKey {
421+
pub fn signing_pubkey(&$self) -> bitcoin::secp256k1::PublicKey {
422422
$contents.signing_pubkey()
423423
}
424424
} }

lightning/src/onion_message/messenger.rs

Lines changed: 61 additions & 64 deletions
Original file line numberDiff line numberDiff line change
@@ -246,6 +246,64 @@ pub trait CustomOnionMessageHandler {
246246
fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
247247
}
248248

249+
250+
/// Create an onion message with contents `message` to the destination of `path`.
251+
/// Returns (introduction_node_id, onion_msg)
252+
pub fn create_onion_message<ES: Deref, NS: Deref, T: CustomOnionMessageContents>(
253+
entropy_source: &ES, node_signer: &NS, secp_ctx: &Secp256k1<secp256k1::All>,
254+
path: OnionMessagePath, message: OnionMessageContents<T>, reply_path: Option<BlindedPath>,
255+
) -> Result<(PublicKey, msgs::OnionMessage), SendError>
256+
where
257+
ES::Target: EntropySource,
258+
NS::Target: NodeSigner,
259+
{
260+
let OnionMessagePath { intermediate_nodes, mut destination } = path;
261+
if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
262+
if blinded_hops.len() < 2 {
263+
return Err(SendError::TooFewBlindedHops);
264+
}
265+
}
266+
267+
if message.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
268+
269+
// If we are sending straight to a blinded path and we are the introduction node, we need to
270+
// advance the blinded path by 1 hop so the second hop is the new introduction node.
271+
if intermediate_nodes.len() == 0 {
272+
if let Destination::BlindedPath(ref mut blinded_path) = destination {
273+
let our_node_id = node_signer.get_node_id(Recipient::Node)
274+
.map_err(|()| SendError::GetNodeIdFailed)?;
275+
if blinded_path.introduction_node_id == our_node_id {
276+
advance_path_by_one(blinded_path, node_signer, &secp_ctx)
277+
.map_err(|()| SendError::BlindedPathAdvanceFailed)?;
278+
}
279+
}
280+
}
281+
282+
let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
283+
let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
284+
let (introduction_node_id, blinding_point) = if intermediate_nodes.len() != 0 {
285+
(intermediate_nodes[0], PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
286+
} else {
287+
match destination {
288+
Destination::Node(pk) => (pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
289+
Destination::BlindedPath(BlindedPath { introduction_node_id, blinding_point, .. }) =>
290+
(introduction_node_id, blinding_point),
291+
}
292+
};
293+
let (packet_payloads, packet_keys) = packet_payloads_and_keys(
294+
&secp_ctx, &intermediate_nodes, destination, message, reply_path, &blinding_secret)
295+
.map_err(|e| SendError::Secp256k1(e))?;
296+
297+
let prng_seed = entropy_source.get_secure_random_bytes();
298+
let onion_routing_packet = construct_onion_message_packet(
299+
packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
300+
301+
Ok((introduction_node_id, msgs::OnionMessage {
302+
blinding_point,
303+
onion_routing_packet
304+
}))
305+
}
306+
249307
impl<ES: Deref, NS: Deref, L: Deref, MR: Deref, OMH: Deref, CMH: Deref>
250308
OnionMessenger<ES, NS, L, MR, OMH, CMH>
251309
where
@@ -283,13 +341,9 @@ where
283341
&self, path: OnionMessagePath, message: OnionMessageContents<T>,
284342
reply_path: Option<BlindedPath>
285343
) -> Result<(), SendError> {
286-
let (introduction_node_id, onion_msg) = Self::create_onion_message(
287-
&self.entropy_source,
288-
&self.node_signer,
289-
&self.secp_ctx,
290-
path,
291-
message,
292-
reply_path
344+
let (introduction_node_id, onion_msg) = create_onion_message(
345+
&self.entropy_source, &self.node_signer, &self.secp_ctx,
346+
path, message, reply_path
293347
)?;
294348

295349
let mut pending_per_peer_msgs = self.pending_messages.lock().unwrap();
@@ -303,63 +357,6 @@ where
303357
}
304358
}
305359

306-
/// Create an onion message with contents `message` to the destination of `path`.
307-
/// Returns (introduction_node_id, onion_msg)
308-
pub fn create_onion_message<T: CustomOnionMessageContents>(
309-
entropy_source: &ES,
310-
node_signer: &NS,
311-
secp_ctx: &Secp256k1<secp256k1::All>,
312-
path: OnionMessagePath,
313-
message: OnionMessageContents<T>,
314-
reply_path: Option<BlindedPath>,
315-
) -> Result<(PublicKey, msgs::OnionMessage), SendError> {
316-
let OnionMessagePath { intermediate_nodes, mut destination } = path;
317-
if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
318-
if blinded_hops.len() < 2 {
319-
return Err(SendError::TooFewBlindedHops);
320-
}
321-
}
322-
323-
if message.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
324-
325-
// If we are sending straight to a blinded path and we are the introduction node, we need to
326-
// advance the blinded path by 1 hop so the second hop is the new introduction node.
327-
if intermediate_nodes.len() == 0 {
328-
if let Destination::BlindedPath(ref mut blinded_path) = destination {
329-
let our_node_id = node_signer.get_node_id(Recipient::Node)
330-
.map_err(|()| SendError::GetNodeIdFailed)?;
331-
if blinded_path.introduction_node_id == our_node_id {
332-
advance_path_by_one(blinded_path, node_signer, &secp_ctx)
333-
.map_err(|()| SendError::BlindedPathAdvanceFailed)?;
334-
}
335-
}
336-
}
337-
338-
let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
339-
let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
340-
let (introduction_node_id, blinding_point) = if intermediate_nodes.len() != 0 {
341-
(intermediate_nodes[0], PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
342-
} else {
343-
match destination {
344-
Destination::Node(pk) => (pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
345-
Destination::BlindedPath(BlindedPath { introduction_node_id, blinding_point, .. }) =>
346-
(introduction_node_id, blinding_point),
347-
}
348-
};
349-
let (packet_payloads, packet_keys) = packet_payloads_and_keys(
350-
&secp_ctx, &intermediate_nodes, destination, message, reply_path, &blinding_secret)
351-
.map_err(|e| SendError::Secp256k1(e))?;
352-
353-
let prng_seed = entropy_source.get_secure_random_bytes();
354-
let onion_routing_packet = construct_onion_message_packet(
355-
packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
356-
357-
Ok((introduction_node_id, msgs::OnionMessage {
358-
blinding_point,
359-
onion_routing_packet
360-
}))
361-
}
362-
363360
fn respond_with_onion_message<T: CustomOnionMessageContents>(
364361
&self, response: OnionMessageContents<T>, path_id: Option<[u8; 32]>,
365362
reply_path: Option<BlindedPath>

lightning/src/routing/router.rs

Lines changed: 4 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -112,12 +112,12 @@ pub trait Router {
112112
/// [`find_route`].
113113
///
114114
/// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
115-
pub struct ScorerAccountingForInFlightHtlcs<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> {
115+
pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
116116
scorer: S,
117117
// Maps a channel's short channel id and its direction to the liquidity used up.
118118
inflight_htlcs: &'a InFlightHtlcs,
119119
}
120-
impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
120+
impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
121121
/// Initialize a new `ScorerAccountingForInFlightHtlcs`.
122122
pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
123123
ScorerAccountingForInFlightHtlcs {
@@ -127,13 +127,8 @@ impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> Sc
127127
}
128128
}
129129

130-
#[cfg(c_bindings)]
131-
impl<'a, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> Writeable for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
132-
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
133-
}
134-
135-
impl<'a, SP: Sized, Sc: 'a + ScoreLookUp<ScoreParams = SP>, S: Deref<Target = Sc>> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, SP, Sc, S> {
136-
type ScoreParams = Sc::ScoreParams;
130+
impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
131+
type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
137132
fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
138133
if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
139134
source, target, short_channel_id

0 commit comments

Comments
 (0)