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};
@@ -1631,6 +1636,109 @@ impl<SP: Deref> InitialRemoteCommitmentReceiver<SP> for InboundV1Channel<SP> whe
16311636 }
16321637}
16331638
1639+ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider {
1640+ fn context(&self) -> &ChannelContext<SP>;
1641+
1642+ fn context_mut(&mut self) -> &mut ChannelContext<SP>;
1643+
1644+ fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor>;
1645+
1646+ fn dual_funding_context(&self) -> &DualFundingChannelContext;
1647+
1648+ fn set_interactive_tx_constructor(&mut self, interactive_tx_constructor: InteractiveTxConstructor);
1649+
1650+ fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
1651+ InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1652+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
1653+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1654+ None => Err(msgs::TxAbort {
1655+ channel_id: self.context().channel_id(),
1656+ data: b"No interactive transaction negotiation in progress".to_vec()
1657+ }),
1658+ })
1659+ }
1660+
1661+ fn tx_add_output(&mut self, msg: &msgs::TxAddOutput)-> InteractiveTxMessageSendResult {
1662+ InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1663+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_output(msg).map_err(
1664+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1665+ None => Err(msgs::TxAbort {
1666+ channel_id: self.context().channel_id(),
1667+ data: b"No interactive transaction negotiation in progress".to_vec()
1668+ }),
1669+ })
1670+ }
1671+
1672+ fn tx_remove_input(&mut self, msg: &msgs::TxRemoveInput)-> InteractiveTxMessageSendResult {
1673+ InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1674+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_remove_input(msg).map_err(
1675+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1676+ None => Err(msgs::TxAbort {
1677+ channel_id: self.context().channel_id(),
1678+ data: b"No interactive transaction negotiation in progress".to_vec()
1679+ }),
1680+ })
1681+ }
1682+
1683+ fn tx_remove_output(&mut self, msg: &msgs::TxRemoveOutput)-> InteractiveTxMessageSendResult {
1684+ InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
1685+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_remove_output(msg).map_err(
1686+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1687+ None => Err(msgs::TxAbort {
1688+ channel_id: self.context().channel_id(),
1689+ data: b"No interactive transaction negotiation in progress".to_vec()
1690+ }),
1691+ })
1692+ }
1693+
1694+ fn tx_complete(&mut self, msg: &msgs::TxComplete) -> HandleTxCompleteResult {
1695+ HandleTxCompleteResult(match self.interactive_tx_constructor_mut() {
1696+ Some(ref mut tx_constructor) => tx_constructor.handle_tx_complete(msg).map_err(
1697+ |reason| reason.into_tx_abort_msg(self.context().channel_id())),
1698+ None => Err(msgs::TxAbort {
1699+ channel_id: self.context().channel_id(),
1700+ data: b"No interactive transaction negotiation in progress".to_vec()
1701+ }),
1702+ })
1703+ }
1704+ }
1705+
1706+ impl<SP: Deref> InteractivelyFunded<SP> for OutboundV2Channel<SP> where SP::Target: SignerProvider {
1707+ fn context(&self) -> &ChannelContext<SP> {
1708+ &self.context
1709+ }
1710+ fn context_mut(&mut self) -> &mut ChannelContext<SP> {
1711+ &mut self.context
1712+ }
1713+ fn dual_funding_context(&self) -> &DualFundingChannelContext {
1714+ &self.dual_funding_context
1715+ }
1716+ fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1717+ &mut self.interactive_tx_constructor
1718+ }
1719+ fn set_interactive_tx_constructor(&mut self, interactive_tx_constructor: InteractiveTxConstructor) {
1720+ self.interactive_tx_constructor = Some(interactive_tx_constructor);
1721+ }
1722+ }
1723+
1724+ impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Target: SignerProvider {
1725+ fn context(&self) -> &ChannelContext<SP> {
1726+ &self.context
1727+ }
1728+ fn context_mut(&mut self) -> &mut ChannelContext<SP> {
1729+ &mut self.context
1730+ }
1731+ fn dual_funding_context(&self) -> &DualFundingChannelContext {
1732+ &self.dual_funding_context
1733+ }
1734+ fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
1735+ &mut self.interactive_tx_constructor
1736+ }
1737+ fn set_interactive_tx_constructor(&mut self, interactive_tx_constructor: InteractiveTxConstructor) {
1738+ self.interactive_tx_constructor = Some(interactive_tx_constructor);
1739+ }
1740+ }
1741+
16341742impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
16351743 fn new_for_inbound_channel<'a, ES: Deref, F: Deref, L: Deref>(
16361744 fee_estimator: &'a LowerBoundedFeeEstimator<F>,
@@ -3760,6 +3868,16 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
37603868 self.channel_transaction_parameters.channel_type_features = self.channel_type.clone();
37613869 Ok(())
37623870 }
3871+
3872+ // Interactive transaction construction
3873+
3874+ pub fn tx_signatures(&self, msg: &msgs::TxSignatures) -> Result<InteractiveTxMessageSend, ChannelError> {
3875+ todo!();
3876+ }
3877+
3878+ pub fn tx_abort(&self, msg: &msgs::TxAbort) -> Result<InteractiveTxMessageSend, ChannelError> {
3879+ todo!();
3880+ }
37633881}
37643882
37653883// Internal utility functions for channels
@@ -3817,6 +3935,42 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
38173935 cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
38183936}
38193937
3938+ pub(super) fn calculate_our_funding_satoshis(
3939+ is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
3940+ funding_outputs: &[TxOut], funding_feerate_sat_per_1000_weight: u32,
3941+ holder_dust_limit_satoshis: u64,
3942+ ) -> Result<u64, APIError> {
3943+ let mut total_input_satoshis = 0u64;
3944+ let mut our_contributed_weight = 0u64;
3945+
3946+ for (idx, input) in funding_inputs.iter().enumerate() {
3947+ if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
3948+ total_input_satoshis = total_input_satoshis.saturating_add(output.value.to_sat());
3949+ our_contributed_weight = our_contributed_weight.saturating_add(estimate_input_weight(output).to_wu());
3950+ } else {
3951+ return Err(APIError::APIMisuseError {
3952+ err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs[{}]",
3953+ input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
3954+ }
3955+ }
3956+ our_contributed_weight = our_contributed_weight.saturating_add(funding_outputs.iter().fold(0u64, |weight, txout| {
3957+ weight.saturating_add(get_output_weight(&txout.script_pubkey).to_wu())
3958+ }));
3959+
3960+ // If we are the initiator, we must pay for weight of all common fields in the funding transaction.
3961+ if is_initiator {
3962+ our_contributed_weight = our_contributed_weight.saturating_add(TX_COMMON_FIELDS_WEIGHT);
3963+ }
3964+
3965+ let funding_satoshis = total_input_satoshis
3966+ .saturating_sub(fee_for_weight(funding_feerate_sat_per_1000_weight, our_contributed_weight));
3967+ if funding_satoshis < holder_dust_limit_satoshis {
3968+ Ok(0)
3969+ } else {
3970+ Ok(funding_satoshis)
3971+ }
3972+ }
3973+
38203974/// Context for dual-funded channels.
38213975pub(super) struct DualFundingChannelContext {
38223976 /// The amount in satoshis we will be contributing to the channel.
@@ -3825,9 +3979,15 @@ pub(super) struct DualFundingChannelContext {
38253979 pub their_funding_satoshis: u64,
38263980 /// The funding transaction locktime suggested by the initiator. If set by us, it is always set
38273981 /// to the current block height to align incentives against fee-sniping.
3828- pub funding_tx_locktime: u32 ,
3982+ pub funding_tx_locktime: LockTime ,
38293983 /// The feerate set by the initiator to be used for the funding transaction.
38303984 pub funding_feerate_sat_per_1000_weight: u32,
3985+ /// The funding inputs we will be contributing to the channel.
3986+ ///
3987+ /// Note that the `our_funding_satoshis` field is equal to the total value of `our_funding_inputs`
3988+ /// minus any fees paid for our contributed weight. This means that change will never be generated
3989+ /// and the maximum value possible will go towards funding the channel.
3990+ pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
38313991}
38323992
38333993// Holder designates channel data owned for the benefit of the user client.
@@ -8273,8 +8433,9 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
82738433 pub fn new<ES: Deref, F: Deref, L: Deref>(
82748434 fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
82758435 counterparty_node_id: PublicKey, their_features: &InitFeatures, funding_satoshis: u64,
8276- user_id: u128, config: &UserConfig, current_chain_height: u32, outbound_scid_alias: u64,
8277- funding_confirmation_target: ConfirmationTarget, logger: L,
8436+ funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>, user_id: u128, config: &UserConfig,
8437+ current_chain_height: u32, outbound_scid_alias: u64, funding_confirmation_target: ConfirmationTarget,
8438+ logger: L,
82788439 ) -> Result<OutboundV2Channel<SP>, APIError>
82798440 where ES::Target: EntropySource,
82808441 F::Target: FeeEstimator,
@@ -8290,7 +8451,11 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
82908451 funding_satoshis, MIN_CHAN_DUST_LIMIT_SATOSHIS);
82918452
82928453 let funding_feerate_sat_per_1000_weight = fee_estimator.bounded_sat_per_1000_weight(funding_confirmation_target);
8293- let funding_tx_locktime = current_chain_height;
8454+ let funding_tx_locktime = LockTime::from_height(current_chain_height)
8455+ .map_err(|_| APIError::APIMisuseError {
8456+ err: format!(
8457+ "Provided current chain height of {} doesn't make sense for a height-based timelock for the funding transaction",
8458+ current_chain_height) })?;
82948459
82958460 let chan = Self {
82968461 context: ChannelContext::new_for_outbound_channel(
@@ -8318,6 +8483,7 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
83188483 their_funding_satoshis: 0,
83198484 funding_tx_locktime,
83208485 funding_feerate_sat_per_1000_weight,
8486+ our_funding_inputs: funding_inputs,
83218487 },
83228488 interactive_tx_constructor: None,
83238489 };
@@ -8382,7 +8548,7 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
83828548 },
83838549 funding_feerate_sat_per_1000_weight: self.context.feerate_per_kw,
83848550 second_per_commitment_point,
8385- locktime: self.dual_funding_context.funding_tx_locktime,
8551+ locktime: self.dual_funding_context.funding_tx_locktime.to_consensus_u32() ,
83868552 require_confirmed_inputs: None,
83878553 }
83888554 }
@@ -8403,13 +8569,22 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
84038569 pub fn new<ES: Deref, F: Deref, L: Deref>(
84048570 fee_estimator: &LowerBoundedFeeEstimator<F>, entropy_source: &ES, signer_provider: &SP,
84058571 counterparty_node_id: PublicKey, our_supported_features: &ChannelTypeFeatures,
8406- their_features: &InitFeatures, msg: &msgs::OpenChannelV2, funding_satoshis: u64, user_id: u128,
8407- config: &UserConfig, current_chain_height: u32, logger: &L,
8572+ their_features: &InitFeatures, msg: &msgs::OpenChannelV2,
8573+ funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>, user_id: u128, config: &UserConfig,
8574+ current_chain_height: u32, logger: &L,
84088575 ) -> Result<InboundV2Channel<SP>, ChannelError>
84098576 where ES::Target: EntropySource,
84108577 F::Target: FeeEstimator,
84118578 L::Target: Logger,
84128579 {
8580+ let funding_satoshis = calculate_our_funding_satoshis(
8581+ false, &funding_inputs, &[], msg.funding_feerate_sat_per_1000_weight,
8582+ msg.common_fields.dust_limit_satoshis
8583+ ).map_err(|_| ChannelError::Close(
8584+ (
8585+ "Failed to accept channel".to_string(),
8586+ ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
8587+ )))?;
84138588 let channel_value_satoshis = funding_satoshis.saturating_add(msg.common_fields.funding_satoshis);
84148589 let counterparty_selected_channel_reserve_satoshis = get_v2_channel_reserve_satoshis(
84158590 channel_value_satoshis, msg.common_fields.dust_limit_satoshis);
@@ -8458,19 +8633,43 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
84588633 &context.get_counterparty_pubkeys().revocation_basepoint);
84598634 context.channel_id = channel_id;
84608635
8461- let chan = Self {
8636+ let mut channel = Self {
84628637 context,
84638638 unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
84648639 dual_funding_context: DualFundingChannelContext {
84658640 our_funding_satoshis: funding_satoshis,
84668641 their_funding_satoshis: msg.common_fields.funding_satoshis,
8467- funding_tx_locktime: msg.locktime,
8642+ funding_tx_locktime: LockTime::from_consensus( msg.locktime) ,
84688643 funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8644+ our_funding_inputs: funding_inputs,
84698645 },
84708646 interactive_tx_constructor: None,
84718647 };
84728648
8473- Ok(chan)
8649+ match InteractiveTxConstructor::new(
8650+ InteractiveTxConstructorArgs {
8651+ entropy_source,
8652+ channel_id: channel.context.channel_id,
8653+ feerate_sat_per_kw: channel.dual_funding_context.funding_feerate_sat_per_1000_weight,
8654+ funding_tx_locktime: channel.dual_funding_context.funding_tx_locktime,
8655+ is_initiator: false,
8656+ inputs_to_contribute: channel.dual_funding_context.our_funding_inputs.clone(),
8657+ outputs_to_contribute: Vec::new(),
8658+ expected_remote_shared_funding_output: Some((channel.context().get_funding_redeemscript(), channel.context().channel_value_satoshis)),
8659+ }
8660+ ) {
8661+ Ok(tx_constructor) => {
8662+ channel.set_interactive_tx_constructor(tx_constructor);
8663+ },
8664+ Err(_) => {
8665+ return Err(ChannelError::Close((
8666+ "V2 channel rejected due to sender error".into(),
8667+ ClosureReason::HolderForceClosed { broadcasted_latest_txn: Some(false) },
8668+ )))
8669+ }
8670+ }
8671+
8672+ Ok(channel)
84748673 }
84758674
84768675 /// Marks an inbound channel as accepted and generates a [`msgs::AcceptChannelV2`] message which
0 commit comments