Skip to content

Commit 0448cf9

Browse files
committed
Add begin_interactive_funding_tx_construction()
1 parent 8a54da6 commit 0448cf9

File tree

2 files changed

+345
-18
lines changed

2 files changed

+345
-18
lines changed

lightning/src/ln/channel.rs

+155-11
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
use bitcoin::amount::Amount;
1111
use bitcoin::constants::ChainHash;
1212
use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
13-
use bitcoin::transaction::{Transaction, TxIn};
13+
use bitcoin::transaction::{Transaction, TxIn, TxOut};
1414
use bitcoin::sighash;
1515
use bitcoin::sighash::EcdsaSighashType;
1616
use bitcoin::consensus::encode;
@@ -31,9 +31,9 @@ use crate::ln::types::ChannelId;
3131
use crate::types::payment::{PaymentPreimage, PaymentHash};
3232
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
3333
use crate::ln::interactivetxs::{
34-
get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35-
InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36-
TX_COMMON_FIELDS_WEIGHT,
34+
get_output_weight, need_to_add_funding_change_output, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
35+
InteractiveTxConstructorArgs, InteractiveTxMessageSend, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
36+
OutputOwned, SharedOwnedOutput, TX_COMMON_FIELDS_WEIGHT,
3737
};
3838
use crate::ln::msgs;
3939
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
@@ -1161,6 +1161,7 @@ impl<'a, SP: Deref> ChannelPhase<SP> where
11611161
}
11621162

