Skip to content

Commit e4c44f3

Browse files
authored
Merge pull request #2430 from TheBlueMatt/2023-07-116-bindings-part-1
Assorted 0.0.116 Bindings updates
2 parents 16311f9 + 35dda4e commit e4c44f3

File tree

8 files changed

+42
-50
lines changed

8 files changed

+42
-50
lines changed

fuzz/src/chanmon_consistency.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ struct FuzzRouter {}
8989
impl Router for FuzzRouter {
9090
fn find_route(
9191
&self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
92-
_inflight_htlcs: &InFlightHtlcs
92+
_inflight_htlcs: InFlightHtlcs
9393
) -> Result<Route, msgs::LightningError> {
9494
Err(msgs::LightningError {
9595
err: String::from("Not implemented"),

fuzz/src/full_stack.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,7 @@ struct FuzzRouter {}
131131
impl Router for FuzzRouter {
132132
fn find_route(
133133
&self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
134-
_inflight_htlcs: &InFlightHtlcs
134+
_inflight_htlcs: InFlightHtlcs
135135
) -> Result<Route, msgs::LightningError> {
136136
Err(msgs::LightningError {
137137
err: String::from("Not implemented"),

lightning/src/events/bump_transaction.rs

+20-15
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ use crate::ln::chan_utils::{
2626
use crate::ln::features::ChannelTypeFeatures;
2727
use crate::ln::PaymentPreimage;
2828
use crate::prelude::*;
29-
use crate::sign::{ChannelSigner, EcdsaChannelSigner, SignerProvider};
29+
use crate::sign::{ChannelSigner, EcdsaChannelSigner, SignerProvider, WriteableEcdsaChannelSigner};
3030
use crate::sync::Mutex;
3131
use crate::util::logger::Logger;
3232

@@ -102,9 +102,9 @@ impl AnchorDescriptor {
102102
}
103103

104104
/// Derives the channel signer required to sign the anchor input.
105-
pub fn derive_channel_signer<SP: Deref>(&self, signer_provider: &SP) -> <SP::Target as SignerProvider>::Signer
105+
pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
106106
where
107-
SP::Target: SignerProvider
107+
SP::Target: SignerProvider<Signer = S>
108108
{
109109
let mut signer = signer_provider.derive_channel_signer(
110110
self.channel_derivation_parameters.value_satoshis,
@@ -211,9 +211,9 @@ impl HTLCDescriptor {
211211
}
212212

213213
/// Derives the channel signer required to sign the HTLC input.
214-
pub fn derive_channel_signer<SP: Deref>(&self, signer_provider: &SP) -> <SP::Target as SignerProvider>::Signer
214+
pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
215215
where
216-
SP::Target: SignerProvider
216+
SP::Target: SignerProvider<Signer = S>
217217
{
218218
let mut signer = signer_provider.derive_channel_signer(
219219
self.channel_derivation_parameters.value_satoshis,
@@ -464,12 +464,12 @@ pub trait CoinSelectionSource {
464464
/// which UTXOs to double spend is left to the implementation, but it must strive to keep the
465465
/// set of other claims being double spent to a minimum.
466466
fn select_confirmed_utxos(
467-
&self, claim_id: ClaimId, must_spend: &[Input], must_pay_to: &[TxOut],
467+
&self, claim_id: ClaimId, must_spend: Vec<Input>, must_pay_to: &[TxOut],
468468
target_feerate_sat_per_1000_weight: u32,
469469
) -> Result<CoinSelection, ()>;
470470
/// Signs and provides the full witness for all inputs within the transaction known to the
471471
/// trait (i.e., any provided via [`CoinSelectionSource::select_confirmed_utxos`]).
472-
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()>;
472+
fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()>;
473473
}
474474

475475
/// An alternative to [`CoinSelectionSource`] that can be implemented and used along [`Wallet`] to
@@ -483,7 +483,7 @@ pub trait WalletSource {
483483
/// Signs and provides the full [`TxIn::script_sig`] and [`TxIn::witness`] for all inputs within
484484
/// the transaction known to the wallet (i.e., any provided via
485485
/// [`WalletSource::list_confirmed_utxos`]).
486-
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()>;
486+
fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()>;
487487
}
488488

489489
/// A wrapper over [`WalletSource`] that implements [`CoinSelection`] by preferring UTXOs that would
@@ -600,7 +600,7 @@ where
600600
L::Target: Logger
601601
{
602602
fn select_confirmed_utxos(
603-
&self, claim_id: ClaimId, must_spend: &[Input], must_pay_to: &[TxOut],
603+
&self, claim_id: ClaimId, must_spend: Vec<Input>, must_pay_to: &[TxOut],
604604
target_feerate_sat_per_1000_weight: u32,
605605
) -> Result<CoinSelection, ()> {
606606
let utxos = self.source.list_confirmed_utxos()?;
@@ -629,7 +629,7 @@ where
629629
.or_else(|_| do_coin_selection(true, true))
630630
}
631631

632-
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()> {
632+
fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
633633
self.source.sign_tx(tx)
634634
}
635635
}
@@ -726,7 +726,7 @@ where
726726
satisfaction_weight: commitment_tx.weight() as u64 + ANCHOR_INPUT_WITNESS_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT,
727727
}];
728728
let coin_selection = self.utxo_source.select_confirmed_utxos(
729-
claim_id, &must_spend, &[], anchor_target_feerate_sat_per_1000_weight,
729+
claim_id, must_spend, &[], anchor_target_feerate_sat_per_1000_weight,
730730
)?;
731731

732732
let mut anchor_tx = Transaction {
@@ -748,7 +748,8 @@ where
748748
let unsigned_tx_weight = anchor_tx.weight() as u64 - (anchor_tx.input.len() as u64 * EMPTY_SCRIPT_SIG_WEIGHT);
749749

750750
log_debug!(self.logger, "Signing anchor transaction {}", anchor_txid);
751-
self.utxo_source.sign_tx(&mut anchor_tx)?;
751+
anchor_tx = self.utxo_source.sign_tx(anchor_tx)?;
752+
752753
let signer = anchor_descriptor.derive_channel_signer(&self.signer_provider);
753754
let anchor_sig = signer.sign_holder_anchor_input(&anchor_tx, 0, &self.secp)?;
754755
anchor_tx.input[0].witness = anchor_descriptor.tx_input_witness(&anchor_sig);
@@ -799,20 +800,24 @@ where
799800

800801
log_debug!(self.logger, "Peforming coin selection for HTLC transaction targeting {} sat/kW",
801802
target_feerate_sat_per_1000_weight);
803+
#[cfg(debug_assertions)]
804+
let must_spend_satisfaction_weight =
805+
must_spend.iter().map(|input| input.satisfaction_weight).sum::<u64>();
802806
let coin_selection = self.utxo_source.select_confirmed_utxos(
803-
claim_id, &must_spend, &htlc_tx.output, target_feerate_sat_per_1000_weight,
807+
claim_id, must_spend, &htlc_tx.output, target_feerate_sat_per_1000_weight,
804808
)?;
805809
#[cfg(debug_assertions)]
806810
let total_satisfaction_weight =
807811
coin_selection.confirmed_utxos.iter().map(|utxo| utxo.satisfaction_weight).sum::<u64>() +
808-
must_spend.iter().map(|input| input.satisfaction_weight).sum::<u64>();
812+
must_spend_satisfaction_weight;
809813
self.process_coin_selection(&mut htlc_tx, coin_selection);
810814

811815
#[cfg(debug_assertions)]
812816
let unsigned_tx_weight = htlc_tx.weight() as u64 - (htlc_tx.input.len() as u64 * EMPTY_SCRIPT_SIG_WEIGHT);
813817

814818
log_debug!(self.logger, "Signing HTLC transaction {}", htlc_tx.txid());
815-
self.utxo_source.sign_tx(&mut htlc_tx)?;
819+
htlc_tx = self.utxo_source.sign_tx(htlc_tx)?;
820+
816821
let mut signers = BTreeMap::new();
817822
for (idx, htlc_descriptor) in htlc_descriptors.iter().enumerate() {
818823
let signer = signers.entry(htlc_descriptor.channel_derivation_parameters.keys_id)

lightning/src/ln/outbound_payment.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -669,7 +669,7 @@ impl OutboundPayments {
669669

670670
let route = router.find_route_with_id(
671671
&node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
672-
Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
672+
Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
673673
payment_hash, payment_id,
674674
).map_err(|_| RetryableSendFailure::RouteNotFound)?;
675675

@@ -712,7 +712,7 @@ impl OutboundPayments {
712712

713713
let route = match router.find_route_with_id(
714714
&node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
715-
Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
715+
Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
716716
payment_hash, payment_id,
717717
) {
718718
Ok(route) => route,

lightning/src/ln/payment_tests.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -3218,7 +3218,7 @@ fn do_claim_from_closed_chan(fail_payment: bool) {
32183218
final_value_msat: 10_000_000,
32193219
};
32203220
let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
3221-
None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
3221+
None, nodes[0].node.compute_inflight_htlcs()).unwrap();
32223222
// Make sure the route is ordered as the B->D path before C->D
32233223
route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
32243224
std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });

lightning/src/routing/router.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Sco
6464
payer: &PublicKey,
6565
params: &RouteParameters,
6666
first_hops: Option<&[&ChannelDetails]>,
67-
inflight_htlcs: &InFlightHtlcs
67+
inflight_htlcs: InFlightHtlcs
6868
) -> Result<Route, LightningError> {
6969
let random_seed_bytes = {
7070
let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
@@ -73,7 +73,7 @@ impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Sco
7373
};
7474
find_route(
7575
payer, params, &self.network_graph, first_hops, &*self.logger,
76-
&ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().deref_mut(), inflight_htlcs),
76+
&ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().deref_mut(), &inflight_htlcs),
7777
&self.score_params,
7878
&random_seed_bytes
7979
)
@@ -85,13 +85,13 @@ pub trait Router {
8585
/// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
8686
fn find_route(
8787
&self, payer: &PublicKey, route_params: &RouteParameters,
88-
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
88+
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
8989
) -> Result<Route, LightningError>;
9090
/// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
9191
/// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
9292
fn find_route_with_id(
9393
&self, payer: &PublicKey, route_params: &RouteParameters,
94-
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
94+
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
9595
_payment_hash: PaymentHash, _payment_id: PaymentId
9696
) -> Result<Route, LightningError> {
9797
self.find_route(payer, route_params, first_hops, inflight_htlcs)
@@ -112,7 +112,7 @@ pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score<ScoreParams = SP>, SP:
112112

113113
impl<'a, S: Score<ScoreParams = SP>, SP: Sized> ScorerAccountingForInFlightHtlcs<'a, S, SP> {
114114
/// Initialize a new `ScorerAccountingForInFlightHtlcs`.
115-
pub fn new(scorer: &'a mut S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
115+
pub fn new(scorer: &'a mut S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
116116
ScorerAccountingForInFlightHtlcs {
117117
scorer,
118118
inflight_htlcs

lightning/src/routing/scoring.rs

+2-15
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ pub trait WriteableScore<'a>: LockableScore<'a> + Writeable {}
175175

176176
#[cfg(not(c_bindings))]
177177
impl<'a, T> WriteableScore<'a> for T where T: LockableScore<'a> + Writeable {}
178-
/// This is not exported to bindings users
178+
#[cfg(not(c_bindings))]
179179
impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
180180
type Score = T;
181181
type Locked = MutexGuard<'a, T>;
@@ -185,6 +185,7 @@ impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
185185
}
186186
}
187187

188+
#[cfg(not(c_bindings))]
188189
impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
189190
type Score = T;
190191
type Locked = RefMut<'a, T>;
@@ -255,21 +256,7 @@ impl<'a, T: 'a + Score> Deref for MultiThreadedScoreLock<'a, T> {
255256
}
256257
}
257258

258-
#[cfg(c_bindings)]
259-
/// This is not exported to bindings users
260-
impl<'a, T: Writeable> Writeable for RefMut<'a, T> {
261-
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
262-
T::write(&**self, writer)
263-
}
264-
}
265259

266-
#[cfg(c_bindings)]
267-
/// This is not exported to bindings users
268-
impl<'a, S: Writeable> Writeable for MutexGuard<'a, S> {
269-
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
270-
S::write(&**self, writer)
271-
}
272-
}
273260

274261
/// Proposed use of a channel passed as a parameter to [`Score::channel_penalty_msat`].
275262
#[derive(Clone, Copy, Debug, PartialEq)]

lightning/src/util/test_utils.rs

+10-10
Original file line numberDiff line numberDiff line change
@@ -112,13 +112,13 @@ impl<'a> TestRouter<'a> {
112112
impl<'a> Router for TestRouter<'a> {
113113
fn find_route(
114114
&self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
115-
inflight_htlcs: &InFlightHtlcs
115+
inflight_htlcs: InFlightHtlcs
116116
) -> Result<Route, msgs::LightningError> {
117117
if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
118118
assert_eq!(find_route_query, *params);
119119
if let Ok(ref route) = find_route_res {
120120
let mut binding = self.scorer.lock().unwrap();
121-
let scorer = ScorerAccountingForInFlightHtlcs::new(binding.deref_mut(), inflight_htlcs);
121+
let scorer = ScorerAccountingForInFlightHtlcs::new(binding.deref_mut(), &inflight_htlcs);
122122
for path in &route.paths {
123123
let mut aggregate_msat = 0u64;
124124
for (idx, hop) in path.hops.iter().rev().enumerate() {
@@ -1105,20 +1105,20 @@ impl TestWalletSource {
11051105
}
11061106

11071107
impl WalletSource for TestWalletSource {
1108-
fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
1108+
fn list_confirmed_utxos(&self) -> Result<Vec<Utxo>, ()> {
11091109
Ok(self.utxos.borrow().clone())
1110-
}
1110+
}
11111111

1112-
fn get_change_script(&self) -> Result<Script, ()> {
1112+
fn get_change_script(&self) -> Result<Script, ()> {
11131113
let public_key = bitcoin::PublicKey::new(self.secret_key.public_key(&self.secp));
11141114
Ok(Script::new_p2pkh(&public_key.pubkey_hash()))
1115-
}
1115+
}
11161116

1117-
fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()> {
1117+
fn sign_tx(&self, mut tx: Transaction) -> Result<Transaction, ()> {
11181118
let utxos = self.utxos.borrow();
11191119
for i in 0..tx.input.len() {
11201120
if let Some(utxo) = utxos.iter().find(|utxo| utxo.outpoint == tx.input[i].previous_output) {
1121-
let sighash = SighashCache::new(&*tx)
1121+
let sighash = SighashCache::new(&tx)
11221122
.legacy_signature_hash(i, &utxo.output.script_pubkey, EcdsaSighashType::All as u32)
11231123
.map_err(|_| ())?;
11241124
let sig = self.secp.sign_ecdsa(&sighash.as_hash().into(), &self.secret_key);
@@ -1129,6 +1129,6 @@ impl WalletSource for TestWalletSource {
11291129
.into_script();
11301130
}
11311131
}
1132-
Ok(())
1133-
}
1132+
Ok(tx)
1133+
}
11341134
}

0 commit comments

Comments
 (0)