Skip to content

Assorted 0.0.116 Bindings updates #2430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
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 fuzz/src/chanmon_consistency.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ struct FuzzRouter {}
impl Router for FuzzRouter {
fn find_route(
&self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
_inflight_htlcs: &InFlightHtlcs
_inflight_htlcs: InFlightHtlcs
) -> Result<Route, msgs::LightningError> {
Err(msgs::LightningError {
err: String::from("Not implemented"),
Expand Down
2 changes: 1 addition & 1 deletion fuzz/src/full_stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ struct FuzzRouter {}
impl Router for FuzzRouter {
fn find_route(
&self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>,
_inflight_htlcs: &InFlightHtlcs
_inflight_htlcs: InFlightHtlcs
) -> Result<Route, msgs::LightningError> {
Err(msgs::LightningError {
err: String::from("Not implemented"),
Expand Down
35 changes: 20 additions & 15 deletions lightning/src/events/bump_transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::ln::chan_utils::{
use crate::ln::features::ChannelTypeFeatures;
use crate::ln::PaymentPreimage;
use crate::prelude::*;
use crate::sign::{ChannelSigner, EcdsaChannelSigner, SignerProvider};
use crate::sign::{ChannelSigner, EcdsaChannelSigner, SignerProvider, WriteableEcdsaChannelSigner};
use crate::sync::Mutex;
use crate::util::logger::Logger;

Expand Down Expand Up @@ -102,9 +102,9 @@ impl AnchorDescriptor {
}

/// Derives the channel signer required to sign the anchor input.
pub fn derive_channel_signer<SP: Deref>(&self, signer_provider: &SP) -> <SP::Target as SignerProvider>::Signer
pub fn derive_channel_signer<S: WriteableEcdsaChannelSigner, SP: Deref>(&self, signer_provider: &SP) -> S
where
SP::Target: SignerProvider
SP::Target: SignerProvider<Signer = S>
{
let mut signer = signer_provider.derive_channel_signer(
self.channel_derivation_parameters.value_satoshis,
Expand Down Expand Up @@ -211,9 +211,9 @@ impl HTLCDescriptor {
}

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

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

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

fn sign_tx(&self, tx: &mut Transaction) -> Result<(), ()> {
fn sign_tx(&self, tx: Transaction) -> Result<Transaction, ()> {
self.source.sign_tx(tx)
}
}
Expand Down Expand Up @@ -726,7 +726,7 @@ where
satisfaction_weight: commitment_tx.weight() as u64 + ANCHOR_INPUT_WITNESS_WEIGHT + EMPTY_SCRIPT_SIG_WEIGHT,
}];
let coin_selection = self.utxo_source.select_confirmed_utxos(
claim_id, &must_spend, &[], anchor_target_feerate_sat_per_1000_weight,
claim_id, must_spend, &[], anchor_target_feerate_sat_per_1000_weight,
)?;

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

log_debug!(self.logger, "Signing anchor transaction {}", anchor_txid);
self.utxo_source.sign_tx(&mut anchor_tx)?;
anchor_tx = self.utxo_source.sign_tx(anchor_tx)?;

let signer = anchor_descriptor.derive_channel_signer(&self.signer_provider);
let anchor_sig = signer.sign_holder_anchor_input(&anchor_tx, 0, &self.secp)?;
anchor_tx.input[0].witness = anchor_descriptor.tx_input_witness(&anchor_sig);
Expand Down Expand Up @@ -799,20 +800,24 @@ where

log_debug!(self.logger, "Peforming coin selection for HTLC transaction targeting {} sat/kW",
target_feerate_sat_per_1000_weight);
#[cfg(debug_assertions)]
let must_spend_satisfaction_weight =
must_spend.iter().map(|input| input.satisfaction_weight).sum::<u64>();
let coin_selection = self.utxo_source.select_confirmed_utxos(
claim_id, &must_spend, &htlc_tx.output, target_feerate_sat_per_1000_weight,
claim_id, must_spend, &htlc_tx.output, target_feerate_sat_per_1000_weight,
)?;
#[cfg(debug_assertions)]
let total_satisfaction_weight =
coin_selection.confirmed_utxos.iter().map(|utxo| utxo.satisfaction_weight).sum::<u64>() +
must_spend.iter().map(|input| input.satisfaction_weight).sum::<u64>();
must_spend_satisfaction_weight;
self.process_coin_selection(&mut htlc_tx, coin_selection);

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

log_debug!(self.logger, "Signing HTLC transaction {}", htlc_tx.txid());
self.utxo_source.sign_tx(&mut htlc_tx)?;
htlc_tx = self.utxo_source.sign_tx(htlc_tx)?;

let mut signers = BTreeMap::new();
for (idx, htlc_descriptor) in htlc_descriptors.iter().enumerate() {
let signer = signers.entry(htlc_descriptor.channel_derivation_parameters.keys_id)
Expand Down
4 changes: 2 additions & 2 deletions lightning/src/ln/outbound_payment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -669,7 +669,7 @@ impl OutboundPayments {

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

Expand Down Expand Up @@ -712,7 +712,7 @@ impl OutboundPayments {

let route = match router.find_route_with_id(
&node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
payment_hash, payment_id,
) {
Ok(route) => route,
Expand Down
2 changes: 1 addition & 1 deletion lightning/src/ln/payment_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3218,7 +3218,7 @@ fn do_claim_from_closed_chan(fail_payment: bool) {
final_value_msat: 10_000_000,
};
let mut route = nodes[0].router.find_route(&nodes[0].node.get_our_node_id(), &route_params,
None, &nodes[0].node.compute_inflight_htlcs()).unwrap();
None, nodes[0].node.compute_inflight_htlcs()).unwrap();
// Make sure the route is ordered as the B->D path before C->D
route.paths.sort_by(|a, _| if a.hops[0].pubkey == nodes[1].node.get_our_node_id() {
std::cmp::Ordering::Less } else { std::cmp::Ordering::Greater });
Expand Down
10 changes: 5 additions & 5 deletions lightning/src/routing/router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Sco
payer: &PublicKey,
params: &RouteParameters,
first_hops: Option<&[&ChannelDetails]>,
inflight_htlcs: &InFlightHtlcs
inflight_htlcs: InFlightHtlcs
) -> Result<Route, LightningError> {
let random_seed_bytes = {
let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
Expand All @@ -73,7 +73,7 @@ impl< G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref, SP: Sized, Sc: Sco
};
find_route(
payer, params, &self.network_graph, first_hops, &*self.logger,
&ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().deref_mut(), inflight_htlcs),
&ScorerAccountingForInFlightHtlcs::new(self.scorer.lock().deref_mut(), &inflight_htlcs),
&self.score_params,
&random_seed_bytes
)
Expand All @@ -85,13 +85,13 @@ pub trait Router {
/// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
fn find_route(
&self, payer: &PublicKey, route_params: &RouteParameters,
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
) -> Result<Route, LightningError>;
/// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
/// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment.
fn find_route_with_id(
&self, payer: &PublicKey, route_params: &RouteParameters,
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: &InFlightHtlcs,
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
_payment_hash: PaymentHash, _payment_id: PaymentId
) -> Result<Route, LightningError> {
self.find_route(payer, route_params, first_hops, inflight_htlcs)
Expand All @@ -112,7 +112,7 @@ pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score<ScoreParams = SP>, SP:

impl<'a, S: Score<ScoreParams = SP>, SP: Sized> ScorerAccountingForInFlightHtlcs<'a, S, SP> {
/// Initialize a new `ScorerAccountingForInFlightHtlcs`.
pub fn new(scorer: &'a mut S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
pub fn new(scorer: &'a mut S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
ScorerAccountingForInFlightHtlcs {
scorer,
inflight_htlcs
Expand Down
17 changes: 2 additions & 15 deletions lightning/src/routing/scoring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ pub trait WriteableScore<'a>: LockableScore<'a> + Writeable {}

#[cfg(not(c_bindings))]
impl<'a, T> WriteableScore<'a> for T where T: LockableScore<'a> + Writeable {}
/// This is not exported to bindings users
#[cfg(not(c_bindings))]
impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
type Score = T;
type Locked = MutexGuard<'a, T>;
Expand All @@ -185,6 +185,7 @@ impl<'a, T: 'a + Score> LockableScore<'a> for Mutex<T> {
}
}

#[cfg(not(c_bindings))]
impl<'a, T: 'a + Score> LockableScore<'a> for RefCell<T> {
type Score = T;
type Locked = RefMut<'a, T>;
Expand Down Expand Up @@ -255,21 +256,7 @@ impl<'a, T: 'a + Score> Deref for MultiThreadedScoreLock<'a, T> {
}
}

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

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

/// Proposed use of a channel passed as a parameter to [`Score::channel_penalty_msat`].
#[derive(Clone, Copy, Debug, PartialEq)]
Expand Down
20 changes: 10 additions & 10 deletions lightning/src/util/test_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,13 @@ impl<'a> TestRouter<'a> {
impl<'a> Router for TestRouter<'a> {
fn find_route(
&self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&channelmanager::ChannelDetails]>,
inflight_htlcs: &InFlightHtlcs
inflight_htlcs: InFlightHtlcs
) -> Result<Route, msgs::LightningError> {
if let Some((find_route_query, find_route_res)) = self.next_routes.lock().unwrap().pop_front() {
assert_eq!(find_route_query, *params);
if let Ok(ref route) = find_route_res {
let mut binding = self.scorer.lock().unwrap();
let scorer = ScorerAccountingForInFlightHtlcs::new(binding.deref_mut(), inflight_htlcs);
let scorer = ScorerAccountingForInFlightHtlcs::new(binding.deref_mut(), &inflight_htlcs);
for path in &route.paths {
let mut aggregate_msat = 0u64;
for (idx, hop) in path.hops.iter().rev().enumerate() {
Expand Down Expand Up @@ -1105,20 +1105,20 @@ impl TestWalletSource {
}

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

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

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