11631163
/// Contains all state common to unfunded inbound/outbound channels.
1164+
#[derive(Default)]
11641165
pub(super) struct UnfundedChannelContext {
11651166
/// A counter tracking how many ticks have elapsed since this unfunded channel was
11661167
/// created. If this unfunded channel reaches peer has yet to respond after reaching
@@ -1684,6 +1685,93 @@ pub(super) trait InteractivelyFunded<SP: Deref> where SP::Target: SignerProvider
16841685

16851686
fn dual_funding_context(&self) -> &DualFundingChannelContext;
16861687

1688+
fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext;
1689+
1690+
fn is_initiator(&self) -> bool;
1691+
1692+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled
1693+
fn begin_interactive_funding_tx_construction<ES: Deref>(
1694+
&mut self, signer_provider: &SP, entropy_source: &ES, holder_node_id: PublicKey,
1695+
extra_input: Option<(TxIn, TransactionU16LenLimited)>,
1696+
) -> Result<Option<InteractiveTxMessageSend>, APIError>
1697+
where ES::Target: EntropySource
1698+
{
1699+
let mut funding_inputs_with_extra = self.dual_funding_context_mut().our_funding_inputs.take().unwrap_or_else(|| vec![]);
1700+
1701+
if let Some(extra_input) = extra_input {
1702+
funding_inputs_with_extra.push(extra_input);
1703+
}
1704+
1705+
let mut funding_inputs_prev_outputs: Vec<TxOut> = Vec::with_capacity(funding_inputs_with_extra.len());
1706+
// Check that vouts exist for each TxIn in provided transactions.
1707+
for (idx, input) in funding_inputs_with_extra.iter().enumerate() {
1708+
if let Some(output) = input.1.as_transaction().output.get(input.0.previous_output.vout as usize) {
1709+
funding_inputs_prev_outputs.push(output.clone());
1710+
} else {
1711+
return Err(APIError::APIMisuseError {
1712+
err: format!("Transaction with txid {} does not have an output with vout of {} corresponding to TxIn at funding_inputs_with_extra[{}]",
1713+
input.1.as_transaction().compute_txid(), input.0.previous_output.vout, idx) });
1714+
}
1715+
}
1716+
1717+
let total_input_satoshis: u64 = funding_inputs_with_extra.iter().map(
1718+
|input| input.1.as_transaction().output.get(input.0.previous_output.vout as usize).map(|out| out.value.to_sat()).unwrap_or(0)
1719+
).sum();
1720+
if total_input_satoshis < self.dual_funding_context().our_funding_satoshis {
1721+
return Err(APIError::APIMisuseError {
1722+
err: format!("Total value of funding inputs must be at least funding amount. It was {} sats",
1723+
total_input_satoshis) });
1724+
}
1725+
1726+
// Add output for funding tx
1727+
let mut funding_outputs = Vec::new();
1728+
let funding_output_value_satoshis = self.context().get_value_satoshis();
1729+
let funding_output_script_pubkey = self.context().get_funding_redeemscript().to_p2wsh();
1730+
let expected_remote_shared_funding_output = if self.is_initiator() {
1731+
let tx_out = TxOut {
1732+
value: Amount::from_sat(funding_output_value_satoshis),
1733+
script_pubkey: funding_output_script_pubkey,
1734+
};
1735+
funding_outputs.push(
1736+
if self.dual_funding_context().their_funding_satoshis.unwrap_or(0) == 0 {
1737+
OutputOwned::SharedControlFullyOwned(tx_out)
1738+
} else {
1739+
OutputOwned::Shared(SharedOwnedOutput::new(
1740+
tx_out, self.dual_funding_context().our_funding_satoshis
1741+
))
1742+
}
1743+
);
1744+
None
1745+
} else {
1746+
Some((funding_output_script_pubkey, funding_output_value_satoshis))
1747+
};
1748+
1749+
maybe_add_funding_change_output(signer_provider, self.is_initiator(), self.dual_funding_context().our_funding_satoshis,
1750+
&funding_inputs_prev_outputs, &mut funding_outputs, self.dual_funding_context().funding_feerate_sat_per_1000_weight,
1751+
self.context().holder_dust_limit_satoshis, self.context().channel_keys_id).map_err(
1752+
|err| APIError::APIMisuseError { err: format!("Could not create change output, {:?}", err)})?;
1753+
1754+
let constructor_args = InteractiveTxConstructorArgs {
1755+
entropy_source,
1756+
holder_node_id,
1757+
counterparty_node_id: self.context().counterparty_node_id,
1758+
channel_id: self.context().channel_id(),
1759+
feerate_sat_per_kw: self.dual_funding_context_mut().funding_feerate_sat_per_1000_weight,
1760+
is_initiator: self.is_initiator(),
1761+
funding_tx_locktime: self.dual_funding_context_mut().funding_tx_locktime,
1762+
inputs_to_contribute: funding_inputs_with_extra,
1763+
outputs_to_contribute: funding_outputs,
1764+
expected_remote_shared_funding_output,
1765+
};
1766+
let mut tx_constructor = InteractiveTxConstructor::new(constructor_args)
1767+
.map_err(|_| APIError::APIMisuseError { err: "Incorrect shared output provided".into() })?;
1768+
let msg = tx_constructor.take_initiator_first_message();
1769+
1770+
self.interactive_tx_constructor_mut().replace(tx_constructor);
1771+
1772+
Ok(msg)
1773+
}
1774+
16871775
fn tx_add_input(&mut self, msg: &msgs::TxAddInput) -> InteractiveTxMessageSendResult {
16881776
InteractiveTxMessageSendResult(match self.interactive_tx_constructor_mut() {
16891777
Some(ref mut tx_constructor) => tx_constructor.handle_tx_add_input(msg).map_err(
@@ -1846,9 +1934,17 @@ impl<SP: Deref> InteractivelyFunded<SP> for OutboundV2Channel<SP> where SP::Targ
18461934
fn dual_funding_context(&self) -> &DualFundingChannelContext {
18471935
&self.dual_funding_context
18481936
}
1937+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1938+
fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1939+
&mut self.dual_funding_context
1940+
}
18491941
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
18501942
&mut self.interactive_tx_constructor
18511943
}
1944+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1945+
fn is_initiator(&self) -> bool {
1946+
true
1947+
}
18521948
}
18531949

18541950
impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Target: SignerProvider {
@@ -1861,9 +1957,17 @@ impl<SP: Deref> InteractivelyFunded<SP> for InboundV2Channel<SP> where SP::Targe
18611957
fn dual_funding_context(&self) -> &DualFundingChannelContext {
18621958
&self.dual_funding_context
18631959
}
1960+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1961+
fn dual_funding_context_mut(&mut self) -> &mut DualFundingChannelContext {
1962+
&mut self.dual_funding_context
1963+
}
18641964
fn interactive_tx_constructor_mut(&mut self) -> &mut Option<InteractiveTxConstructor> {
18651965
&mut self.interactive_tx_constructor
18661966
}
1967+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
1968+
fn is_initiator(&self) -> bool {
1969+
false
1970+
}
18671971
}
18681972

18691973
impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
@@ -4150,6 +4254,41 @@ fn get_v2_channel_reserve_satoshis(channel_value_satoshis: u64, dust_limit_satos
41504254
cmp::min(channel_value_satoshis, cmp::max(q, dust_limit_satoshis))
41514255
}
41524256

4257+
#[allow(dead_code)] // TODO(dual_funding): Remove once begin_interactive_funding_tx_construction() is used
4258+
fn maybe_add_funding_change_output<SP: Deref>(signer_provider: &SP, is_initiator: bool,
4259+
our_funding_satoshis: u64, funding_inputs_prev_outputs: &Vec<TxOut>,
4260+
funding_outputs: &mut Vec<OutputOwned>, funding_feerate_sat_per_1000_weight: u32,
4261+
holder_dust_limit_satoshis: u64, channel_keys_id: [u8; 32],
4262+
) -> Result<Option<TxOut>, ChannelError> where SP::Target: SignerProvider {
4263+
let remaining_value = match need_to_add_funding_change_output(
4264+
is_initiator, our_funding_satoshis, funding_inputs_prev_outputs,
4265+
funding_outputs, funding_feerate_sat_per_1000_weight, holder_dust_limit_satoshis
4266+
) {
4267+
None => {
4268+
// No need to add
4269+
return Ok(None);
4270+
}
4271+
Some(remaining_value) => remaining_value,
4272+
};
4273+
4274+
let change_script = signer_provider.get_destination_script(channel_keys_id).map_err(
4275+
|_| ChannelError::Close((
4276+
"Failed to get change script as new destination script".to_owned(),
4277+
ClosureReason::ProcessingError { err: "Failed to get change script as new destination script".to_owned() }
4278+
))
4279+
)?;
4280+
let mut change_output = TxOut {
4281+
value: Amount::from_sat(remaining_value),
4282+
script_pubkey: change_script,
4283+
};
4284+
let change_output_weight = get_output_weight(&change_output.script_pubkey).to_wu();
4285+
4286+
let change_output_fee = fee_for_weight(funding_feerate_sat_per_1000_weight, change_output_weight);
4287+
change_output.value = Amount::from_sat(remaining_value.saturating_sub(change_output_fee));
4288+
funding_outputs.push(OutputOwned::Single(change_output.clone()));
4289+
Ok(Some(change_output))
4290+
}
4291+
41534292
pub(super) fn calculate_our_funding_satoshis(
41544293
is_initiator: bool, funding_inputs: &[(TxIn, TransactionU16LenLimited)],
41554294
total_witness_weight: Weight, funding_feerate_sat_per_1000_weight: u32,
@@ -4195,6 +4334,9 @@ pub(super) fn calculate_our_funding_satoshis(
41954334
pub(super) struct DualFundingChannelContext {
41964335
/// The amount in satoshis we will be contributing to the channel.
41974336
pub our_funding_satoshis: u64,
4337+
/// The amount in satoshis our counterparty will be contributing to the channel.
4338+
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4339+
pub their_funding_satoshis: Option<u64>,
41984340
/// The funding transaction locktime suggested by the initiator. If set by us, it is always set
41994341
/// to the current block height to align incentives against fee-sniping.
42004342
pub funding_tx_locktime: LockTime,
@@ -4206,7 +4348,7 @@ pub(super) struct DualFundingChannelContext {
42064348
/// minus any fees paid for our contributed weight. This means that change will never be generated
42074349
/// and the maximum value possible will go towards funding the channel.
42084350
#[allow(dead_code)] // TODO(dual_funding): Remove once contribution to V2 channels is enabled.
4209-
pub our_funding_inputs: Vec<(TxIn, TransactionU16LenLimited)>,
4351+
pub our_funding_inputs: Option<Vec<(TxIn, TransactionU16LenLimited)>>,
42104352
}
42114353

42124354
// Holder designates channel data owned for the benefit of the user client.
@@ -8295,7 +8437,7 @@ impl<SP: Deref> OutboundV1Channel<SP> where SP::Target: SignerProvider {
82958437
pubkeys,
82968438
logger,
82978439
)?,
8298-
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 }
8440+
unfunded_context: UnfundedChannelContext::default(),
82998441
};
83008442
Ok(chan)
83018443
}
@@ -8599,7 +8741,7 @@ impl<SP: Deref> InboundV1Channel<SP> where SP::Target: SignerProvider {
85998741
msg.push_msat,
86008742
msg.common_fields.clone(),
86018743
)?,
8602-
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
8744+
unfunded_context: UnfundedChannelContext::default(),
86038745
};
86048746
Ok(chan)
86058747
}
@@ -8782,12 +8924,13 @@ impl<SP: Deref> OutboundV2Channel<SP> where SP::Target: SignerProvider {
87828924
pubkeys,
87838925
logger,
87848926
)?,
8785-
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
8927+
unfunded_context: UnfundedChannelContext::default(),
87868928
dual_funding_context: DualFundingChannelContext {
87878929
our_funding_satoshis: funding_satoshis,
8930+
their_funding_satoshis: None,
87888931
funding_tx_locktime,
87898932
funding_feerate_sat_per_1000_weight,
8790-
our_funding_inputs: funding_inputs,
8933+
our_funding_inputs: Some(funding_inputs),
87918934
},
87928935
interactive_tx_constructor: None,
87938936
};
@@ -8948,9 +9091,10 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
89489091

89499092
let dual_funding_context = DualFundingChannelContext {
89509093
our_funding_satoshis: funding_satoshis,
9094+
their_funding_satoshis: Some(msg.common_fields.funding_satoshis),
89519095
funding_tx_locktime: LockTime::from_consensus(msg.locktime),
89529096
funding_feerate_sat_per_1000_weight: msg.funding_feerate_sat_per_1000_weight,
8953-
our_funding_inputs: funding_inputs.clone(),
9097+
our_funding_inputs: Some(funding_inputs.clone()),
89549098
};
89559099

89569100
let interactive_tx_constructor = Some(InteractiveTxConstructor::new(
@@ -8975,7 +9119,7 @@ impl<SP: Deref> InboundV2Channel<SP> where SP::Target: SignerProvider {
89759119
context,
89769120
dual_funding_context,
89779121
interactive_tx_constructor,
8978-
unfunded_context: UnfundedChannelContext { unfunded_channel_age_ticks: 0 },
9122+
unfunded_context: UnfundedChannelContext::default(),
89799123
})
89809124
}
89819125

0 commit comments

Comments
 (0)