1010use bitcoin::amount::Amount;
1111use bitcoin::constants::ChainHash;
1212use bitcoin::script::{Script, ScriptBuf, Builder};
13- use bitcoin::transaction::Transaction;
13+ use bitcoin::transaction::{ Transaction, TxIn, TxOut} ;
1414use bitcoin::sighash;
1515use bitcoin::sighash::EcdsaSighashType;
1616use bitcoin::consensus::encode;
17+ use bitcoin::absolute::LockTime;
1718
1819use bitcoin::hashes::Hash;
1920use bitcoin::hashes::sha256::Hash as Sha256;
@@ -27,7 +28,11 @@ use bitcoin::secp256k1;
2728
2829use crate::ln::types::{ChannelId, PaymentPreimage, PaymentHash};
2930use crate::ln::features::{ChannelTypeFeatures, InitFeatures};
30- use crate::ln::interactivetxs::InteractiveTxConstructor;
31+ use crate::ln::interactivetxs::{
32+ estimate_input_weight, get_output_weight, HandleTxCompleteResult,
33+ InteractiveTxConstructor, InteractiveTxConstructorArgs, InteractiveTxMessageSend,
34+ InteractiveTxMessageSendResult, TX_COMMON_FIELDS_WEIGHT,
35+ };
3136use crate::ln::msgs;
3237use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
3338use crate::ln::script::{self, ShutdownScript};
@@ -44,14 +49,14 @@ use crate::ln::chan_utils::{
4449use crate::ln::chan_utils;
4550use crate::ln::onion_utils::HTLCFailReason;
4651use crate::chain::BestBlock;
47- use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator};
52+ use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator, fee_for_weight };
4853use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS, CLOSED_CHANNEL_UPDATE_ID};
4954use crate::chain::transaction::{OutPoint, TransactionData};
5055use crate::sign::ecdsa::EcdsaChannelSigner;
5156use crate::sign::{EntropySource, ChannelSigner, SignerProvider, NodeSigner, Recipient};
5257use crate::events::ClosureReason;
5358use crate::routing::gossip::NodeId;
54- use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
59+ use crate::util::ser::{Readable, ReadableArgs, TransactionU16LenLimited, Writeable, Writer};
5560use crate::util::logger::{Logger, Record, WithContext};
5661use crate::util::errors::APIError;
5762use crate::util::config::{UserConfig, ChannelConfig, LegacyChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits, MaxDustHTLCExposure};
@@ -1490,6 +1495,109 @@ pub(super) struct ChannelContext<SP: Deref> where SP::Target: SignerProvider {
14901495 blocked_monitor_updates: Vec<PendingChannelMonitorUpdate>,
14911496}
14921497
1498+ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider {
1499+ fn context(&self) -> &ChannelContext<SP>;
1500+
1501+ fn context_mut(&mut self) -> &mut ChannelContext<SP>;
1502+
1503+ fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor>;
1504+
1505+ fn dual_funding_context(&self) -> &DualFundingChannelContext;
1506+
1507+ fn set_interactive_tx_constructor(&mut self, interactive_tx_constructor: InteractiveTxConstructor);
1508+
1509+ fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
1510+ InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1511+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
1512+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1513+ None => Err(msgs::TxAbort {
1514+ channel_id: self.context().channel_id(),
1515+ data: b"No interactive transaction negotiation in progress".to_vec()
1516+ }),
1517+ })
1518+ }
1519+
1520+ fn tx_add_output(&mut self, msg: &msgs::TxAddOutput)-> InteractiveTxMessageSendResult {
1521+ InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1522+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_output(msg).map_err(
1523+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1524+ None => Err(msgs::TxAbort {
1525+ channel_id: self.context().channel_id(),
1526+ data: b"No interactive transaction negotiation in progress".to_vec()
1527+ }),
1528+ })
1529+ }
1530+
1531+ fn tx_remove_input(&mut self, msg: &msgs::TxRemoveInput)-> InteractiveTxMessageSendResult {
1532+ InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1533+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_remove_input(msg).map_err(
1534+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1535+ None => Err(msgs::TxAbort {
1536+ channel_id: self.context().channel_id(),
1537+ data: b"No interactive transaction negotiation in progress".to_vec()
1538+ }),
1539+ })
1540+ }
1541+
1542+ fn tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput)-> InteractiveTxMessageSendResult {
1543+ InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1544+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_remove_output(msg).map_err(
1545+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1546+ None => Err(msgs::TxAbort {
1547+ channel_id: self.context().channel_id(),
1548+ data: b"No interactive transaction negotiation in progress".to_vec()
1549+ }),
1550+ })
1551+ }
1552+
1553+ fn tx_complete(&mut self, msg: &msgs::TxComplete) -> HandleTxCompleteResult {
1554+ HandleTxCompleteResult(match self.interactive_tx_constructor_mut() {
1555+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_complete(msg).map_err(
1556+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1557+ None => Err(msgs::TxAbort {
1558+ channel_id: self.context().channel_id(),
1559+ data: b"No interactive transaction negotiation in progress".to_vec()
1560+ }),
1561+ })
1562+ }
1563+ }
1564+
1565+ impl<SP: Deref> InteractivelyFunded<SP> for OutboundV2Channel<SP> where SP::Target: SignerProvider {
1566+ fn context(&self) -> &ChannelContext<SP> {
1567+ &self.context
1568+ }
1569+ fn context_mut(&mut self) -> &mut ChannelContext<SP> {
1570+ &mut self.context
1571+ }
1572+ fn dual_funding_context(&self) -> &DualFundingChannelContext {
1573+ &self.dual_funding_context
1574+ }
1575+ fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1576+ &mut self.interactive_tx_constructor
1577+ }
1578+ fn set_interactive_tx_constructor(&mut self, interactive_tx_constructor: InteractiveTxConstructor) {
1579+ self.interactive_tx_constructor = Some(interactive_tx_constructor);
1580+ }
1581+ }
1582+
1583+ impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Target: SignerProvider {
1584+ fn context(&self) -> &ChannelContext<SP> {
1585+ &self.context
1586+ }
1587+ fn context_mut(&mut self) -> &mut ChannelContext<SP> {
1588+ &mut self.context
1589+ }
1590+ fn dual_funding_context(&self) -> &DualFundingChannelContext {
1591+ &self.dual_funding_context
1592+ }
1593+ fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1594+ &mut self.interactive_tx_constructor
1595+ }
1596+ fn set_interactive_tx_constructor(&mut self, interactive_tx_constructor: InteractiveTxConstructor) {
1597+ self.interactive_tx_constructor = Some(interactive_tx_constructor);
1598+ }
1599+ }
1600+
14931601impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
14941602 fn new_for_inbound_channel<'a, ES: Deref, F: Deref, L: Deref>(
14951603 fee_estimator: &'a LowerBoundedFeeEstimator<F>,
@@ -3620,6 +3728,16 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
36203728 self.channel_transaction_parameters.channel_type_features = self.channel_type.clone();
36213729 Ok(())
36223730 }
3731+
3732+ // Interactive transaction construction
3733+
3734+ pub fn tx_signatures(&self, msg: &msgs::TxSignatures) -> Result<InteractiveTxMessageSend, ChannelError> {
3735+ todo!();
3736+ }
3737+
3738+ pub fn tx_abort(&self, msg: &msgs::TxAbort) -> Result<InteractiveTxMessageSend, ChannelError> {
3739+ todo!();
3740+ }
36233741}
36243742
36253743// Internal utility functions for channels
@@ -3677,6 +3795,42 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
36773795 cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
36783796}
36793797
3798+ pub(super) fn calculate_our_funding_satoshis(
3799+ is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
3800+ funding_outputs: &[TxOut], funding_feerate_sat_per_1000_weight: u32,
3801+ holder_dust_limit_satoshis: u64,
3802+ ) -> Result<u64, APIError> {
3803+ let mut total_input_satoshis = 0u64;
3804+ let mut our_contributed_weight = 0u64;
3805+
3806+ for (idx, input) in funding_inputs.iter().enumerate() {
3807+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
3808+ total_input_satoshis = total_input_satoshis.saturating_add(output.value.to_sat());
3809+ our_contributed_weight = our_contributed_weight.saturating_add(estimate_input_weight(output).to_wu());
3810+ } else {
3811+ return Err(APIError::APIMisuseError {
3812+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
3813+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
3814+ }
3815+ }
3816+ our_contributed_weight = our_contributed_weight.saturating_add(funding_outputs.iter().fold(0u64, |weight, txout| {
3817+ weight.saturating_add(get_output_weight(&txout.script_pubkey).to_wu())
3818+ }));
3819+
3820+ // If we are the initiator, we must pay for weight of all common fields in the funding transaction.
3821+ if is_initiator {
3822+ our_contributed_weight = our_contributed_weight.saturating_add(TX_COMMON_FIELDS_WEIGHT);
3823+ }
3824+
3825+ let funding_satoshis = total_input_satoshis
3826+ .saturating_sub(fee_for_weight(funding_feerate_sat_per_1000_weight, our_contributed_weight));
3827+ if funding_satoshis < holder_dust_limit_satoshis {
3828+ Ok(0)
3829+ } else {
3830+ Ok(funding_satoshis)
3831+ }
3832+ }
3833+
36803834/// Context for dual-funded channels.
36813835pub(super) struct DualFundingChannelContext {
36823836 /// The amount in satoshis we will be contributing to the channel.
@@ -3685,9 +3839,15 @@ pub(super) struct DualFundingChannelContext {
36853839 pub their_funding_satoshis: u64,
36863840 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
36873841 /// to the current block height to align incentives against fee-sniping.
3688- pub funding_tx_locktime: u32 ,
3842+ pub funding_tx_locktime: LockTime ,
36893843 /// The feerate set by the initiator to be used for the funding transaction.
36903844 pub funding_feerate_sat_per_1000_weight: u32,
3845+ /// The funding inputs we will be contributing to the channel.
3846+ ///
3847+ /// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
3848+ /// minus any fees paid for our contributed weight. This means that change will never be generated
3849+ /// and the maximum value possible will go towards funding the channel.
3850+ pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
36913851}
36923852
36933853// Holder designates channel data owned for the benefit of the user client.
@@ -8249,8 +8409,9 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
82498409 pub fn new<ES: Deref, F: Deref, L: Deref>(
82508410 fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
82518411 counterparty_node_id: PublicKey, their_features: &InitFeatures, funding_satoshis: u64,
8252- user_id: u128, config: &UserConfig, current_chain_height: u32, outbound_scid_alias: u64,
8253- funding_confirmation_target: ConfirmationTarget, logger: L,
8412+ funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>, user_id: u128, config: &UserConfig,
8413+ current_chain_height: u32, outbound_scid_alias: u64, funding_confirmation_target: ConfirmationTarget,
8414+ logger: L,
82548415 ) -> Result<OutboundV2Channel<SP>, APIError>
82558416 where ES::Target: EntropySource,
82568417 F::Target: FeeEstimator,
@@ -8266,7 +8427,11 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
82668427 funding_satoshis, MIN_CHAN_DUST_LIMIT_SATOSHIS);
82678428
82688429 let funding_feerate_sat_per_1000_weight = fee_estimator.bounded_sat_per_1000_weight(funding_confirmation_target);
8269- let funding_tx_locktime = current_chain_height;
8430+ let funding_tx_locktime = LockTime::from_height(current_chain_height)
8431+ .map_err(|_| APIError::APIMisuseError {
8432+ err: format!(
8433+ "Provided current chain height of {} doesn't make sense for a height-based timelock for the funding transaction",
8434+ current_chain_height) })?;
82708435
82718436 let chan = Self {
82728437 context: ChannelContext::new_for_outbound_channel(
@@ -8294,6 +8459,7 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
82948459 their_funding_satoshis: 0,
82958460 funding_tx_locktime,
82968461 funding_feerate_sat_per_1000_weight,
8462+ our_funding_inputs: funding_inputs,
82978463 },
82988464 interactive_tx_constructor: None,
82998465 };
@@ -8358,7 +8524,7 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
83588524 },
83598525 funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
83608526 second_per_commitment_point,
8361- locktime: self.dual_funding_context.funding_tx_locktime,
8527+ locktime: self.dual_funding_context.funding_tx_locktime.to_consensus_u32() ,
83628528 require_confirmed_inputs: None,
83638529 }
83648530 }
@@ -8379,13 +8545,22 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
83798545 pub fn new<ES: Deref, F: Deref, L: Deref>(
83808546 fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
83818547 counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
8382- their_features: &InitFeatures, msg: &msgs::OpenChannelV2, funding_satoshis: u64, user_id: u128,
8383- config: &UserConfig, current_chain_height: u32, logger: &L,
8548+ their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
8549+ funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>, user_id: u128, config: &UserConfig,
8550+ current_chain_height: u32, logger: &L,
83848551 ) -> Result<InboundV2Channel<SP>, ChannelError>
83858552 where ES::Target: EntropySource,
83868553 F::Target: FeeEstimator,
83878554 L::Target: Logger,
83888555 {
8556+ let funding_satoshis = calculate_our_funding_satoshis(
8557+ false, &funding_inputs, &[], msg.funding_feerate_sat_per_1000_weight,
8558+ msg.common_fields.dust_limit_satoshis
8559+ ).map_err(|_| ChannelError::Close(
8560+ (
8561+ "Failed to accept channel".to_string(),
8562+ ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
8563+ )))?;
83898564 let channel_value_satoshis = funding_satoshis.saturating_add(msg.common_fields.funding_satoshis);
83908565 let counterparty_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
83918566 channel_value_satoshis, msg.common_fields.dust_limit_satoshis);
@@ -8434,19 +8609,43 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
84348609 &context.get_counterparty_pubkeys().revocation_basepoint);
84358610 context.channel_id = channel_id;
84368611
8437- let chan = Self {
8612+ let mut channel = Self {
84388613 context,
84398614 unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
84408615 dual_funding_context: DualFundingChannelContext {
84418616 our_funding_satoshis: funding_satoshis,
84428617 their_funding_satoshis: msg.common_fields.funding_satoshis,
8443- funding_tx_locktime: msg.locktime,
8618+ funding_tx_locktime: LockTime::from_consensus( msg.locktime) ,
84448619 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8620+ our_funding_inputs: funding_inputs,
84458621 },
84468622 interactive_tx_constructor: None,
84478623 };
84488624
8449- Ok(chan)
8625+ match InteractiveTxConstructor::new(
8626+ InteractiveTxConstructorArgs {
8627+ entropy_source,
8628+ channel_id: channel.context.channel_id,
8629+ feerate_sat_per_kw: channel.dual_funding_context.funding_feerate_sat_per_1000_weight,
8630+ funding_tx_locktime: channel.dual_funding_context.funding_tx_locktime,
8631+ is_initiator: false,
8632+ inputs_to_contribute: channel.dual_funding_context.our_funding_inputs.clone(),
8633+ outputs_to_contribute: Vec::new(),
8634+ expected_remote_shared_funding_output: Some((channel.context().get_funding_redeemscript(), channel.context().channel_value_satoshis)),
8635+ }
8636+ ) {
8637+ Ok(tx_constructor) => {
8638+ channel.set_interactive_tx_constructor(tx_constructor);
8639+ },
8640+ Err(_) => {
8641+ return Err(ChannelError::Close((
8642+ "V2 channel rejected due to sender error".into(),
8643+ ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
8644+ )))
8645+ }
8646+ }
8647+
8648+ Ok(channel)
84508649 }
84518650
84528651 /// Marks an inbound channel as accepted and generates a [`msgs::AcceptChannelV2`] message which
0 commit comments